babylon.2.1-rc.debug.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.scale = function (scale) {
  56. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  57. };
  58. Color3.prototype.scaleToRef = function (scale, result) {
  59. result.r = this.r * scale;
  60. result.g = this.g * scale;
  61. result.b = this.b * scale;
  62. return this;
  63. };
  64. Color3.prototype.add = function (otherColor) {
  65. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  66. };
  67. Color3.prototype.addToRef = function (otherColor, result) {
  68. result.r = this.r + otherColor.r;
  69. result.g = this.g + otherColor.g;
  70. result.b = this.b + otherColor.b;
  71. return this;
  72. };
  73. Color3.prototype.subtract = function (otherColor) {
  74. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  75. };
  76. Color3.prototype.subtractToRef = function (otherColor, result) {
  77. result.r = this.r - otherColor.r;
  78. result.g = this.g - otherColor.g;
  79. result.b = this.b - otherColor.b;
  80. return this;
  81. };
  82. Color3.prototype.clone = function () {
  83. return new Color3(this.r, this.g, this.b);
  84. };
  85. Color3.prototype.copyFrom = function (source) {
  86. this.r = source.r;
  87. this.g = source.g;
  88. this.b = source.b;
  89. return this;
  90. };
  91. Color3.prototype.copyFromFloats = function (r, g, b) {
  92. this.r = r;
  93. this.g = g;
  94. this.b = b;
  95. return this;
  96. };
  97. // Statics
  98. Color3.FromArray = function (array, offset) {
  99. if (offset === void 0) { offset = 0; }
  100. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  101. };
  102. Color3.FromInts = function (r, g, b) {
  103. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  104. };
  105. Color3.Lerp = function (start, end, amount) {
  106. var r = start.r + ((end.r - start.r) * amount);
  107. var g = start.g + ((end.g - start.g) * amount);
  108. var b = start.b + ((end.b - start.b) * amount);
  109. return new Color3(r, g, b);
  110. };
  111. Color3.Red = function () { return new Color3(1, 0, 0); };
  112. Color3.Green = function () { return new Color3(0, 1, 0); };
  113. Color3.Blue = function () { return new Color3(0, 0, 1); };
  114. Color3.Black = function () { return new Color3(0, 0, 0); };
  115. Color3.White = function () { return new Color3(1, 1, 1); };
  116. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  117. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  118. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  119. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  120. return Color3;
  121. })();
  122. BABYLON.Color3 = Color3;
  123. var Color4 = (function () {
  124. function Color4(r, g, b, a) {
  125. this.r = r;
  126. this.g = g;
  127. this.b = b;
  128. this.a = a;
  129. }
  130. // Operators
  131. Color4.prototype.addInPlace = function (right) {
  132. this.r += right.r;
  133. this.g += right.g;
  134. this.b += right.b;
  135. this.a += right.a;
  136. return this;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. return this;
  152. };
  153. Color4.prototype.add = function (right) {
  154. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  155. };
  156. Color4.prototype.subtract = function (right) {
  157. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  158. };
  159. Color4.prototype.subtractToRef = function (right, result) {
  160. result.r = this.r - right.r;
  161. result.g = this.g - right.g;
  162. result.b = this.b - right.b;
  163. result.a = this.a - right.a;
  164. return this;
  165. };
  166. Color4.prototype.scale = function (scale) {
  167. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  168. };
  169. Color4.prototype.scaleToRef = function (scale, result) {
  170. result.r = this.r * scale;
  171. result.g = this.g * scale;
  172. result.b = this.b * scale;
  173. result.a = this.a * scale;
  174. return this;
  175. };
  176. Color4.prototype.toString = function () {
  177. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  178. };
  179. Color4.prototype.clone = function () {
  180. return new Color4(this.r, this.g, this.b, this.a);
  181. };
  182. Color4.prototype.copyFrom = function (source) {
  183. this.r = source.r;
  184. this.g = source.g;
  185. this.b = source.b;
  186. this.a = source.a;
  187. return this;
  188. };
  189. // Statics
  190. Color4.Lerp = function (left, right, amount) {
  191. var result = new Color4(0, 0, 0, 0);
  192. Color4.LerpToRef(left, right, amount, result);
  193. return result;
  194. };
  195. Color4.LerpToRef = function (left, right, amount, result) {
  196. result.r = left.r + (right.r - left.r) * amount;
  197. result.g = left.g + (right.g - left.g) * amount;
  198. result.b = left.b + (right.b - left.b) * amount;
  199. result.a = left.a + (right.a - left.a) * amount;
  200. };
  201. Color4.FromArray = function (array, offset) {
  202. if (offset === void 0) { offset = 0; }
  203. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  204. };
  205. Color4.FromInts = function (r, g, b, a) {
  206. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  207. };
  208. return Color4;
  209. })();
  210. BABYLON.Color4 = Color4;
  211. var Vector2 = (function () {
  212. function Vector2(x, y) {
  213. this.x = x;
  214. this.y = y;
  215. }
  216. Vector2.prototype.toString = function () {
  217. return "{X: " + this.x + " Y:" + this.y + "}";
  218. };
  219. // Operators
  220. Vector2.prototype.toArray = function (array, index) {
  221. if (index === void 0) { index = 0; }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. return this;
  225. };
  226. Vector2.prototype.asArray = function () {
  227. var result = [];
  228. this.toArray(result, 0);
  229. return result;
  230. };
  231. Vector2.prototype.copyFrom = function (source) {
  232. this.x = source.x;
  233. this.y = source.y;
  234. return this;
  235. };
  236. Vector2.prototype.copyFromFloats = function (x, y) {
  237. this.x = x;
  238. this.y = y;
  239. return this;
  240. };
  241. Vector2.prototype.add = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.addVector3 = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.subtract = function (otherVector) {
  248. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  249. };
  250. Vector2.prototype.subtractInPlace = function (otherVector) {
  251. this.x -= otherVector.x;
  252. this.y -= otherVector.y;
  253. return this;
  254. };
  255. Vector2.prototype.multiplyInPlace = function (otherVector) {
  256. this.x *= otherVector.x;
  257. this.y *= otherVector.y;
  258. return this;
  259. };
  260. Vector2.prototype.multiply = function (otherVector) {
  261. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  262. };
  263. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  264. result.x = this.x * otherVector.x;
  265. result.y = this.y * otherVector.y;
  266. return this;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. return this;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  294. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  295. };
  296. // Properties
  297. Vector2.prototype.length = function () {
  298. return Math.sqrt(this.x * this.x + this.y * this.y);
  299. };
  300. Vector2.prototype.lengthSquared = function () {
  301. return (this.x * this.x + this.y * this.y);
  302. };
  303. // Methods
  304. Vector2.prototype.normalize = function () {
  305. var len = this.length();
  306. if (len === 0)
  307. return this;
  308. var num = 1.0 / len;
  309. this.x *= num;
  310. this.y *= num;
  311. return this;
  312. };
  313. Vector2.prototype.clone = function () {
  314. return new Vector2(this.x, this.y);
  315. };
  316. // Statics
  317. Vector2.Zero = function () {
  318. return new Vector2(0, 0);
  319. };
  320. Vector2.FromArray = function (array, offset) {
  321. if (offset === void 0) { offset = 0; }
  322. return new Vector2(array[offset], array[offset + 1]);
  323. };
  324. Vector2.FromArrayToRef = function (array, offset, result) {
  325. result.x = array[offset];
  326. result.y = array[offset + 1];
  327. };
  328. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  329. var squared = amount * amount;
  330. var cubed = amount * squared;
  331. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  332. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  333. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  334. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  335. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  336. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Clamp = function (value, min, max) {
  340. var x = value.x;
  341. x = (x > max.x) ? max.x : x;
  342. x = (x < min.x) ? min.x : x;
  343. var y = value.y;
  344. y = (y > max.y) ? max.y : y;
  345. y = (y < min.y) ? min.y : y;
  346. return new Vector2(x, y);
  347. };
  348. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  349. var squared = amount * amount;
  350. var cubed = amount * squared;
  351. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  352. var part2 = (-2.0 * cubed) + (3.0 * squared);
  353. var part3 = (cubed - (2.0 * squared)) + amount;
  354. var part4 = cubed - squared;
  355. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  356. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  357. return new Vector2(x, y);
  358. };
  359. Vector2.Lerp = function (start, end, amount) {
  360. var x = start.x + ((end.x - start.x) * amount);
  361. var y = start.y + ((end.y - start.y) * amount);
  362. return new Vector2(x, y);
  363. };
  364. Vector2.Dot = function (left, right) {
  365. return left.x * right.x + left.y * right.y;
  366. };
  367. Vector2.Normalize = function (vector) {
  368. var newVector = vector.clone();
  369. newVector.normalize();
  370. return newVector;
  371. };
  372. Vector2.Minimize = function (left, right) {
  373. var x = (left.x < right.x) ? left.x : right.x;
  374. var y = (left.y < right.y) ? left.y : right.y;
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Maximize = function (left, right) {
  378. var x = (left.x > right.x) ? left.x : right.x;
  379. var y = (left.y > right.y) ? left.y : right.y;
  380. return new Vector2(x, y);
  381. };
  382. Vector2.Transform = function (vector, transformation) {
  383. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  384. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Distance = function (value1, value2) {
  388. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  389. };
  390. Vector2.DistanceSquared = function (value1, value2) {
  391. var x = value1.x - value2.x;
  392. var y = value1.y - value2.y;
  393. return (x * x) + (y * y);
  394. };
  395. return Vector2;
  396. })();
  397. BABYLON.Vector2 = Vector2;
  398. var Vector3 = (function () {
  399. function Vector3(x, y, z) {
  400. this.x = x;
  401. this.y = y;
  402. this.z = z;
  403. }
  404. Vector3.prototype.toString = function () {
  405. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  406. };
  407. // Operators
  408. Vector3.prototype.asArray = function () {
  409. var result = [];
  410. this.toArray(result, 0);
  411. return result;
  412. };
  413. Vector3.prototype.toArray = function (array, index) {
  414. if (index === void 0) { index = 0; }
  415. array[index] = this.x;
  416. array[index + 1] = this.y;
  417. array[index + 2] = this.z;
  418. return this;
  419. };
  420. Vector3.prototype.toQuaternion = function () {
  421. var result = new Quaternion(0, 0, 0, 1);
  422. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  423. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  424. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  425. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  426. var cosy = Math.cos(this.y * 0.5);
  427. var siny = Math.sin(this.y * 0.5);
  428. result.x = coszMinusx * siny;
  429. result.y = -sinzMinusx * siny;
  430. result.z = sinxPlusz * cosy;
  431. result.w = cosxPlusz * cosy;
  432. return result;
  433. };
  434. Vector3.prototype.addInPlace = function (otherVector) {
  435. this.x += otherVector.x;
  436. this.y += otherVector.y;
  437. this.z += otherVector.z;
  438. return this;
  439. };
  440. Vector3.prototype.add = function (otherVector) {
  441. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  442. };
  443. Vector3.prototype.addToRef = function (otherVector, result) {
  444. result.x = this.x + otherVector.x;
  445. result.y = this.y + otherVector.y;
  446. result.z = this.z + otherVector.z;
  447. return this;
  448. };
  449. Vector3.prototype.subtractInPlace = function (otherVector) {
  450. this.x -= otherVector.x;
  451. this.y -= otherVector.y;
  452. this.z -= otherVector.z;
  453. return this;
  454. };
  455. Vector3.prototype.subtract = function (otherVector) {
  456. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  457. };
  458. Vector3.prototype.subtractToRef = function (otherVector, result) {
  459. result.x = this.x - otherVector.x;
  460. result.y = this.y - otherVector.y;
  461. result.z = this.z - otherVector.z;
  462. return this;
  463. };
  464. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  465. return new Vector3(this.x - x, this.y - y, this.z - z);
  466. };
  467. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  468. result.x = this.x - x;
  469. result.y = this.y - y;
  470. result.z = this.z - z;
  471. return this;
  472. };
  473. Vector3.prototype.negate = function () {
  474. return new Vector3(-this.x, -this.y, -this.z);
  475. };
  476. Vector3.prototype.scaleInPlace = function (scale) {
  477. this.x *= scale;
  478. this.y *= scale;
  479. this.z *= scale;
  480. return this;
  481. };
  482. Vector3.prototype.scale = function (scale) {
  483. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  484. };
  485. Vector3.prototype.scaleToRef = function (scale, result) {
  486. result.x = this.x * scale;
  487. result.y = this.y * scale;
  488. result.z = this.z * scale;
  489. };
  490. Vector3.prototype.equals = function (otherVector) {
  491. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  492. };
  493. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  494. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  495. };
  496. Vector3.prototype.equalsToFloats = function (x, y, z) {
  497. return this.x === x && this.y === y && this.z === z;
  498. };
  499. Vector3.prototype.multiplyInPlace = function (otherVector) {
  500. this.x *= otherVector.x;
  501. this.y *= otherVector.y;
  502. this.z *= otherVector.z;
  503. return this;
  504. };
  505. Vector3.prototype.multiply = function (otherVector) {
  506. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  507. };
  508. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  509. result.x = this.x * otherVector.x;
  510. result.y = this.y * otherVector.y;
  511. result.z = this.z * otherVector.z;
  512. return this;
  513. };
  514. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  515. return new Vector3(this.x * x, this.y * y, this.z * z);
  516. };
  517. Vector3.prototype.divide = function (otherVector) {
  518. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  519. };
  520. Vector3.prototype.divideToRef = function (otherVector, result) {
  521. result.x = this.x / otherVector.x;
  522. result.y = this.y / otherVector.y;
  523. result.z = this.z / otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.MinimizeInPlace = function (other) {
  527. if (other.x < this.x)
  528. this.x = other.x;
  529. if (other.y < this.y)
  530. this.y = other.y;
  531. if (other.z < this.z)
  532. this.z = other.z;
  533. return this;
  534. };
  535. Vector3.prototype.MaximizeInPlace = function (other) {
  536. if (other.x > this.x)
  537. this.x = other.x;
  538. if (other.y > this.y)
  539. this.y = other.y;
  540. if (other.z > this.z)
  541. this.z = other.z;
  542. return this;
  543. };
  544. // Properties
  545. Vector3.prototype.length = function () {
  546. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  547. };
  548. Vector3.prototype.lengthSquared = function () {
  549. return (this.x * this.x + this.y * this.y + this.z * this.z);
  550. };
  551. // Methods
  552. Vector3.prototype.normalize = function () {
  553. var len = this.length();
  554. if (len === 0 || len === 1.0)
  555. return this;
  556. var num = 1.0 / len;
  557. this.x *= num;
  558. this.y *= num;
  559. this.z *= num;
  560. return this;
  561. };
  562. Vector3.prototype.clone = function () {
  563. return new Vector3(this.x, this.y, this.z);
  564. };
  565. Vector3.prototype.copyFrom = function (source) {
  566. this.x = source.x;
  567. this.y = source.y;
  568. this.z = source.z;
  569. return this;
  570. };
  571. Vector3.prototype.copyFromFloats = function (x, y, z) {
  572. this.x = x;
  573. this.y = y;
  574. this.z = z;
  575. return this;
  576. };
  577. // Statics
  578. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  579. var d0 = Vector3.Dot(vector0, axis) - size;
  580. var d1 = Vector3.Dot(vector1, axis) - size;
  581. var s = d0 / (d0 - d1);
  582. return s;
  583. };
  584. Vector3.FromArray = function (array, offset) {
  585. if (!offset) {
  586. offset = 0;
  587. }
  588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  589. };
  590. Vector3.FromArrayToRef = function (array, offset, result) {
  591. result.x = array[offset];
  592. result.y = array[offset + 1];
  593. result.z = array[offset + 2];
  594. };
  595. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  596. result.x = array[offset];
  597. result.y = array[offset + 1];
  598. result.z = array[offset + 2];
  599. };
  600. Vector3.FromFloatsToRef = function (x, y, z, result) {
  601. result.x = x;
  602. result.y = y;
  603. result.z = z;
  604. };
  605. Vector3.Zero = function () {
  606. return new Vector3(0, 0, 0);
  607. };
  608. Vector3.Up = function () {
  609. return new Vector3(0, 1.0, 0);
  610. };
  611. Vector3.TransformCoordinates = function (vector, transformation) {
  612. var result = Vector3.Zero();
  613. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  614. return result;
  615. };
  616. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  617. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  618. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  619. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  620. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  621. result.x = x / w;
  622. result.y = y / w;
  623. result.z = z / w;
  624. };
  625. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  626. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  627. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  628. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  629. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  630. result.x = rx / rw;
  631. result.y = ry / rw;
  632. result.z = rz / rw;
  633. };
  634. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  635. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  636. var m0 = SIMD.float32x4.load(transformation.m, 0);
  637. var m1 = SIMD.float32x4.load(transformation.m, 4);
  638. var m2 = SIMD.float32x4.load(transformation.m, 8);
  639. var m3 = SIMD.float32x4.load(transformation.m, 12);
  640. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  641. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  642. SIMD.float32x4.storeXYZ(result._data, 0, r);
  643. };
  644. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  645. var v0 = SIMD.float32x4.splat(x);
  646. var v1 = SIMD.float32x4.splat(y);
  647. var v2 = SIMD.float32x4.splat(z);
  648. var m0 = SIMD.float32x4.load(transformation.m, 0);
  649. var m1 = SIMD.float32x4.load(transformation.m, 4);
  650. var m2 = SIMD.float32x4.load(transformation.m, 8);
  651. var m3 = SIMD.float32x4.load(transformation.m, 12);
  652. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  653. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  654. SIMD.float32x4.storeXYZ(result._data, 0, r);
  655. };
  656. Vector3.TransformNormal = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformNormalToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  662. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  663. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  664. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  665. };
  666. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  667. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  668. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  669. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  670. };
  671. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  672. var squared = amount * amount;
  673. var cubed = amount * squared;
  674. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  675. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  676. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  677. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  678. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  679. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  680. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  681. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  682. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Clamp = function (value, min, max) {
  686. var x = value.x;
  687. x = (x > max.x) ? max.x : x;
  688. x = (x < min.x) ? min.x : x;
  689. var y = value.y;
  690. y = (y > max.y) ? max.y : y;
  691. y = (y < min.y) ? min.y : y;
  692. var z = value.z;
  693. z = (z > max.z) ? max.z : z;
  694. z = (z < min.z) ? min.z : z;
  695. return new Vector3(x, y, z);
  696. };
  697. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  698. var squared = amount * amount;
  699. var cubed = amount * squared;
  700. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  701. var part2 = (-2.0 * cubed) + (3.0 * squared);
  702. var part3 = (cubed - (2.0 * squared)) + amount;
  703. var part4 = cubed - squared;
  704. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  705. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  706. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  707. return new Vector3(x, y, z);
  708. };
  709. Vector3.Lerp = function (start, end, amount) {
  710. var x = start.x + ((end.x - start.x) * amount);
  711. var y = start.y + ((end.y - start.y) * amount);
  712. var z = start.z + ((end.z - start.z) * amount);
  713. return new Vector3(x, y, z);
  714. };
  715. Vector3.Dot = function (left, right) {
  716. return (left.x * right.x + left.y * right.y + left.z * right.z);
  717. };
  718. Vector3.Cross = function (left, right) {
  719. var result = Vector3.Zero();
  720. Vector3.CrossToRef(left, right, result);
  721. return result;
  722. };
  723. Vector3.CrossToRef = function (left, right, result) {
  724. result.x = left.y * right.z - left.z * right.y;
  725. result.y = left.z * right.x - left.x * right.z;
  726. result.z = left.x * right.y - left.y * right.x;
  727. };
  728. Vector3.Normalize = function (vector) {
  729. var result = Vector3.Zero();
  730. Vector3.NormalizeToRef(vector, result);
  731. return result;
  732. };
  733. Vector3.NormalizeToRef = function (vector, result) {
  734. result.copyFrom(vector);
  735. result.normalize();
  736. };
  737. Vector3.Project = function (vector, world, transform, viewport) {
  738. var cw = viewport.width;
  739. var ch = viewport.height;
  740. var cx = viewport.x;
  741. var cy = viewport.y;
  742. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  743. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  744. return Vector3.TransformCoordinates(vector, finalMatrix);
  745. };
  746. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  747. var matrix = world.multiply(transform);
  748. matrix.invert();
  749. source.x = source.x / viewportWidth * 2 - 1;
  750. source.y = -(source.y / viewportHeight * 2 - 1);
  751. var vector = Vector3.TransformCoordinates(source, matrix);
  752. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  753. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  754. vector = vector.scale(1.0 / num);
  755. }
  756. return vector;
  757. };
  758. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  759. var matrix = world.multiply(view).multiply(projection);
  760. matrix.invert();
  761. source.x = source.x / viewportWidth * 2 - 1;
  762. source.y = -(source.y / viewportHeight * 2 - 1);
  763. var vector = Vector3.TransformCoordinates(source, matrix);
  764. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  765. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  766. vector = vector.scale(1.0 / num);
  767. }
  768. return vector;
  769. };
  770. Vector3.Minimize = function (left, right) {
  771. var min = left.clone();
  772. min.MinimizeInPlace(right);
  773. return min;
  774. };
  775. Vector3.Maximize = function (left, right) {
  776. var max = left.clone();
  777. max.MaximizeInPlace(right);
  778. return max;
  779. };
  780. Vector3.Distance = function (value1, value2) {
  781. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  782. };
  783. Vector3.DistanceSquared = function (value1, value2) {
  784. var x = value1.x - value2.x;
  785. var y = value1.y - value2.y;
  786. var z = value1.z - value2.z;
  787. return (x * x) + (y * y) + (z * z);
  788. };
  789. Vector3.Center = function (value1, value2) {
  790. var center = value1.add(value2);
  791. center.scaleInPlace(0.5);
  792. return center;
  793. };
  794. /**
  795. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  796. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  797. * to something in order to rotate it from its local system to the given target system.
  798. */
  799. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  800. var u = Vector3.Normalize(axis1);
  801. var v = Vector3.Normalize(axis2);
  802. var w = Vector3.Normalize(axis3);
  803. // world axis
  804. var X = Axis.X;
  805. var Y = Axis.Y;
  806. var Z = Axis.Z;
  807. // equation unknowns and vars
  808. var yaw = 0.0;
  809. var pitch = 0.0;
  810. var roll = 0.0;
  811. var x = 0.0;
  812. var y = 0.0;
  813. var z = 0.0;
  814. var t = 0.0;
  815. var sign = -1.0;
  816. var pi = Math.PI;
  817. var nbRevert = 0;
  818. var cross;
  819. var dot = 0.0;
  820. // step 1 : rotation around w
  821. // Rv3(u) = u1, and u1 belongs to plane xOz
  822. // Rv3(w) = w1 = w invariant
  823. var u1;
  824. var v1;
  825. if (w.z == 0) {
  826. z = 1.0;
  827. }
  828. else if (w.x == 0) {
  829. x = 1.0;
  830. }
  831. else {
  832. t = w.z / w.x;
  833. x = -t * Math.sqrt(1 / (1 + t * t));
  834. z = Math.sqrt(1 / (1 + t * t));
  835. }
  836. u1 = new Vector3(x, y, z);
  837. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  838. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  839. if (Vector3.Dot(w, cross) < 0) {
  840. sign = 1;
  841. }
  842. dot = Vector3.Dot(u, u1);
  843. roll = Math.acos(dot) * sign;
  844. if (Vector3.Dot(u1, X) < 0) {
  845. roll = Math.PI + roll;
  846. u1 = u1.scaleInPlace(-1);
  847. v1 = v1.scaleInPlace(-1);
  848. nbRevert++;
  849. }
  850. // step 2 : rotate around u1
  851. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  852. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  853. var w2;
  854. var v2;
  855. x = 0.0;
  856. y = 0.0;
  857. z = 0.0;
  858. sign = -1;
  859. if (w.z == 0) {
  860. x = 1.0;
  861. }
  862. else {
  863. t = u1.z / u1.x;
  864. x = -t * Math.sqrt(1 / (1 + t * t));
  865. z = Math.sqrt(1 / (1 + t * t));
  866. }
  867. w2 = new BABYLON.Vector3(x, y, z);
  868. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  869. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  870. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  871. sign = 1;
  872. }
  873. dot = BABYLON.Vector3.Dot(w, w2);
  874. pitch = Math.acos(dot) * sign;
  875. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  876. pitch = Math.PI + pitch;
  877. v2 = v2.scaleInPlace(-1);
  878. w2 = w2.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 3 : rotate around v2
  882. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  883. sign = -1;
  884. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  885. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  886. sign = 1;
  887. }
  888. dot = BABYLON.Vector3.Dot(u1, X);
  889. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  890. if (dot < 0 && nbRevert < 2) {
  891. yaw = Math.PI + yaw;
  892. }
  893. return new BABYLON.Vector3(pitch, yaw, roll);
  894. };
  895. return Vector3;
  896. })();
  897. BABYLON.Vector3 = Vector3;
  898. //Vector4 class created for EulerAngle class conversion to Quaternion
  899. var Vector4 = (function () {
  900. function Vector4(x, y, z, w) {
  901. this.x = x;
  902. this.y = y;
  903. this.z = z;
  904. this.w = w;
  905. }
  906. Vector4.prototype.toString = function () {
  907. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  908. };
  909. // Operators
  910. Vector4.prototype.asArray = function () {
  911. var result = [];
  912. this.toArray(result, 0);
  913. return result;
  914. };
  915. Vector4.prototype.toArray = function (array, index) {
  916. if (index === undefined) {
  917. index = 0;
  918. }
  919. array[index] = this.x;
  920. array[index + 1] = this.y;
  921. array[index + 2] = this.z;
  922. array[index + 3] = this.w;
  923. return this;
  924. };
  925. Vector4.prototype.addInPlace = function (otherVector) {
  926. this.x += otherVector.x;
  927. this.y += otherVector.y;
  928. this.z += otherVector.z;
  929. this.w += otherVector.w;
  930. return this;
  931. };
  932. Vector4.prototype.add = function (otherVector) {
  933. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  934. };
  935. Vector4.prototype.addToRef = function (otherVector, result) {
  936. result.x = this.x + otherVector.x;
  937. result.y = this.y + otherVector.y;
  938. result.z = this.z + otherVector.z;
  939. result.w = this.w + otherVector.w;
  940. return this;
  941. };
  942. Vector4.prototype.subtractInPlace = function (otherVector) {
  943. this.x -= otherVector.x;
  944. this.y -= otherVector.y;
  945. this.z -= otherVector.z;
  946. this.w -= otherVector.w;
  947. return this;
  948. };
  949. Vector4.prototype.subtract = function (otherVector) {
  950. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  951. };
  952. Vector4.prototype.subtractToRef = function (otherVector, result) {
  953. result.x = this.x - otherVector.x;
  954. result.y = this.y - otherVector.y;
  955. result.z = this.z - otherVector.z;
  956. result.w = this.w - otherVector.w;
  957. return this;
  958. };
  959. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  960. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  961. };
  962. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  963. result.x = this.x - x;
  964. result.y = this.y - y;
  965. result.z = this.z - z;
  966. result.w = this.w - w;
  967. return this;
  968. };
  969. Vector4.prototype.negate = function () {
  970. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  971. };
  972. Vector4.prototype.scaleInPlace = function (scale) {
  973. this.x *= scale;
  974. this.y *= scale;
  975. this.z *= scale;
  976. this.w *= scale;
  977. return this;
  978. };
  979. Vector4.prototype.scale = function (scale) {
  980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  981. };
  982. Vector4.prototype.scaleToRef = function (scale, result) {
  983. result.x = this.x * scale;
  984. result.y = this.y * scale;
  985. result.z = this.z * scale;
  986. result.w = this.w * scale;
  987. };
  988. Vector4.prototype.equals = function (otherVector) {
  989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  990. };
  991. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  992. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  993. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  994. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  995. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  996. };
  997. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  998. return this.x === x && this.y === y && this.z === z && this.w === w;
  999. };
  1000. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1001. this.x *= otherVector.x;
  1002. this.y *= otherVector.y;
  1003. this.z *= otherVector.z;
  1004. this.w *= otherVector.w;
  1005. return this;
  1006. };
  1007. Vector4.prototype.multiply = function (otherVector) {
  1008. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1009. };
  1010. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1011. result.x = this.x * otherVector.x;
  1012. result.y = this.y * otherVector.y;
  1013. result.z = this.z * otherVector.z;
  1014. result.w = this.w * otherVector.w;
  1015. return this;
  1016. };
  1017. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1018. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1019. };
  1020. Vector4.prototype.divide = function (otherVector) {
  1021. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1022. };
  1023. Vector4.prototype.divideToRef = function (otherVector, result) {
  1024. result.x = this.x / otherVector.x;
  1025. result.y = this.y / otherVector.y;
  1026. result.z = this.z / otherVector.z;
  1027. result.w = this.w / otherVector.w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.MinimizeInPlace = function (other) {
  1031. if (other.x < this.x)
  1032. this.x = other.x;
  1033. if (other.y < this.y)
  1034. this.y = other.y;
  1035. if (other.z < this.z)
  1036. this.z = other.z;
  1037. if (other.w < this.w)
  1038. this.w = other.w;
  1039. return this;
  1040. };
  1041. Vector4.prototype.MaximizeInPlace = function (other) {
  1042. if (other.x > this.x)
  1043. this.x = other.x;
  1044. if (other.y > this.y)
  1045. this.y = other.y;
  1046. if (other.z > this.z)
  1047. this.z = other.z;
  1048. if (other.w > this.w)
  1049. this.w = other.w;
  1050. return this;
  1051. };
  1052. // Properties
  1053. Vector4.prototype.length = function () {
  1054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1055. };
  1056. Vector4.prototype.lengthSquared = function () {
  1057. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1058. };
  1059. // Methods
  1060. Vector4.prototype.normalize = function () {
  1061. var len = this.length();
  1062. if (len === 0)
  1063. return this;
  1064. var num = 1.0 / len;
  1065. this.x *= num;
  1066. this.y *= num;
  1067. this.z *= num;
  1068. this.w *= num;
  1069. return this;
  1070. };
  1071. Vector4.prototype.clone = function () {
  1072. return new Vector4(this.x, this.y, this.z, this.w);
  1073. };
  1074. Vector4.prototype.copyFrom = function (source) {
  1075. this.x = source.x;
  1076. this.y = source.y;
  1077. this.z = source.z;
  1078. this.w = source.w;
  1079. return this;
  1080. };
  1081. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1082. this.x = x;
  1083. this.y = y;
  1084. this.z = z;
  1085. this.w = w;
  1086. return this;
  1087. };
  1088. // Statics
  1089. Vector4.FromArray = function (array, offset) {
  1090. if (!offset) {
  1091. offset = 0;
  1092. }
  1093. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1094. };
  1095. Vector4.FromArrayToRef = function (array, offset, result) {
  1096. result.x = array[offset];
  1097. result.y = array[offset + 1];
  1098. result.z = array[offset + 2];
  1099. result.w = array[offset + 3];
  1100. };
  1101. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1102. result.x = array[offset];
  1103. result.y = array[offset + 1];
  1104. result.z = array[offset + 2];
  1105. result.w = array[offset + 3];
  1106. };
  1107. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1108. result.x = x;
  1109. result.y = y;
  1110. result.z = z;
  1111. result.w = w;
  1112. };
  1113. Vector4.Zero = function () {
  1114. return new Vector4(0, 0, 0, 0);
  1115. };
  1116. Vector4.Normalize = function (vector) {
  1117. var result = Vector4.Zero();
  1118. Vector4.NormalizeToRef(vector, result);
  1119. return result;
  1120. };
  1121. Vector4.NormalizeToRef = function (vector, result) {
  1122. result.copyFrom(vector);
  1123. result.normalize();
  1124. };
  1125. Vector4.Minimize = function (left, right) {
  1126. var min = left.clone();
  1127. min.MinimizeInPlace(right);
  1128. return min;
  1129. };
  1130. Vector4.Maximize = function (left, right) {
  1131. var max = left.clone();
  1132. max.MaximizeInPlace(right);
  1133. return max;
  1134. };
  1135. Vector4.Distance = function (value1, value2) {
  1136. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1137. };
  1138. Vector4.DistanceSquared = function (value1, value2) {
  1139. var x = value1.x - value2.x;
  1140. var y = value1.y - value2.y;
  1141. var z = value1.z - value2.z;
  1142. var w = value1.w - value2.w;
  1143. return (x * x) + (y * y) + (z * z) + (w * w);
  1144. };
  1145. Vector4.Center = function (value1, value2) {
  1146. var center = value1.add(value2);
  1147. center.scaleInPlace(0.5);
  1148. return center;
  1149. };
  1150. return Vector4;
  1151. })();
  1152. BABYLON.Vector4 = Vector4;
  1153. var Quaternion = (function () {
  1154. function Quaternion(x, y, z, w) {
  1155. if (x === void 0) { x = 0; }
  1156. if (y === void 0) { y = 0; }
  1157. if (z === void 0) { z = 0; }
  1158. if (w === void 0) { w = 1; }
  1159. this.x = x;
  1160. this.y = y;
  1161. this.z = z;
  1162. this.w = w;
  1163. }
  1164. Quaternion.prototype.toString = function () {
  1165. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1166. };
  1167. Quaternion.prototype.asArray = function () {
  1168. return [this.x, this.y, this.z, this.w];
  1169. };
  1170. Quaternion.prototype.equals = function (otherQuaternion) {
  1171. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1172. };
  1173. Quaternion.prototype.clone = function () {
  1174. return new Quaternion(this.x, this.y, this.z, this.w);
  1175. };
  1176. Quaternion.prototype.copyFrom = function (other) {
  1177. this.x = other.x;
  1178. this.y = other.y;
  1179. this.z = other.z;
  1180. this.w = other.w;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1184. this.x = x;
  1185. this.y = y;
  1186. this.z = z;
  1187. this.w = w;
  1188. return this;
  1189. };
  1190. Quaternion.prototype.add = function (other) {
  1191. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1192. };
  1193. Quaternion.prototype.subtract = function (other) {
  1194. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1195. };
  1196. Quaternion.prototype.scale = function (value) {
  1197. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1198. };
  1199. Quaternion.prototype.multiply = function (q1) {
  1200. var result = new Quaternion(0, 0, 0, 1.0);
  1201. this.multiplyToRef(q1, result);
  1202. return result;
  1203. };
  1204. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1205. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1206. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1207. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1208. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1209. result.copyFromFloats(x, y, z, w);
  1210. return this;
  1211. };
  1212. Quaternion.prototype.length = function () {
  1213. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1214. };
  1215. Quaternion.prototype.normalize = function () {
  1216. var length = 1.0 / this.length();
  1217. this.x *= length;
  1218. this.y *= length;
  1219. this.z *= length;
  1220. this.w *= length;
  1221. return this;
  1222. };
  1223. Quaternion.prototype.toEulerAngles = function () {
  1224. var result = Vector3.Zero();
  1225. this.toEulerAnglesToRef(result);
  1226. return result;
  1227. };
  1228. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1229. //result is an EulerAngles in the in the z-x-z convention
  1230. var qx = this.x;
  1231. var qy = this.y;
  1232. var qz = this.z;
  1233. var qw = this.w;
  1234. var qxy = qx * qy;
  1235. var qxz = qx * qz;
  1236. var qwy = qw * qy;
  1237. var qwz = qw * qz;
  1238. var qwx = qw * qx;
  1239. var qyz = qy * qz;
  1240. var sqx = qx * qx;
  1241. var sqy = qy * qy;
  1242. var determinant = sqx + sqy;
  1243. if (determinant !== 0.000 && determinant !== 1.000) {
  1244. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1245. result.y = Math.acos(1 - 2 * determinant);
  1246. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1247. }
  1248. else {
  1249. if (determinant === 0.0) {
  1250. result.x = 0.0;
  1251. result.y = 0.0;
  1252. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1253. }
  1254. else {
  1255. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1256. result.y = Math.PI;
  1257. result.z = 0.0;
  1258. }
  1259. }
  1260. return this;
  1261. };
  1262. Quaternion.prototype.toRotationMatrix = function (result) {
  1263. var xx = this.x * this.x;
  1264. var yy = this.y * this.y;
  1265. var zz = this.z * this.z;
  1266. var xy = this.x * this.y;
  1267. var zw = this.z * this.w;
  1268. var zx = this.z * this.x;
  1269. var yw = this.y * this.w;
  1270. var yz = this.y * this.z;
  1271. var xw = this.x * this.w;
  1272. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1273. result.m[1] = 2.0 * (xy + zw);
  1274. result.m[2] = 2.0 * (zx - yw);
  1275. result.m[3] = 0;
  1276. result.m[4] = 2.0 * (xy - zw);
  1277. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1278. result.m[6] = 2.0 * (yz + xw);
  1279. result.m[7] = 0;
  1280. result.m[8] = 2.0 * (zx + yw);
  1281. result.m[9] = 2.0 * (yz - xw);
  1282. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1283. result.m[11] = 0;
  1284. result.m[12] = 0;
  1285. result.m[13] = 0;
  1286. result.m[14] = 0;
  1287. result.m[15] = 1.0;
  1288. return this;
  1289. };
  1290. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1291. Quaternion.FromRotationMatrixToRef(matrix, this);
  1292. return this;
  1293. };
  1294. // Statics
  1295. Quaternion.FromRotationMatrix = function (matrix) {
  1296. var result = new Quaternion();
  1297. Quaternion.FromRotationMatrixToRef(matrix, result);
  1298. return result;
  1299. };
  1300. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1301. var data = matrix.m;
  1302. var m11 = data[0], m12 = data[4], m13 = data[8];
  1303. var m21 = data[1], m22 = data[5], m23 = data[9];
  1304. var m31 = data[2], m32 = data[6], m33 = data[10];
  1305. var trace = m11 + m22 + m33;
  1306. var s;
  1307. if (trace > 0) {
  1308. s = 0.5 / Math.sqrt(trace + 1.0);
  1309. result.w = 0.25 / s;
  1310. result.x = (m32 - m23) * s;
  1311. result.y = (m13 - m31) * s;
  1312. result.z = (m21 - m12) * s;
  1313. }
  1314. else if (m11 > m22 && m11 > m33) {
  1315. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1316. result.w = (m32 - m23) / s;
  1317. result.x = 0.25 * s;
  1318. result.y = (m12 + m21) / s;
  1319. result.z = (m13 + m31) / s;
  1320. }
  1321. else if (m22 > m33) {
  1322. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1323. result.w = (m13 - m31) / s;
  1324. result.x = (m12 + m21) / s;
  1325. result.y = 0.25 * s;
  1326. result.z = (m23 + m32) / s;
  1327. }
  1328. else {
  1329. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1330. result.w = (m21 - m12) / s;
  1331. result.x = (m13 + m31) / s;
  1332. result.y = (m23 + m32) / s;
  1333. result.z = 0.25 * s;
  1334. }
  1335. };
  1336. Quaternion.Inverse = function (q) {
  1337. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1338. };
  1339. Quaternion.Identity = function () {
  1340. return new Quaternion(0, 0, 0, 1);
  1341. };
  1342. Quaternion.RotationAxis = function (axis, angle) {
  1343. var result = new Quaternion();
  1344. var sin = Math.sin(angle / 2);
  1345. result.w = Math.cos(angle / 2);
  1346. result.x = axis.x * sin;
  1347. result.y = axis.y * sin;
  1348. result.z = axis.z * sin;
  1349. return result;
  1350. };
  1351. Quaternion.FromArray = function (array, offset) {
  1352. if (!offset) {
  1353. offset = 0;
  1354. }
  1355. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1356. };
  1357. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1358. var result = new Quaternion();
  1359. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1360. return result;
  1361. };
  1362. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1363. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1364. var halfRoll = roll * 0.5;
  1365. var halfPitch = pitch * 0.5;
  1366. var halfYaw = yaw * 0.5;
  1367. var sinRoll = Math.sin(halfRoll);
  1368. var cosRoll = Math.cos(halfRoll);
  1369. var sinPitch = Math.sin(halfPitch);
  1370. var cosPitch = Math.cos(halfPitch);
  1371. var sinYaw = Math.sin(halfYaw);
  1372. var cosYaw = Math.cos(halfYaw);
  1373. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1374. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1375. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1376. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1377. };
  1378. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1379. var result = new Quaternion();
  1380. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1381. return result;
  1382. };
  1383. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1384. // Produces a quaternion from Euler angles in the z-x-z orientation
  1385. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1386. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1387. var halfBeta = beta * 0.5;
  1388. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1389. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1390. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1391. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1392. };
  1393. Quaternion.Slerp = function (left, right, amount) {
  1394. var num2;
  1395. var num3;
  1396. var num = amount;
  1397. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1398. var flag = false;
  1399. if (num4 < 0) {
  1400. flag = true;
  1401. num4 = -num4;
  1402. }
  1403. if (num4 > 0.999999) {
  1404. num3 = 1 - num;
  1405. num2 = flag ? -num : num;
  1406. }
  1407. else {
  1408. var num5 = Math.acos(num4);
  1409. var num6 = (1.0 / Math.sin(num5));
  1410. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1411. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1412. }
  1413. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1414. };
  1415. return Quaternion;
  1416. })();
  1417. BABYLON.Quaternion = Quaternion;
  1418. var Matrix = (function () {
  1419. function Matrix() {
  1420. this.m = new Float32Array(16);
  1421. }
  1422. // Properties
  1423. Matrix.prototype.isIdentity = function () {
  1424. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1425. return false;
  1426. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1427. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1428. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1429. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1430. return false;
  1431. return true;
  1432. };
  1433. Matrix.prototype.determinant = function () {
  1434. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1435. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1436. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1437. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1438. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1439. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1440. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1441. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1442. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1443. };
  1444. // Methods
  1445. Matrix.prototype.toArray = function () {
  1446. return this.m;
  1447. };
  1448. Matrix.prototype.asArray = function () {
  1449. return this.toArray();
  1450. };
  1451. Matrix.prototype.invert = function () {
  1452. this.invertToRef(this);
  1453. return this;
  1454. };
  1455. Matrix.prototype.invertToRef = function (other) {
  1456. var l1 = this.m[0];
  1457. var l2 = this.m[1];
  1458. var l3 = this.m[2];
  1459. var l4 = this.m[3];
  1460. var l5 = this.m[4];
  1461. var l6 = this.m[5];
  1462. var l7 = this.m[6];
  1463. var l8 = this.m[7];
  1464. var l9 = this.m[8];
  1465. var l10 = this.m[9];
  1466. var l11 = this.m[10];
  1467. var l12 = this.m[11];
  1468. var l13 = this.m[12];
  1469. var l14 = this.m[13];
  1470. var l15 = this.m[14];
  1471. var l16 = this.m[15];
  1472. var l17 = (l11 * l16) - (l12 * l15);
  1473. var l18 = (l10 * l16) - (l12 * l14);
  1474. var l19 = (l10 * l15) - (l11 * l14);
  1475. var l20 = (l9 * l16) - (l12 * l13);
  1476. var l21 = (l9 * l15) - (l11 * l13);
  1477. var l22 = (l9 * l14) - (l10 * l13);
  1478. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1479. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1480. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1481. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1482. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1483. var l28 = (l7 * l16) - (l8 * l15);
  1484. var l29 = (l6 * l16) - (l8 * l14);
  1485. var l30 = (l6 * l15) - (l7 * l14);
  1486. var l31 = (l5 * l16) - (l8 * l13);
  1487. var l32 = (l5 * l15) - (l7 * l13);
  1488. var l33 = (l5 * l14) - (l6 * l13);
  1489. var l34 = (l7 * l12) - (l8 * l11);
  1490. var l35 = (l6 * l12) - (l8 * l10);
  1491. var l36 = (l6 * l11) - (l7 * l10);
  1492. var l37 = (l5 * l12) - (l8 * l9);
  1493. var l38 = (l5 * l11) - (l7 * l9);
  1494. var l39 = (l5 * l10) - (l6 * l9);
  1495. other.m[0] = l23 * l27;
  1496. other.m[4] = l24 * l27;
  1497. other.m[8] = l25 * l27;
  1498. other.m[12] = l26 * l27;
  1499. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1500. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1501. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1502. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1503. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1504. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1505. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1506. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1507. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1508. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1509. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1510. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1511. return this;
  1512. };
  1513. Matrix.prototype.invertToRefSIMD = function (other) {
  1514. var src = this.m;
  1515. var dest = other.m;
  1516. var row0, row1, row2, row3;
  1517. var tmp1;
  1518. var minor0, minor1, minor2, minor3;
  1519. var det;
  1520. // Load the 4 rows
  1521. var src0 = SIMD.float32x4.load(src, 0);
  1522. var src1 = SIMD.float32x4.load(src, 4);
  1523. var src2 = SIMD.float32x4.load(src, 8);
  1524. var src3 = SIMD.float32x4.load(src, 12);
  1525. // Transpose the source matrix. Sort of. Not a true transpose operation
  1526. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1527. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1528. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1529. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1530. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1531. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1532. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1533. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1534. // This is a true transposition, but it will lead to an incorrect result
  1535. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1536. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1537. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1538. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1539. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1540. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1541. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1542. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1543. // ----
  1544. tmp1 = SIMD.float32x4.mul(row2, row3);
  1545. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1546. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1547. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1548. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1549. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1550. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1551. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1552. // ----
  1553. tmp1 = SIMD.float32x4.mul(row1, row2);
  1554. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1555. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1556. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1557. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1558. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1559. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1560. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1561. // ----
  1562. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1563. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1564. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1565. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1566. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1567. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1568. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1569. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1570. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1571. // ----
  1572. tmp1 = SIMD.float32x4.mul(row0, row1);
  1573. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1574. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1575. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1576. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1577. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1578. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1579. // ----
  1580. tmp1 = SIMD.float32x4.mul(row0, row3);
  1581. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1582. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1583. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1584. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1585. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1586. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1587. // ----
  1588. tmp1 = SIMD.float32x4.mul(row0, row2);
  1589. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1590. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1591. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1592. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1593. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1594. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1595. // Compute determinant
  1596. det = SIMD.float32x4.mul(row0, minor0);
  1597. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1598. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1599. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1600. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1601. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1602. // These shuffles aren't necessary if the faulty transposition is done
  1603. // up at the top of this function.
  1604. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1605. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1606. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1607. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1608. // Compute final values by multiplying with 1/det
  1609. minor0 = SIMD.float32x4.mul(det, minor0);
  1610. minor1 = SIMD.float32x4.mul(det, minor1);
  1611. minor2 = SIMD.float32x4.mul(det, minor2);
  1612. minor3 = SIMD.float32x4.mul(det, minor3);
  1613. SIMD.float32x4.store(dest, 0, minor0);
  1614. SIMD.float32x4.store(dest, 4, minor1);
  1615. SIMD.float32x4.store(dest, 8, minor2);
  1616. SIMD.float32x4.store(dest, 12, minor3);
  1617. return this;
  1618. };
  1619. Matrix.prototype.setTranslation = function (vector3) {
  1620. this.m[12] = vector3.x;
  1621. this.m[13] = vector3.y;
  1622. this.m[14] = vector3.z;
  1623. return this;
  1624. };
  1625. Matrix.prototype.multiply = function (other) {
  1626. var result = new Matrix();
  1627. this.multiplyToRef(other, result);
  1628. return result;
  1629. };
  1630. Matrix.prototype.copyFrom = function (other) {
  1631. for (var index = 0; index < 16; index++) {
  1632. this.m[index] = other.m[index];
  1633. }
  1634. return this;
  1635. };
  1636. Matrix.prototype.copyToArray = function (array, offset) {
  1637. if (offset === void 0) { offset = 0; }
  1638. for (var index = 0; index < 16; index++) {
  1639. array[offset + index] = this.m[index];
  1640. }
  1641. return this;
  1642. };
  1643. Matrix.prototype.multiplyToRef = function (other, result) {
  1644. this.multiplyToArray(other, result.m, 0);
  1645. return this;
  1646. };
  1647. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1648. var tm0 = this.m[0];
  1649. var tm1 = this.m[1];
  1650. var tm2 = this.m[2];
  1651. var tm3 = this.m[3];
  1652. var tm4 = this.m[4];
  1653. var tm5 = this.m[5];
  1654. var tm6 = this.m[6];
  1655. var tm7 = this.m[7];
  1656. var tm8 = this.m[8];
  1657. var tm9 = this.m[9];
  1658. var tm10 = this.m[10];
  1659. var tm11 = this.m[11];
  1660. var tm12 = this.m[12];
  1661. var tm13 = this.m[13];
  1662. var tm14 = this.m[14];
  1663. var tm15 = this.m[15];
  1664. var om0 = other.m[0];
  1665. var om1 = other.m[1];
  1666. var om2 = other.m[2];
  1667. var om3 = other.m[3];
  1668. var om4 = other.m[4];
  1669. var om5 = other.m[5];
  1670. var om6 = other.m[6];
  1671. var om7 = other.m[7];
  1672. var om8 = other.m[8];
  1673. var om9 = other.m[9];
  1674. var om10 = other.m[10];
  1675. var om11 = other.m[11];
  1676. var om12 = other.m[12];
  1677. var om13 = other.m[13];
  1678. var om14 = other.m[14];
  1679. var om15 = other.m[15];
  1680. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1681. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1682. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1683. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1684. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1685. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1686. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1687. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1688. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1689. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1690. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1691. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1692. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1693. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1694. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1695. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1696. return this;
  1697. };
  1698. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. var tm = this.m;
  1701. var om = other.m;
  1702. var om0 = SIMD.float32x4.load(om, 0);
  1703. var om1 = SIMD.float32x4.load(om, 4);
  1704. var om2 = SIMD.float32x4.load(om, 8);
  1705. var om3 = SIMD.float32x4.load(om, 12);
  1706. var tm0 = SIMD.float32x4.load(tm, 0);
  1707. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1708. var tm1 = SIMD.float32x4.load(tm, 4);
  1709. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1710. var tm2 = SIMD.float32x4.load(tm, 8);
  1711. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1712. var tm3 = SIMD.float32x4.load(tm, 12);
  1713. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1714. };
  1715. Matrix.prototype.equals = function (value) {
  1716. return value &&
  1717. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1718. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1719. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1720. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1721. };
  1722. Matrix.prototype.clone = function () {
  1723. 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]);
  1724. };
  1725. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1726. translation.x = this.m[12];
  1727. translation.y = this.m[13];
  1728. translation.z = this.m[14];
  1729. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1730. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1731. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1732. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1733. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1734. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1735. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1736. rotation.x = 0;
  1737. rotation.y = 0;
  1738. rotation.z = 0;
  1739. rotation.w = 1;
  1740. return false;
  1741. }
  1742. var rotationMatrix = Matrix.FromValues(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);
  1743. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1744. return true;
  1745. };
  1746. // Statics
  1747. Matrix.FromArray = function (array, offset) {
  1748. var result = new Matrix();
  1749. if (!offset) {
  1750. offset = 0;
  1751. }
  1752. Matrix.FromArrayToRef(array, offset, result);
  1753. return result;
  1754. };
  1755. Matrix.FromArrayToRef = function (array, offset, result) {
  1756. for (var index = 0; index < 16; index++) {
  1757. result.m[index] = array[index + offset];
  1758. }
  1759. };
  1760. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1761. result.m[0] = initialM11;
  1762. result.m[1] = initialM12;
  1763. result.m[2] = initialM13;
  1764. result.m[3] = initialM14;
  1765. result.m[4] = initialM21;
  1766. result.m[5] = initialM22;
  1767. result.m[6] = initialM23;
  1768. result.m[7] = initialM24;
  1769. result.m[8] = initialM31;
  1770. result.m[9] = initialM32;
  1771. result.m[10] = initialM33;
  1772. result.m[11] = initialM34;
  1773. result.m[12] = initialM41;
  1774. result.m[13] = initialM42;
  1775. result.m[14] = initialM43;
  1776. result.m[15] = initialM44;
  1777. };
  1778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1779. var result = new Matrix();
  1780. result.m[0] = initialM11;
  1781. result.m[1] = initialM12;
  1782. result.m[2] = initialM13;
  1783. result.m[3] = initialM14;
  1784. result.m[4] = initialM21;
  1785. result.m[5] = initialM22;
  1786. result.m[6] = initialM23;
  1787. result.m[7] = initialM24;
  1788. result.m[8] = initialM31;
  1789. result.m[9] = initialM32;
  1790. result.m[10] = initialM33;
  1791. result.m[11] = initialM34;
  1792. result.m[12] = initialM41;
  1793. result.m[13] = initialM42;
  1794. result.m[14] = initialM43;
  1795. result.m[15] = initialM44;
  1796. return result;
  1797. };
  1798. Matrix.Compose = function (scale, rotation, translation) {
  1799. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1800. var rotationMatrix = Matrix.Identity();
  1801. rotation.toRotationMatrix(rotationMatrix);
  1802. result = result.multiply(rotationMatrix);
  1803. result.setTranslation(translation);
  1804. return result;
  1805. };
  1806. Matrix.Identity = function () {
  1807. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1808. };
  1809. Matrix.IdentityToRef = function (result) {
  1810. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1811. };
  1812. Matrix.Zero = function () {
  1813. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1814. };
  1815. Matrix.RotationX = function (angle) {
  1816. var result = new Matrix();
  1817. Matrix.RotationXToRef(angle, result);
  1818. return result;
  1819. };
  1820. Matrix.Invert = function (source) {
  1821. var result = new Matrix();
  1822. source.invertToRef(result);
  1823. return result;
  1824. };
  1825. Matrix.RotationXToRef = function (angle, result) {
  1826. var s = Math.sin(angle);
  1827. var c = Math.cos(angle);
  1828. result.m[0] = 1.0;
  1829. result.m[15] = 1.0;
  1830. result.m[5] = c;
  1831. result.m[10] = c;
  1832. result.m[9] = -s;
  1833. result.m[6] = s;
  1834. result.m[1] = 0;
  1835. result.m[2] = 0;
  1836. result.m[3] = 0;
  1837. result.m[4] = 0;
  1838. result.m[7] = 0;
  1839. result.m[8] = 0;
  1840. result.m[11] = 0;
  1841. result.m[12] = 0;
  1842. result.m[13] = 0;
  1843. result.m[14] = 0;
  1844. };
  1845. Matrix.RotationY = function (angle) {
  1846. var result = new Matrix();
  1847. Matrix.RotationYToRef(angle, result);
  1848. return result;
  1849. };
  1850. Matrix.RotationYToRef = function (angle, result) {
  1851. var s = Math.sin(angle);
  1852. var c = Math.cos(angle);
  1853. result.m[5] = 1.0;
  1854. result.m[15] = 1.0;
  1855. result.m[0] = c;
  1856. result.m[2] = -s;
  1857. result.m[8] = s;
  1858. result.m[10] = c;
  1859. result.m[1] = 0;
  1860. result.m[3] = 0;
  1861. result.m[4] = 0;
  1862. result.m[6] = 0;
  1863. result.m[7] = 0;
  1864. result.m[9] = 0;
  1865. result.m[11] = 0;
  1866. result.m[12] = 0;
  1867. result.m[13] = 0;
  1868. result.m[14] = 0;
  1869. };
  1870. Matrix.RotationZ = function (angle) {
  1871. var result = new Matrix();
  1872. Matrix.RotationZToRef(angle, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationZToRef = function (angle, result) {
  1876. var s = Math.sin(angle);
  1877. var c = Math.cos(angle);
  1878. result.m[10] = 1.0;
  1879. result.m[15] = 1.0;
  1880. result.m[0] = c;
  1881. result.m[1] = s;
  1882. result.m[4] = -s;
  1883. result.m[5] = c;
  1884. result.m[2] = 0;
  1885. result.m[3] = 0;
  1886. result.m[6] = 0;
  1887. result.m[7] = 0;
  1888. result.m[8] = 0;
  1889. result.m[9] = 0;
  1890. result.m[11] = 0;
  1891. result.m[12] = 0;
  1892. result.m[13] = 0;
  1893. result.m[14] = 0;
  1894. };
  1895. Matrix.RotationAxis = function (axis, angle) {
  1896. var s = Math.sin(-angle);
  1897. var c = Math.cos(-angle);
  1898. var c1 = 1 - c;
  1899. axis.normalize();
  1900. var result = Matrix.Zero();
  1901. result.m[0] = (axis.x * axis.x) * c1 + c;
  1902. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1903. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1904. result.m[3] = 0.0;
  1905. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1906. result.m[5] = (axis.y * axis.y) * c1 + c;
  1907. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1908. result.m[7] = 0.0;
  1909. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1910. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1911. result.m[10] = (axis.z * axis.z) * c1 + c;
  1912. result.m[11] = 0.0;
  1913. result.m[15] = 1.0;
  1914. return result;
  1915. };
  1916. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1917. var result = new Matrix();
  1918. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1919. return result;
  1920. };
  1921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1923. this._tempQuaternion.toRotationMatrix(result);
  1924. };
  1925. Matrix.Scaling = function (x, y, z) {
  1926. var result = Matrix.Zero();
  1927. Matrix.ScalingToRef(x, y, z, result);
  1928. return result;
  1929. };
  1930. Matrix.ScalingToRef = function (x, y, z, result) {
  1931. result.m[0] = x;
  1932. result.m[1] = 0;
  1933. result.m[2] = 0;
  1934. result.m[3] = 0;
  1935. result.m[4] = 0;
  1936. result.m[5] = y;
  1937. result.m[6] = 0;
  1938. result.m[7] = 0;
  1939. result.m[8] = 0;
  1940. result.m[9] = 0;
  1941. result.m[10] = z;
  1942. result.m[11] = 0;
  1943. result.m[12] = 0;
  1944. result.m[13] = 0;
  1945. result.m[14] = 0;
  1946. result.m[15] = 1.0;
  1947. };
  1948. Matrix.Translation = function (x, y, z) {
  1949. var result = Matrix.Identity();
  1950. Matrix.TranslationToRef(x, y, z, result);
  1951. return result;
  1952. };
  1953. Matrix.TranslationToRef = function (x, y, z, result) {
  1954. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1955. };
  1956. Matrix.LookAtLH = function (eye, target, up) {
  1957. var result = Matrix.Zero();
  1958. Matrix.LookAtLHToRef(eye, target, up, result);
  1959. return result;
  1960. };
  1961. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1962. // Z axis
  1963. target.subtractToRef(eye, this._zAxis);
  1964. this._zAxis.normalize();
  1965. // X axis
  1966. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1967. this._xAxis.normalize();
  1968. // Y axis
  1969. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1970. this._yAxis.normalize();
  1971. // Eye angles
  1972. var ex = -Vector3.Dot(this._xAxis, eye);
  1973. var ey = -Vector3.Dot(this._yAxis, eye);
  1974. var ez = -Vector3.Dot(this._zAxis, eye);
  1975. 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);
  1976. };
  1977. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1978. var out = result.m;
  1979. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1980. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1981. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1982. // cc.kmVec3Subtract(f, pCenter, pEye);
  1983. var f = SIMD.float32x4.sub(center, eye);
  1984. // cc.kmVec3Normalize(f, f);
  1985. var tmp = SIMD.float32x4.mul(f, f);
  1986. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1987. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1988. // cc.kmVec3Assign(up, pUp);
  1989. // cc.kmVec3Normalize(up, up);
  1990. tmp = SIMD.float32x4.mul(up, up);
  1991. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1992. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1993. // cc.kmVec3Cross(s, f, up);
  1994. 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)));
  1995. // cc.kmVec3Normalize(s, s);
  1996. tmp = SIMD.float32x4.mul(s, s);
  1997. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1998. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1999. // cc.kmVec3Cross(u, s, f);
  2000. 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)));
  2001. // cc.kmVec3Normalize(s, s);
  2002. tmp = SIMD.float32x4.mul(s, s);
  2003. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2004. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2005. var zero = SIMD.float32x4.splat(0.0);
  2006. s = SIMD.float32x4.neg(s);
  2007. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2008. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2009. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2010. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2011. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2012. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2013. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2014. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2015. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2016. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2017. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2018. var b3 = SIMD.float32x4.neg(eye);
  2019. b3 = SIMD.float32x4.withW(b3, 1.0);
  2020. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2021. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2022. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2023. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2024. };
  2025. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2026. var matrix = Matrix.Zero();
  2027. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2028. return matrix;
  2029. };
  2030. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2031. var hw = 2.0 / width;
  2032. var hh = 2.0 / height;
  2033. var id = 1.0 / (zfar - znear);
  2034. var nid = znear / (znear - zfar);
  2035. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2036. };
  2037. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2038. var matrix = Matrix.Zero();
  2039. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2040. return matrix;
  2041. };
  2042. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2043. result.m[0] = 2.0 / (right - left);
  2044. result.m[1] = result.m[2] = result.m[3] = 0;
  2045. result.m[5] = 2.0 / (top - bottom);
  2046. result.m[4] = result.m[6] = result.m[7] = 0;
  2047. result.m[10] = -1.0 / (znear - zfar);
  2048. result.m[8] = result.m[9] = result.m[11] = 0;
  2049. result.m[12] = (left + right) / (left - right);
  2050. result.m[13] = (top + bottom) / (bottom - top);
  2051. result.m[14] = znear / (znear - zfar);
  2052. result.m[15] = 1.0;
  2053. };
  2054. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2055. var matrix = Matrix.Zero();
  2056. matrix.m[0] = (2.0 * znear) / width;
  2057. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2058. matrix.m[5] = (2.0 * znear) / height;
  2059. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2060. matrix.m[10] = -zfar / (znear - zfar);
  2061. matrix.m[8] = matrix.m[9] = 0.0;
  2062. matrix.m[11] = 1.0;
  2063. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2064. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2065. return matrix;
  2066. };
  2067. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2068. var matrix = Matrix.Zero();
  2069. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2070. return matrix;
  2071. };
  2072. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2073. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2074. var tan = 1.0 / (Math.tan(fov * 0.5));
  2075. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2076. if (v_fixed) {
  2077. result.m[0] = tan / aspect;
  2078. }
  2079. else {
  2080. result.m[0] = tan;
  2081. }
  2082. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2083. if (v_fixed) {
  2084. result.m[5] = tan;
  2085. }
  2086. else {
  2087. result.m[5] = tan * aspect;
  2088. }
  2089. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2090. result.m[8] = result.m[9] = 0.0;
  2091. result.m[10] = -zfar / (znear - zfar);
  2092. result.m[11] = 1.0;
  2093. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2094. result.m[14] = (znear * zfar) / (znear - zfar);
  2095. };
  2096. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2097. var cw = viewport.width;
  2098. var ch = viewport.height;
  2099. var cx = viewport.x;
  2100. var cy = viewport.y;
  2101. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2102. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2103. };
  2104. Matrix.Transpose = function (matrix) {
  2105. var result = new Matrix();
  2106. result.m[0] = matrix.m[0];
  2107. result.m[1] = matrix.m[4];
  2108. result.m[2] = matrix.m[8];
  2109. result.m[3] = matrix.m[12];
  2110. result.m[4] = matrix.m[1];
  2111. result.m[5] = matrix.m[5];
  2112. result.m[6] = matrix.m[9];
  2113. result.m[7] = matrix.m[13];
  2114. result.m[8] = matrix.m[2];
  2115. result.m[9] = matrix.m[6];
  2116. result.m[10] = matrix.m[10];
  2117. result.m[11] = matrix.m[14];
  2118. result.m[12] = matrix.m[3];
  2119. result.m[13] = matrix.m[7];
  2120. result.m[14] = matrix.m[11];
  2121. result.m[15] = matrix.m[15];
  2122. return result;
  2123. };
  2124. Matrix.Reflection = function (plane) {
  2125. var matrix = new Matrix();
  2126. Matrix.ReflectionToRef(plane, matrix);
  2127. return matrix;
  2128. };
  2129. Matrix.ReflectionToRef = function (plane, result) {
  2130. plane.normalize();
  2131. var x = plane.normal.x;
  2132. var y = plane.normal.y;
  2133. var z = plane.normal.z;
  2134. var temp = -2 * x;
  2135. var temp2 = -2 * y;
  2136. var temp3 = -2 * z;
  2137. result.m[0] = (temp * x) + 1;
  2138. result.m[1] = temp2 * x;
  2139. result.m[2] = temp3 * x;
  2140. result.m[3] = 0.0;
  2141. result.m[4] = temp * y;
  2142. result.m[5] = (temp2 * y) + 1;
  2143. result.m[6] = temp3 * y;
  2144. result.m[7] = 0.0;
  2145. result.m[8] = temp * z;
  2146. result.m[9] = temp2 * z;
  2147. result.m[10] = (temp3 * z) + 1;
  2148. result.m[11] = 0.0;
  2149. result.m[12] = temp * plane.d;
  2150. result.m[13] = temp2 * plane.d;
  2151. result.m[14] = temp3 * plane.d;
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix._tempQuaternion = new Quaternion();
  2155. Matrix._xAxis = Vector3.Zero();
  2156. Matrix._yAxis = Vector3.Zero();
  2157. Matrix._zAxis = Vector3.Zero();
  2158. return Matrix;
  2159. })();
  2160. BABYLON.Matrix = Matrix;
  2161. var Plane = (function () {
  2162. function Plane(a, b, c, d) {
  2163. this.normal = new Vector3(a, b, c);
  2164. this.d = d;
  2165. }
  2166. Plane.prototype.asArray = function () {
  2167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2168. };
  2169. // Methods
  2170. Plane.prototype.clone = function () {
  2171. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2172. };
  2173. Plane.prototype.normalize = function () {
  2174. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2175. var magnitude = 0;
  2176. if (norm !== 0) {
  2177. magnitude = 1.0 / norm;
  2178. }
  2179. this.normal.x *= magnitude;
  2180. this.normal.y *= magnitude;
  2181. this.normal.z *= magnitude;
  2182. this.d *= magnitude;
  2183. return this;
  2184. };
  2185. Plane.prototype.transform = function (transformation) {
  2186. var transposedMatrix = Matrix.Transpose(transformation);
  2187. var x = this.normal.x;
  2188. var y = this.normal.y;
  2189. var z = this.normal.z;
  2190. var d = this.d;
  2191. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2192. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2193. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2194. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2195. return new Plane(normalX, normalY, normalZ, finalD);
  2196. };
  2197. Plane.prototype.dotCoordinate = function (point) {
  2198. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2199. };
  2200. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2201. var x1 = point2.x - point1.x;
  2202. var y1 = point2.y - point1.y;
  2203. var z1 = point2.z - point1.z;
  2204. var x2 = point3.x - point1.x;
  2205. var y2 = point3.y - point1.y;
  2206. var z2 = point3.z - point1.z;
  2207. var yz = (y1 * z2) - (z1 * y2);
  2208. var xz = (z1 * x2) - (x1 * z2);
  2209. var xy = (x1 * y2) - (y1 * x2);
  2210. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2211. var invPyth;
  2212. if (pyth !== 0) {
  2213. invPyth = 1.0 / pyth;
  2214. }
  2215. else {
  2216. invPyth = 0;
  2217. }
  2218. this.normal.x = yz * invPyth;
  2219. this.normal.y = xz * invPyth;
  2220. this.normal.z = xy * invPyth;
  2221. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2222. return this;
  2223. };
  2224. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2225. var dot = Vector3.Dot(this.normal, direction);
  2226. return (dot <= epsilon);
  2227. };
  2228. Plane.prototype.signedDistanceTo = function (point) {
  2229. return Vector3.Dot(point, this.normal) + this.d;
  2230. };
  2231. // Statics
  2232. Plane.FromArray = function (array) {
  2233. return new Plane(array[0], array[1], array[2], array[3]);
  2234. };
  2235. Plane.FromPoints = function (point1, point2, point3) {
  2236. var result = new Plane(0, 0, 0, 0);
  2237. result.copyFromPoints(point1, point2, point3);
  2238. return result;
  2239. };
  2240. Plane.FromPositionAndNormal = function (origin, normal) {
  2241. var result = new Plane(0, 0, 0, 0);
  2242. normal.normalize();
  2243. result.normal = normal;
  2244. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2245. return result;
  2246. };
  2247. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2248. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2249. return Vector3.Dot(point, normal) + d;
  2250. };
  2251. return Plane;
  2252. })();
  2253. BABYLON.Plane = Plane;
  2254. var Viewport = (function () {
  2255. function Viewport(x, y, width, height) {
  2256. this.x = x;
  2257. this.y = y;
  2258. this.width = width;
  2259. this.height = height;
  2260. }
  2261. Viewport.prototype.toGlobal = function (engine) {
  2262. var width = engine.getRenderWidth();
  2263. var height = engine.getRenderHeight();
  2264. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2265. };
  2266. return Viewport;
  2267. })();
  2268. BABYLON.Viewport = Viewport;
  2269. var Frustum = (function () {
  2270. function Frustum() {
  2271. }
  2272. Frustum.GetPlanes = function (transform) {
  2273. var frustumPlanes = [];
  2274. for (var index = 0; index < 6; index++) {
  2275. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2276. }
  2277. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2278. return frustumPlanes;
  2279. };
  2280. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2281. // Near
  2282. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2283. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2284. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2285. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2286. frustumPlanes[0].normalize();
  2287. // Far
  2288. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2289. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2290. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2291. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2292. frustumPlanes[1].normalize();
  2293. // Left
  2294. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2295. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2296. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2297. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2298. frustumPlanes[2].normalize();
  2299. // Right
  2300. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2301. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2302. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2303. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2304. frustumPlanes[3].normalize();
  2305. // Top
  2306. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2307. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2308. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2309. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2310. frustumPlanes[4].normalize();
  2311. // Bottom
  2312. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2313. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2314. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2315. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2316. frustumPlanes[5].normalize();
  2317. };
  2318. return Frustum;
  2319. })();
  2320. BABYLON.Frustum = Frustum;
  2321. var Ray = (function () {
  2322. function Ray(origin, direction, length) {
  2323. if (length === void 0) { length = Number.MAX_VALUE; }
  2324. this.origin = origin;
  2325. this.direction = direction;
  2326. this.length = length;
  2327. }
  2328. // Methods
  2329. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2330. var d = 0.0;
  2331. var maxValue = Number.MAX_VALUE;
  2332. if (Math.abs(this.direction.x) < 0.0000001) {
  2333. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2334. return false;
  2335. }
  2336. }
  2337. else {
  2338. var inv = 1.0 / this.direction.x;
  2339. var min = (minimum.x - this.origin.x) * inv;
  2340. var max = (maximum.x - this.origin.x) * inv;
  2341. if (max === -Infinity) {
  2342. max = Infinity;
  2343. }
  2344. if (min > max) {
  2345. var temp = min;
  2346. min = max;
  2347. max = temp;
  2348. }
  2349. d = Math.max(min, d);
  2350. maxValue = Math.min(max, maxValue);
  2351. if (d > maxValue) {
  2352. return false;
  2353. }
  2354. }
  2355. if (Math.abs(this.direction.y) < 0.0000001) {
  2356. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2357. return false;
  2358. }
  2359. }
  2360. else {
  2361. inv = 1.0 / this.direction.y;
  2362. min = (minimum.y - this.origin.y) * inv;
  2363. max = (maximum.y - this.origin.y) * inv;
  2364. if (max === -Infinity) {
  2365. max = Infinity;
  2366. }
  2367. if (min > max) {
  2368. temp = min;
  2369. min = max;
  2370. max = temp;
  2371. }
  2372. d = Math.max(min, d);
  2373. maxValue = Math.min(max, maxValue);
  2374. if (d > maxValue) {
  2375. return false;
  2376. }
  2377. }
  2378. if (Math.abs(this.direction.z) < 0.0000001) {
  2379. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2380. return false;
  2381. }
  2382. }
  2383. else {
  2384. inv = 1.0 / this.direction.z;
  2385. min = (minimum.z - this.origin.z) * inv;
  2386. max = (maximum.z - this.origin.z) * inv;
  2387. if (max === -Infinity) {
  2388. max = Infinity;
  2389. }
  2390. if (min > max) {
  2391. temp = min;
  2392. min = max;
  2393. max = temp;
  2394. }
  2395. d = Math.max(min, d);
  2396. maxValue = Math.min(max, maxValue);
  2397. if (d > maxValue) {
  2398. return false;
  2399. }
  2400. }
  2401. return true;
  2402. };
  2403. Ray.prototype.intersectsBox = function (box) {
  2404. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2405. };
  2406. Ray.prototype.intersectsSphere = function (sphere) {
  2407. var x = sphere.center.x - this.origin.x;
  2408. var y = sphere.center.y - this.origin.y;
  2409. var z = sphere.center.z - this.origin.z;
  2410. var pyth = (x * x) + (y * y) + (z * z);
  2411. var rr = sphere.radius * sphere.radius;
  2412. if (pyth <= rr) {
  2413. return true;
  2414. }
  2415. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2416. if (dot < 0.0) {
  2417. return false;
  2418. }
  2419. var temp = pyth - (dot * dot);
  2420. return temp <= rr;
  2421. };
  2422. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2423. if (!this._edge1) {
  2424. this._edge1 = Vector3.Zero();
  2425. this._edge2 = Vector3.Zero();
  2426. this._pvec = Vector3.Zero();
  2427. this._tvec = Vector3.Zero();
  2428. this._qvec = Vector3.Zero();
  2429. }
  2430. vertex1.subtractToRef(vertex0, this._edge1);
  2431. vertex2.subtractToRef(vertex0, this._edge2);
  2432. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2433. var det = Vector3.Dot(this._edge1, this._pvec);
  2434. if (det === 0) {
  2435. return null;
  2436. }
  2437. var invdet = 1 / det;
  2438. this.origin.subtractToRef(vertex0, this._tvec);
  2439. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2440. if (bu < 0 || bu > 1.0) {
  2441. return null;
  2442. }
  2443. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2444. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2445. if (bv < 0 || bu + bv > 1.0) {
  2446. return null;
  2447. }
  2448. //check if the distance is longer than the predefined length.
  2449. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2450. if (distance > this.length) {
  2451. return null;
  2452. }
  2453. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2454. };
  2455. // Statics
  2456. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2457. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2458. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2459. var direction = end.subtract(start);
  2460. direction.normalize();
  2461. return new Ray(start, direction);
  2462. };
  2463. /**
  2464. * 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
  2465. * transformed to the given world matrix.
  2466. * @param origin The origin point
  2467. * @param end The end point
  2468. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2469. */
  2470. Ray.CreateNewFromTo = function (origin, end, world) {
  2471. if (world === void 0) { world = Matrix.Identity(); }
  2472. var direction = end.subtract(origin);
  2473. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2474. direction.normalize();
  2475. return Ray.Transform(new Ray(origin, direction, length), world);
  2476. };
  2477. Ray.Transform = function (ray, matrix) {
  2478. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2479. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2480. return new Ray(newOrigin, newDirection, ray.length);
  2481. };
  2482. return Ray;
  2483. })();
  2484. BABYLON.Ray = Ray;
  2485. (function (Space) {
  2486. Space[Space["LOCAL"] = 0] = "LOCAL";
  2487. Space[Space["WORLD"] = 1] = "WORLD";
  2488. })(BABYLON.Space || (BABYLON.Space = {}));
  2489. var Space = BABYLON.Space;
  2490. var Axis = (function () {
  2491. function Axis() {
  2492. }
  2493. Axis.X = new Vector3(1, 0, 0);
  2494. Axis.Y = new Vector3(0, 1, 0);
  2495. Axis.Z = new Vector3(0, 0, 1);
  2496. return Axis;
  2497. })();
  2498. BABYLON.Axis = Axis;
  2499. ;
  2500. var BezierCurve = (function () {
  2501. function BezierCurve() {
  2502. }
  2503. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2504. // Extract X (which is equal to time here)
  2505. var f0 = 1 - 3 * x2 + 3 * x1;
  2506. var f1 = 3 * x2 - 6 * x1;
  2507. var f2 = 3 * x1;
  2508. var refinedT = t;
  2509. for (var i = 0; i < 5; i++) {
  2510. var refinedT2 = refinedT * refinedT;
  2511. var refinedT3 = refinedT2 * refinedT;
  2512. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2513. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2514. refinedT -= (x - t) * slope;
  2515. refinedT = Math.min(1, Math.max(0, refinedT));
  2516. }
  2517. // Resolve cubic bezier for the given x
  2518. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2519. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2520. Math.pow(refinedT, 3);
  2521. };
  2522. return BezierCurve;
  2523. })();
  2524. BABYLON.BezierCurve = BezierCurve;
  2525. (function (Orientation) {
  2526. Orientation[Orientation["CW"] = 0] = "CW";
  2527. Orientation[Orientation["CCW"] = 1] = "CCW";
  2528. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2529. var Orientation = BABYLON.Orientation;
  2530. var Angle = (function () {
  2531. function Angle(radians) {
  2532. var _this = this;
  2533. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2534. this.radians = function () { return _this._radians; };
  2535. this._radians = radians;
  2536. if (this._radians < 0)
  2537. this._radians += (2 * Math.PI);
  2538. }
  2539. Angle.BetweenTwoPoints = function (a, b) {
  2540. var delta = b.subtract(a);
  2541. var theta = Math.atan2(delta.y, delta.x);
  2542. return new Angle(theta);
  2543. };
  2544. Angle.FromRadians = function (radians) {
  2545. return new Angle(radians);
  2546. };
  2547. Angle.FromDegrees = function (degrees) {
  2548. return new Angle(degrees * Math.PI / 180);
  2549. };
  2550. return Angle;
  2551. })();
  2552. BABYLON.Angle = Angle;
  2553. var Arc2 = (function () {
  2554. function Arc2(startPoint, midPoint, endPoint) {
  2555. this.startPoint = startPoint;
  2556. this.midPoint = midPoint;
  2557. this.endPoint = endPoint;
  2558. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2559. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2560. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2561. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2562. 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);
  2563. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2564. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2565. var a1 = this.startAngle.degrees();
  2566. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2567. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2568. // angles correction
  2569. if (a2 - a1 > +180.0)
  2570. a2 -= 360.0;
  2571. if (a2 - a1 < -180.0)
  2572. a2 += 360.0;
  2573. if (a3 - a2 > +180.0)
  2574. a3 -= 360.0;
  2575. if (a3 - a2 < -180.0)
  2576. a3 += 360.0;
  2577. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2578. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2579. }
  2580. return Arc2;
  2581. })();
  2582. BABYLON.Arc2 = Arc2;
  2583. var PathCursor = (function () {
  2584. function PathCursor(path) {
  2585. this.path = path;
  2586. this._onchange = new Array();
  2587. this.value = 0;
  2588. this.animations = new Array();
  2589. }
  2590. PathCursor.prototype.getPoint = function () {
  2591. var point = this.path.getPointAtLengthPosition(this.value);
  2592. return new Vector3(point.x, 0, point.y);
  2593. };
  2594. PathCursor.prototype.moveAhead = function (step) {
  2595. if (step === void 0) { step = 0.002; }
  2596. this.move(step);
  2597. return this;
  2598. };
  2599. PathCursor.prototype.moveBack = function (step) {
  2600. if (step === void 0) { step = 0.002; }
  2601. this.move(-step);
  2602. return this;
  2603. };
  2604. PathCursor.prototype.move = function (step) {
  2605. if (Math.abs(step) > 1) {
  2606. throw "step size should be less than 1.";
  2607. }
  2608. this.value += step;
  2609. this.ensureLimits();
  2610. this.raiseOnChange();
  2611. return this;
  2612. };
  2613. PathCursor.prototype.ensureLimits = function () {
  2614. while (this.value > 1) {
  2615. this.value -= 1;
  2616. }
  2617. while (this.value < 0) {
  2618. this.value += 1;
  2619. }
  2620. return this;
  2621. };
  2622. // used by animation engine
  2623. PathCursor.prototype.markAsDirty = function (propertyName) {
  2624. this.ensureLimits();
  2625. this.raiseOnChange();
  2626. return this;
  2627. };
  2628. PathCursor.prototype.raiseOnChange = function () {
  2629. var _this = this;
  2630. this._onchange.forEach(function (f) { return f(_this); });
  2631. return this;
  2632. };
  2633. PathCursor.prototype.onchange = function (f) {
  2634. this._onchange.push(f);
  2635. return this;
  2636. };
  2637. return PathCursor;
  2638. })();
  2639. BABYLON.PathCursor = PathCursor;
  2640. var Path2 = (function () {
  2641. function Path2(x, y) {
  2642. this._points = new Array();
  2643. this._length = 0;
  2644. this.closed = false;
  2645. this._points.push(new Vector2(x, y));
  2646. }
  2647. Path2.prototype.addLineTo = function (x, y) {
  2648. if (closed) {
  2649. BABYLON.Tools.Error("cannot add lines to closed paths");
  2650. return this;
  2651. }
  2652. var newPoint = new Vector2(x, y);
  2653. var previousPoint = this._points[this._points.length - 1];
  2654. this._points.push(newPoint);
  2655. this._length += newPoint.subtract(previousPoint).length();
  2656. return this;
  2657. };
  2658. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2659. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2660. if (closed) {
  2661. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2662. return this;
  2663. }
  2664. var startPoint = this._points[this._points.length - 1];
  2665. var midPoint = new Vector2(midX, midY);
  2666. var endPoint = new Vector2(endX, endY);
  2667. var arc = new Arc2(startPoint, midPoint, endPoint);
  2668. var increment = arc.angle.radians() / numberOfSegments;
  2669. if (arc.orientation === Orientation.CW)
  2670. increment *= -1;
  2671. var currentAngle = arc.startAngle.radians() + increment;
  2672. for (var i = 0; i < numberOfSegments; i++) {
  2673. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2674. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2675. this.addLineTo(x, y);
  2676. currentAngle += increment;
  2677. }
  2678. return this;
  2679. };
  2680. Path2.prototype.close = function () {
  2681. this.closed = true;
  2682. return this;
  2683. };
  2684. Path2.prototype.length = function () {
  2685. var result = this._length;
  2686. if (!this.closed) {
  2687. var lastPoint = this._points[this._points.length - 1];
  2688. var firstPoint = this._points[0];
  2689. result += (firstPoint.subtract(lastPoint).length());
  2690. }
  2691. return result;
  2692. };
  2693. Path2.prototype.getPoints = function () {
  2694. return this._points;
  2695. };
  2696. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2697. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2698. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2699. return Vector2.Zero();
  2700. }
  2701. var lengthPosition = normalizedLengthPosition * this.length();
  2702. var previousOffset = 0;
  2703. for (var i = 0; i < this._points.length; i++) {
  2704. var j = (i + 1) % this._points.length;
  2705. var a = this._points[i];
  2706. var b = this._points[j];
  2707. var bToA = b.subtract(a);
  2708. var nextOffset = (bToA.length() + previousOffset);
  2709. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2710. var dir = bToA.normalize();
  2711. var localOffset = lengthPosition - previousOffset;
  2712. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2713. }
  2714. previousOffset = nextOffset;
  2715. }
  2716. BABYLON.Tools.Error("internal error");
  2717. return Vector2.Zero();
  2718. };
  2719. Path2.StartingAt = function (x, y) {
  2720. return new Path2(x, y);
  2721. };
  2722. return Path2;
  2723. })();
  2724. BABYLON.Path2 = Path2;
  2725. var Path3D = (function () {
  2726. function Path3D(path, firstNormal) {
  2727. this.path = path;
  2728. this._curve = new Array();
  2729. this._distances = new Array();
  2730. this._tangents = new Array();
  2731. this._normals = new Array();
  2732. this._binormals = new Array();
  2733. for (var p = 0; p < path.length; p++) {
  2734. this._curve[p] = path[p].clone(); // hard copy
  2735. }
  2736. this._compute(firstNormal);
  2737. }
  2738. Path3D.prototype.getCurve = function () {
  2739. return this._curve;
  2740. };
  2741. Path3D.prototype.getTangents = function () {
  2742. return this._tangents;
  2743. };
  2744. Path3D.prototype.getNormals = function () {
  2745. return this._normals;
  2746. };
  2747. Path3D.prototype.getBinormals = function () {
  2748. return this._binormals;
  2749. };
  2750. Path3D.prototype.getDistances = function () {
  2751. return this._distances;
  2752. };
  2753. Path3D.prototype.update = function (path, firstNormal) {
  2754. for (var p = 0; p < path.length; p++) {
  2755. this._curve[p].x = path[p].x;
  2756. this._curve[p].y = path[p].y;
  2757. this._curve[p].z = path[p].z;
  2758. }
  2759. this._compute(firstNormal);
  2760. return this;
  2761. };
  2762. // private function compute() : computes tangents, normals and binormals
  2763. Path3D.prototype._compute = function (firstNormal) {
  2764. var l = this._curve.length;
  2765. // first and last tangents
  2766. this._tangents[0] = this._getFirstNonNullVector(0);
  2767. this._tangents[0].normalize();
  2768. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2769. this._tangents[l - 1].normalize();
  2770. // normals and binormals at first point : arbitrary vector with _normalVector()
  2771. var tg0 = this._tangents[0];
  2772. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2773. this._normals[0] = pp0;
  2774. this._normals[0].normalize();
  2775. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2776. this._binormals[0].normalize();
  2777. this._distances[0] = 0;
  2778. // normals and binormals : next points
  2779. var prev; // previous vector (segment)
  2780. var cur; // current vector (segment)
  2781. var curTang; // current tangent
  2782. var prevNorm; // previous normal
  2783. var prevBinor; // previous binormal
  2784. for (var i = 1; i < l; i++) {
  2785. // tangents
  2786. prev = this._getLastNonNullVector(i);
  2787. if (i < l - 1) {
  2788. cur = this._getFirstNonNullVector(i);
  2789. this._tangents[i] = prev.add(cur);
  2790. this._tangents[i].normalize();
  2791. }
  2792. this._distances[i] = this._distances[i - 1] + prev.length();
  2793. // normals and binormals
  2794. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2795. curTang = this._tangents[i];
  2796. prevNorm = this._normals[i - 1];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. this._normals[i].normalize();
  2800. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2801. this._binormals[i].normalize();
  2802. }
  2803. };
  2804. // private function getFirstNonNullVector(index)
  2805. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2806. Path3D.prototype._getFirstNonNullVector = function (index) {
  2807. var i = 1;
  2808. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2809. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2810. i++;
  2811. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2812. }
  2813. return nNVector;
  2814. };
  2815. // private function getLastNonNullVector(index)
  2816. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2817. Path3D.prototype._getLastNonNullVector = function (index) {
  2818. var i = 1;
  2819. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2820. while (nLVector.length() == 0 && index > i + 1) {
  2821. i++;
  2822. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2823. }
  2824. return nLVector;
  2825. };
  2826. // private function normalVector(v0, vt, va) :
  2827. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2828. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2829. Path3D.prototype._normalVector = function (v0, vt, va) {
  2830. var normal0;
  2831. if (va === undefined || va === null) {
  2832. var point;
  2833. if (vt.y !== 1) {
  2834. point = new Vector3(0, -1, 0);
  2835. }
  2836. else if (vt.x !== 1) {
  2837. point = new Vector3(1, 0, 0);
  2838. }
  2839. else if (vt.z !== 1) {
  2840. point = new Vector3(0, 0, 1);
  2841. }
  2842. normal0 = Vector3.Cross(vt, point);
  2843. }
  2844. else {
  2845. normal0 = Vector3.Cross(vt, va);
  2846. Vector3.CrossToRef(normal0, vt, normal0);
  2847. }
  2848. normal0.normalize();
  2849. return normal0;
  2850. };
  2851. return Path3D;
  2852. })();
  2853. BABYLON.Path3D = Path3D;
  2854. var Curve3 = (function () {
  2855. function Curve3(points) {
  2856. this._length = 0;
  2857. this._points = points;
  2858. this._length = this._computeLength(points);
  2859. }
  2860. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2861. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2862. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2863. var bez = new Array();
  2864. var equation = function (t, val0, val1, val2) {
  2865. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2866. return res;
  2867. };
  2868. for (var i = 0; i <= nbPoints; i++) {
  2869. 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)));
  2870. }
  2871. return new Curve3(bez);
  2872. };
  2873. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2874. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2875. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2876. var bez = new Array();
  2877. var equation = function (t, val0, val1, val2, val3) {
  2878. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2879. return res;
  2880. };
  2881. for (var i = 0; i <= nbPoints; i++) {
  2882. 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)));
  2883. }
  2884. return new Curve3(bez);
  2885. };
  2886. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2887. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2888. var hermite = new Array();
  2889. var step = 1 / nbPoints;
  2890. for (var i = 0; i <= nbPoints; i++) {
  2891. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2892. }
  2893. return new Curve3(hermite);
  2894. };
  2895. Curve3.prototype.getPoints = function () {
  2896. return this._points;
  2897. };
  2898. Curve3.prototype.length = function () {
  2899. return this._length;
  2900. };
  2901. Curve3.prototype.continue = function (curve) {
  2902. var lastPoint = this._points[this._points.length - 1];
  2903. var continuedPoints = this._points.slice();
  2904. var curvePoints = curve.getPoints();
  2905. for (var i = 1; i < curvePoints.length; i++) {
  2906. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2907. }
  2908. var continuedCurve = new Curve3(continuedPoints);
  2909. return continuedCurve;
  2910. };
  2911. Curve3.prototype._computeLength = function (path) {
  2912. var l = 0;
  2913. for (var i = 1; i < path.length; i++) {
  2914. l += (path[i].subtract(path[i - 1])).length();
  2915. }
  2916. return l;
  2917. };
  2918. return Curve3;
  2919. })();
  2920. BABYLON.Curve3 = Curve3;
  2921. // Vertex formats
  2922. var PositionNormalVertex = (function () {
  2923. function PositionNormalVertex(position, normal) {
  2924. if (position === void 0) { position = Vector3.Zero(); }
  2925. if (normal === void 0) { normal = Vector3.Up(); }
  2926. this.position = position;
  2927. this.normal = normal;
  2928. }
  2929. PositionNormalVertex.prototype.clone = function () {
  2930. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2931. };
  2932. return PositionNormalVertex;
  2933. })();
  2934. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2935. var PositionNormalTextureVertex = (function () {
  2936. function PositionNormalTextureVertex(position, normal, uv) {
  2937. if (position === void 0) { position = Vector3.Zero(); }
  2938. if (normal === void 0) { normal = Vector3.Up(); }
  2939. if (uv === void 0) { uv = Vector2.Zero(); }
  2940. this.position = position;
  2941. this.normal = normal;
  2942. this.uv = uv;
  2943. }
  2944. PositionNormalTextureVertex.prototype.clone = function () {
  2945. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2946. };
  2947. return PositionNormalTextureVertex;
  2948. })();
  2949. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2950. // SIMD
  2951. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2952. var previousInvertToRef = Matrix.prototype.invertToRef;
  2953. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2954. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2955. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2956. var SIMDHelper = (function () {
  2957. function SIMDHelper() {
  2958. }
  2959. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2960. get: function () {
  2961. return SIMDHelper._isEnabled;
  2962. },
  2963. enumerable: true,
  2964. configurable: true
  2965. });
  2966. SIMDHelper.DisableSIMD = function () {
  2967. // Replace functions
  2968. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2969. Matrix.prototype.invertToRef = previousInvertToRef;
  2970. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2971. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2972. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2973. SIMDHelper._isEnabled = false;
  2974. };
  2975. SIMDHelper.EnableSIMD = function () {
  2976. if (window.SIMD === undefined) {
  2977. return;
  2978. }
  2979. // Replace functions
  2980. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2981. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2982. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2983. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2984. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2985. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2986. get: function () { return this._data[0]; },
  2987. set: function (value) {
  2988. if (!this._data) {
  2989. this._data = new Float32Array(3);
  2990. }
  2991. this._data[0] = value;
  2992. }
  2993. });
  2994. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2995. get: function () { return this._data[1]; },
  2996. set: function (value) {
  2997. this._data[1] = value;
  2998. }
  2999. });
  3000. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  3001. get: function () { return this._data[2]; },
  3002. set: function (value) {
  3003. this._data[2] = value;
  3004. }
  3005. });
  3006. SIMDHelper._isEnabled = true;
  3007. };
  3008. SIMDHelper._isEnabled = false;
  3009. return SIMDHelper;
  3010. })();
  3011. BABYLON.SIMDHelper = SIMDHelper;
  3012. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3013. SIMDHelper.EnableSIMD();
  3014. }
  3015. })(BABYLON || (BABYLON = {}));
  3016. //# sourceMappingURL=babylon.math.js.map
  3017. var BABYLON;
  3018. (function (BABYLON) {
  3019. var Database = (function () {
  3020. function Database(urlToScene, callbackManifestChecked) {
  3021. // Handling various flavors of prefixed version of IndexedDB
  3022. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3023. this.callbackManifestChecked = callbackManifestChecked;
  3024. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  3025. this.db = null;
  3026. this.enableSceneOffline = false;
  3027. this.enableTexturesOffline = false;
  3028. this.manifestVersionFound = 0;
  3029. this.mustUpdateRessources = false;
  3030. this.hasReachedQuota = false;
  3031. this.checkManifestFile();
  3032. }
  3033. Database.prototype.checkManifestFile = function () {
  3034. var _this = this;
  3035. function noManifestFile() {
  3036. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  3037. that.enableSceneOffline = false;
  3038. that.enableTexturesOffline = false;
  3039. that.callbackManifestChecked(false);
  3040. }
  3041. var that = this;
  3042. var manifestURL = this.currentSceneUrl + ".manifest";
  3043. var xhr = new XMLHttpRequest();
  3044. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3045. xhr.open("GET", manifestURLTimeStamped, true);
  3046. xhr.addEventListener("load", function () {
  3047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3048. try {
  3049. var manifestFile = JSON.parse(xhr.response);
  3050. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3051. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3052. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3053. _this.manifestVersionFound = manifestFile.version;
  3054. }
  3055. if (_this.callbackManifestChecked) {
  3056. _this.callbackManifestChecked(true);
  3057. }
  3058. }
  3059. catch (ex) {
  3060. noManifestFile();
  3061. }
  3062. }
  3063. else {
  3064. noManifestFile();
  3065. }
  3066. }, false);
  3067. xhr.addEventListener("error", function (event) {
  3068. noManifestFile();
  3069. }, false);
  3070. try {
  3071. xhr.send();
  3072. }
  3073. catch (ex) {
  3074. BABYLON.Tools.Error("Error on XHR send request.");
  3075. that.callbackManifestChecked(false);
  3076. }
  3077. };
  3078. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3079. var _this = this;
  3080. function handleError() {
  3081. that.isSupported = false;
  3082. if (errorCallback)
  3083. errorCallback();
  3084. }
  3085. var that = this;
  3086. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3087. // Your browser doesn't support IndexedDB
  3088. this.isSupported = false;
  3089. if (errorCallback)
  3090. errorCallback();
  3091. }
  3092. else {
  3093. // If the DB hasn't been opened or created yet
  3094. if (!this.db) {
  3095. this.hasReachedQuota = false;
  3096. this.isSupported = true;
  3097. var request = this.idbFactory.open("babylonjs", 1);
  3098. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3099. request.onerror = function (event) {
  3100. handleError();
  3101. };
  3102. // executes when a version change transaction cannot complete due to other active transactions
  3103. request.onblocked = function (event) {
  3104. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3105. handleError();
  3106. };
  3107. // DB has been opened successfully
  3108. request.onsuccess = function (event) {
  3109. _this.db = request.result;
  3110. successCallback();
  3111. };
  3112. // Initialization of the DB. Creating Scenes & Textures stores
  3113. request.onupgradeneeded = function (event) {
  3114. _this.db = (event.target).result;
  3115. try {
  3116. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3117. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3118. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3119. }
  3120. catch (ex) {
  3121. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3122. handleError();
  3123. }
  3124. };
  3125. }
  3126. else {
  3127. if (successCallback)
  3128. successCallback();
  3129. }
  3130. }
  3131. };
  3132. Database.prototype.loadImageFromDB = function (url, image) {
  3133. var _this = this;
  3134. var completeURL = Database.ReturnFullUrlLocation(url);
  3135. var saveAndLoadImage = function () {
  3136. if (!_this.hasReachedQuota && _this.db !== null) {
  3137. // the texture is not yet in the DB, let's try to save it
  3138. _this._saveImageIntoDBAsync(completeURL, image);
  3139. }
  3140. else {
  3141. image.src = url;
  3142. }
  3143. };
  3144. if (!this.mustUpdateRessources) {
  3145. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3146. }
  3147. else {
  3148. saveAndLoadImage();
  3149. }
  3150. };
  3151. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3152. if (this.isSupported && this.db !== null) {
  3153. var texture;
  3154. var transaction = this.db.transaction(["textures"]);
  3155. transaction.onabort = function (event) {
  3156. image.src = url;
  3157. };
  3158. transaction.oncomplete = function (event) {
  3159. var blobTextureURL;
  3160. if (texture) {
  3161. var URL = window.URL || window.webkitURL;
  3162. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3163. image.onerror = function () {
  3164. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3165. image.src = url;
  3166. };
  3167. image.src = blobTextureURL;
  3168. }
  3169. else {
  3170. notInDBCallback();
  3171. }
  3172. };
  3173. var getRequest = transaction.objectStore("textures").get(url);
  3174. getRequest.onsuccess = function (event) {
  3175. texture = (event.target).result;
  3176. };
  3177. getRequest.onerror = function (event) {
  3178. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3179. image.src = url;
  3180. };
  3181. }
  3182. else {
  3183. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3184. image.src = url;
  3185. }
  3186. };
  3187. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3188. var _this = this;
  3189. if (this.isSupported) {
  3190. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3191. var generateBlobUrl = function () {
  3192. var blobTextureURL;
  3193. if (blob) {
  3194. var URL = window.URL || window.webkitURL;
  3195. try {
  3196. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3197. }
  3198. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3199. catch (ex) {
  3200. blobTextureURL = URL.createObjectURL(blob);
  3201. }
  3202. }
  3203. image.src = blobTextureURL;
  3204. };
  3205. if (Database.isUASupportingBlobStorage) {
  3206. var xhr = new XMLHttpRequest(), blob;
  3207. xhr.open("GET", url, true);
  3208. xhr.responseType = "blob";
  3209. xhr.addEventListener("load", function () {
  3210. if (xhr.status === 200) {
  3211. // Blob as response (XHR2)
  3212. blob = xhr.response;
  3213. var transaction = _this.db.transaction(["textures"], "readwrite");
  3214. // the transaction could abort because of a QuotaExceededError error
  3215. transaction.onabort = function (event) {
  3216. try {
  3217. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3218. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3219. this.hasReachedQuota = true;
  3220. }
  3221. }
  3222. catch (ex) { }
  3223. generateBlobUrl();
  3224. };
  3225. transaction.oncomplete = function (event) {
  3226. generateBlobUrl();
  3227. };
  3228. var newTexture = { textureUrl: url, data: blob };
  3229. try {
  3230. // Put the blob into the dabase
  3231. var addRequest = transaction.objectStore("textures").put(newTexture);
  3232. addRequest.onsuccess = function (event) {
  3233. };
  3234. addRequest.onerror = function (event) {
  3235. generateBlobUrl();
  3236. };
  3237. }
  3238. catch (ex) {
  3239. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3240. if (ex.code === 25) {
  3241. Database.isUASupportingBlobStorage = false;
  3242. }
  3243. image.src = url;
  3244. }
  3245. }
  3246. else {
  3247. image.src = url;
  3248. }
  3249. }, false);
  3250. xhr.addEventListener("error", function (event) {
  3251. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3252. image.src = url;
  3253. }, false);
  3254. xhr.send();
  3255. }
  3256. else {
  3257. image.src = url;
  3258. }
  3259. }
  3260. else {
  3261. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3262. image.src = url;
  3263. }
  3264. };
  3265. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3266. var _this = this;
  3267. var updateVersion = function (event) {
  3268. // the version is not yet in the DB or we need to update it
  3269. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3270. };
  3271. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3272. };
  3273. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3274. var _this = this;
  3275. if (this.isSupported) {
  3276. var version;
  3277. try {
  3278. var transaction = this.db.transaction(["versions"]);
  3279. transaction.oncomplete = function (event) {
  3280. if (version) {
  3281. // If the version in the JSON file is > than the version in DB
  3282. if (_this.manifestVersionFound > version.data) {
  3283. _this.mustUpdateRessources = true;
  3284. updateInDBCallback();
  3285. }
  3286. else {
  3287. callback(version.data);
  3288. }
  3289. }
  3290. else {
  3291. _this.mustUpdateRessources = true;
  3292. updateInDBCallback();
  3293. }
  3294. };
  3295. transaction.onabort = function (event) {
  3296. callback(-1);
  3297. };
  3298. var getRequest = transaction.objectStore("versions").get(url);
  3299. getRequest.onsuccess = function (event) {
  3300. version = (event.target).result;
  3301. };
  3302. getRequest.onerror = function (event) {
  3303. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3304. callback(-1);
  3305. };
  3306. }
  3307. catch (ex) {
  3308. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3309. callback(-1);
  3310. }
  3311. }
  3312. else {
  3313. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3314. callback(-1);
  3315. }
  3316. };
  3317. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3318. var _this = this;
  3319. if (this.isSupported && !this.hasReachedQuota) {
  3320. try {
  3321. // Open a transaction to the database
  3322. var transaction = this.db.transaction(["versions"], "readwrite");
  3323. // the transaction could abort because of a QuotaExceededError error
  3324. transaction.onabort = function (event) {
  3325. try {
  3326. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3327. _this.hasReachedQuota = true;
  3328. }
  3329. }
  3330. catch (ex) { }
  3331. callback(-1);
  3332. };
  3333. transaction.oncomplete = function (event) {
  3334. callback(_this.manifestVersionFound);
  3335. };
  3336. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3337. // Put the scene into the database
  3338. var addRequest = transaction.objectStore("versions").put(newVersion);
  3339. addRequest.onsuccess = function (event) {
  3340. };
  3341. addRequest.onerror = function (event) {
  3342. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3343. };
  3344. }
  3345. catch (ex) {
  3346. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3347. callback(-1);
  3348. }
  3349. }
  3350. else {
  3351. callback(-1);
  3352. }
  3353. };
  3354. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3355. var _this = this;
  3356. var completeUrl = Database.ReturnFullUrlLocation(url);
  3357. var saveAndLoadFile = function (event) {
  3358. // the scene is not yet in the DB, let's try to save it
  3359. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3360. };
  3361. this._checkVersionFromDB(completeUrl, function (version) {
  3362. if (version !== -1) {
  3363. if (!_this.mustUpdateRessources) {
  3364. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3365. }
  3366. else {
  3367. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3368. }
  3369. }
  3370. else {
  3371. errorCallback();
  3372. }
  3373. });
  3374. };
  3375. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3376. if (this.isSupported) {
  3377. var targetStore;
  3378. if (url.indexOf(".babylon") !== -1) {
  3379. targetStore = "scenes";
  3380. }
  3381. else {
  3382. targetStore = "textures";
  3383. }
  3384. var file;
  3385. var transaction = this.db.transaction([targetStore]);
  3386. transaction.oncomplete = function (event) {
  3387. if (file) {
  3388. callback(file.data);
  3389. }
  3390. else {
  3391. notInDBCallback();
  3392. }
  3393. };
  3394. transaction.onabort = function (event) {
  3395. notInDBCallback();
  3396. };
  3397. var getRequest = transaction.objectStore(targetStore).get(url);
  3398. getRequest.onsuccess = function (event) {
  3399. file = (event.target).result;
  3400. };
  3401. getRequest.onerror = function (event) {
  3402. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3403. notInDBCallback();
  3404. };
  3405. }
  3406. else {
  3407. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3408. callback();
  3409. }
  3410. };
  3411. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3412. var _this = this;
  3413. if (this.isSupported) {
  3414. var targetStore;
  3415. if (url.indexOf(".babylon") !== -1) {
  3416. targetStore = "scenes";
  3417. }
  3418. else {
  3419. targetStore = "textures";
  3420. }
  3421. // Create XHR
  3422. var xhr = new XMLHttpRequest(), fileData;
  3423. xhr.open("GET", url, true);
  3424. if (useArrayBuffer) {
  3425. xhr.responseType = "arraybuffer";
  3426. }
  3427. xhr.onprogress = progressCallback;
  3428. xhr.addEventListener("load", function () {
  3429. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3430. // Blob as response (XHR2)
  3431. //fileData = xhr.responseText;
  3432. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3433. if (!_this.hasReachedQuota) {
  3434. // Open a transaction to the database
  3435. var transaction = _this.db.transaction([targetStore], "readwrite");
  3436. // the transaction could abort because of a QuotaExceededError error
  3437. transaction.onabort = function (event) {
  3438. try {
  3439. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3440. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3441. this.hasReachedQuota = true;
  3442. }
  3443. }
  3444. catch (ex) { }
  3445. callback(fileData);
  3446. };
  3447. transaction.oncomplete = function (event) {
  3448. callback(fileData);
  3449. };
  3450. var newFile;
  3451. if (targetStore === "scenes") {
  3452. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3453. }
  3454. else {
  3455. newFile = { textureUrl: url, data: fileData };
  3456. }
  3457. try {
  3458. // Put the scene into the database
  3459. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3460. addRequest.onsuccess = function (event) {
  3461. };
  3462. addRequest.onerror = function (event) {
  3463. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3464. };
  3465. }
  3466. catch (ex) {
  3467. callback(fileData);
  3468. }
  3469. }
  3470. else {
  3471. callback(fileData);
  3472. }
  3473. }
  3474. else {
  3475. callback();
  3476. }
  3477. }, false);
  3478. xhr.addEventListener("error", function (event) {
  3479. BABYLON.Tools.Error("error on XHR request.");
  3480. callback();
  3481. }, false);
  3482. xhr.send();
  3483. }
  3484. else {
  3485. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3486. callback();
  3487. }
  3488. };
  3489. Database.isUASupportingBlobStorage = true;
  3490. Database.parseURL = function (url) {
  3491. var a = document.createElement('a');
  3492. a.href = url;
  3493. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3494. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3495. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3496. return absLocation;
  3497. };
  3498. Database.ReturnFullUrlLocation = function (url) {
  3499. if (url.indexOf("http:/") === -1) {
  3500. return (BABYLON.Database.parseURL(window.location.href) + url);
  3501. }
  3502. else {
  3503. return url;
  3504. }
  3505. };
  3506. return Database;
  3507. })();
  3508. BABYLON.Database = Database;
  3509. })(BABYLON || (BABYLON = {}));
  3510. //# sourceMappingURL=babylon.database.js.map
  3511. var BABYLON;
  3512. (function (BABYLON) {
  3513. var Internals;
  3514. (function (Internals) {
  3515. /*
  3516. * Based on jsTGALoader - Javascript loader for TGA file
  3517. * By Vincent Thibault
  3518. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3519. */
  3520. var TGATools = (function () {
  3521. function TGATools() {
  3522. }
  3523. TGATools.GetTGAHeader = function (data) {
  3524. var offset = 0;
  3525. var header = {
  3526. id_length: data[offset++],
  3527. colormap_type: data[offset++],
  3528. image_type: data[offset++],
  3529. colormap_index: data[offset++] | data[offset++] << 8,
  3530. colormap_length: data[offset++] | data[offset++] << 8,
  3531. colormap_size: data[offset++],
  3532. origin: [
  3533. data[offset++] | data[offset++] << 8,
  3534. data[offset++] | data[offset++] << 8
  3535. ],
  3536. width: data[offset++] | data[offset++] << 8,
  3537. height: data[offset++] | data[offset++] << 8,
  3538. pixel_size: data[offset++],
  3539. flags: data[offset++]
  3540. };
  3541. return header;
  3542. };
  3543. TGATools.UploadContent = function (gl, data) {
  3544. // Not enough data to contain header ?
  3545. if (data.length < 19) {
  3546. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3547. return;
  3548. }
  3549. // Read Header
  3550. var offset = 18;
  3551. var header = TGATools.GetTGAHeader(data);
  3552. // Assume it's a valid Targa file.
  3553. if (header.id_length + offset > data.length) {
  3554. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3555. return;
  3556. }
  3557. // Skip not needed data
  3558. offset += header.id_length;
  3559. var use_rle = false;
  3560. var use_pal = false;
  3561. var use_rgb = false;
  3562. var use_grey = false;
  3563. // Get some informations.
  3564. switch (header.image_type) {
  3565. case TGATools._TYPE_RLE_INDEXED:
  3566. use_rle = true;
  3567. case TGATools._TYPE_INDEXED:
  3568. use_pal = true;
  3569. break;
  3570. case TGATools._TYPE_RLE_RGB:
  3571. use_rle = true;
  3572. case TGATools._TYPE_RGB:
  3573. use_rgb = true;
  3574. break;
  3575. case TGATools._TYPE_RLE_GREY:
  3576. use_rle = true;
  3577. case TGATools._TYPE_GREY:
  3578. use_grey = true;
  3579. break;
  3580. }
  3581. var pixel_data;
  3582. var numAlphaBits = header.flags & 0xf;
  3583. var pixel_size = header.pixel_size >> 3;
  3584. var pixel_total = header.width * header.height * pixel_size;
  3585. // Read palettes
  3586. var palettes;
  3587. if (use_pal) {
  3588. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3589. }
  3590. // Read LRE
  3591. if (use_rle) {
  3592. pixel_data = new Uint8Array(pixel_total);
  3593. var c, count, i;
  3594. var localOffset = 0;
  3595. var pixels = new Uint8Array(pixel_size);
  3596. while (offset < pixel_total && localOffset < pixel_total) {
  3597. c = data[offset++];
  3598. count = (c & 0x7f) + 1;
  3599. // RLE pixels
  3600. if (c & 0x80) {
  3601. // Bind pixel tmp array
  3602. for (i = 0; i < pixel_size; ++i) {
  3603. pixels[i] = data[offset++];
  3604. }
  3605. // Copy pixel array
  3606. for (i = 0; i < count; ++i) {
  3607. pixel_data.set(pixels, localOffset + i * pixel_size);
  3608. }
  3609. localOffset += pixel_size * count;
  3610. }
  3611. else {
  3612. count *= pixel_size;
  3613. for (i = 0; i < count; ++i) {
  3614. pixel_data[localOffset + i] = data[offset++];
  3615. }
  3616. localOffset += count;
  3617. }
  3618. }
  3619. }
  3620. else {
  3621. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3622. }
  3623. // Load to texture
  3624. var x_start, y_start, x_step, y_step, y_end, x_end;
  3625. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3626. default:
  3627. case TGATools._ORIGIN_UL:
  3628. x_start = 0;
  3629. x_step = 1;
  3630. x_end = header.width;
  3631. y_start = 0;
  3632. y_step = 1;
  3633. y_end = header.height;
  3634. break;
  3635. case TGATools._ORIGIN_BL:
  3636. x_start = 0;
  3637. x_step = 1;
  3638. x_end = header.width;
  3639. y_start = header.height - 1;
  3640. y_step = -1;
  3641. y_end = -1;
  3642. break;
  3643. case TGATools._ORIGIN_UR:
  3644. x_start = header.width - 1;
  3645. x_step = -1;
  3646. x_end = -1;
  3647. y_start = 0;
  3648. y_step = 1;
  3649. y_end = header.height;
  3650. break;
  3651. case TGATools._ORIGIN_BR:
  3652. x_start = header.width - 1;
  3653. x_step = -1;
  3654. x_end = -1;
  3655. y_start = header.height - 1;
  3656. y_step = -1;
  3657. y_end = -1;
  3658. break;
  3659. }
  3660. // Load the specify method
  3661. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3662. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3663. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3664. };
  3665. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3666. var image = pixel_data, colormap = palettes;
  3667. var width = header.width, height = header.height;
  3668. var color, i = 0, x, y;
  3669. var imageData = new Uint8Array(width * height * 4);
  3670. for (y = y_start; y !== y_end; y += y_step) {
  3671. for (x = x_start; x !== x_end; x += x_step, i++) {
  3672. color = image[i];
  3673. imageData[(x + width * y) * 4 + 3] = 255;
  3674. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3675. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3676. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3677. }
  3678. }
  3679. return imageData;
  3680. };
  3681. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3682. var image = pixel_data;
  3683. var width = header.width, height = header.height;
  3684. var color, i = 0, x, y;
  3685. var imageData = new Uint8Array(width * height * 4);
  3686. for (y = y_start; y !== y_end; y += y_step) {
  3687. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3688. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3689. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3690. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3691. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3692. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3693. }
  3694. }
  3695. return imageData;
  3696. };
  3697. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3698. var image = pixel_data;
  3699. var width = header.width, height = header.height;
  3700. var i = 0, x, y;
  3701. var imageData = new Uint8Array(width * height * 4);
  3702. for (y = y_start; y !== y_end; y += y_step) {
  3703. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3704. imageData[(x + width * y) * 4 + 3] = 255;
  3705. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3706. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3707. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3708. }
  3709. }
  3710. return imageData;
  3711. };
  3712. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3713. var image = pixel_data;
  3714. var width = header.width, height = header.height;
  3715. var i = 0, x, y;
  3716. var imageData = new Uint8Array(width * height * 4);
  3717. for (y = y_start; y !== y_end; y += y_step) {
  3718. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3719. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3720. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3721. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3722. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3723. }
  3724. }
  3725. return imageData;
  3726. };
  3727. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3728. var image = pixel_data;
  3729. var width = header.width, height = header.height;
  3730. var color, i = 0, x, y;
  3731. var imageData = new Uint8Array(width * height * 4);
  3732. for (y = y_start; y !== y_end; y += y_step) {
  3733. for (x = x_start; x !== x_end; x += x_step, i++) {
  3734. color = image[i];
  3735. imageData[(x + width * y) * 4 + 0] = color;
  3736. imageData[(x + width * y) * 4 + 1] = color;
  3737. imageData[(x + width * y) * 4 + 2] = color;
  3738. imageData[(x + width * y) * 4 + 3] = 255;
  3739. }
  3740. }
  3741. return imageData;
  3742. };
  3743. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3744. var image = pixel_data;
  3745. var width = header.width, height = header.height;
  3746. var i = 0, x, y;
  3747. var imageData = new Uint8Array(width * height * 4);
  3748. for (y = y_start; y !== y_end; y += y_step) {
  3749. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3750. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3751. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3752. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3753. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3754. }
  3755. }
  3756. return imageData;
  3757. };
  3758. TGATools._TYPE_NO_DATA = 0;
  3759. TGATools._TYPE_INDEXED = 1;
  3760. TGATools._TYPE_RGB = 2;
  3761. TGATools._TYPE_GREY = 3;
  3762. TGATools._TYPE_RLE_INDEXED = 9;
  3763. TGATools._TYPE_RLE_RGB = 10;
  3764. TGATools._TYPE_RLE_GREY = 11;
  3765. TGATools._ORIGIN_MASK = 0x30;
  3766. TGATools._ORIGIN_SHIFT = 0x04;
  3767. TGATools._ORIGIN_BL = 0x00;
  3768. TGATools._ORIGIN_BR = 0x01;
  3769. TGATools._ORIGIN_UL = 0x02;
  3770. TGATools._ORIGIN_UR = 0x03;
  3771. return TGATools;
  3772. })();
  3773. Internals.TGATools = TGATools;
  3774. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3775. })(BABYLON || (BABYLON = {}));
  3776. //# sourceMappingURL=babylon.tools.tga.js.map
  3777. var BABYLON;
  3778. (function (BABYLON) {
  3779. var Internals;
  3780. (function (Internals) {
  3781. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3782. // All values and structures referenced from:
  3783. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3784. var DDS_MAGIC = 0x20534444;
  3785. 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;
  3786. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3787. 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;
  3788. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3789. function FourCCToInt32(value) {
  3790. return value.charCodeAt(0) +
  3791. (value.charCodeAt(1) << 8) +
  3792. (value.charCodeAt(2) << 16) +
  3793. (value.charCodeAt(3) << 24);
  3794. }
  3795. function Int32ToFourCC(value) {
  3796. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3797. }
  3798. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3799. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3800. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3801. var headerLengthInt = 31; // The header length in 32 bit ints
  3802. // Offsets into the header array
  3803. var off_magic = 0;
  3804. var off_size = 1;
  3805. var off_flags = 2;
  3806. var off_height = 3;
  3807. var off_width = 4;
  3808. var off_mipmapCount = 7;
  3809. var off_pfFlags = 20;
  3810. var off_pfFourCC = 21;
  3811. var off_RGBbpp = 22;
  3812. var off_RMask = 23;
  3813. var off_GMask = 24;
  3814. var off_BMask = 25;
  3815. var off_AMask = 26;
  3816. var off_caps1 = 27;
  3817. var off_caps2 = 28;
  3818. ;
  3819. var DDSTools = (function () {
  3820. function DDSTools() {
  3821. }
  3822. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3823. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3824. var mipmapCount = 1;
  3825. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3826. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3827. }
  3828. return {
  3829. width: header[off_width],
  3830. height: header[off_height],
  3831. mipmapCount: mipmapCount,
  3832. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3833. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3834. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3835. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3836. };
  3837. };
  3838. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3839. var byteArray = new Uint8Array(dataLength);
  3840. var srcData = new Uint8Array(arrayBuffer);
  3841. var index = 0;
  3842. for (var y = height - 1; y >= 0; y--) {
  3843. for (var x = 0; x < width; x++) {
  3844. var srcPos = dataOffset + (x + y * width) * 4;
  3845. byteArray[index + 2] = srcData[srcPos];
  3846. byteArray[index + 1] = srcData[srcPos + 1];
  3847. byteArray[index] = srcData[srcPos + 2];
  3848. byteArray[index + 3] = srcData[srcPos + 3];
  3849. index += 4;
  3850. }
  3851. }
  3852. return byteArray;
  3853. };
  3854. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3855. var byteArray = new Uint8Array(dataLength);
  3856. var srcData = new Uint8Array(arrayBuffer);
  3857. var index = 0;
  3858. for (var y = height - 1; y >= 0; y--) {
  3859. for (var x = 0; x < width; x++) {
  3860. var srcPos = dataOffset + (x + y * width) * 3;
  3861. byteArray[index + 2] = srcData[srcPos];
  3862. byteArray[index + 1] = srcData[srcPos + 1];
  3863. byteArray[index] = srcData[srcPos + 2];
  3864. index += 3;
  3865. }
  3866. }
  3867. return byteArray;
  3868. };
  3869. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3870. var byteArray = new Uint8Array(dataLength);
  3871. var srcData = new Uint8Array(arrayBuffer);
  3872. var index = 0;
  3873. for (var y = height - 1; y >= 0; y--) {
  3874. for (var x = 0; x < width; x++) {
  3875. var srcPos = dataOffset + (x + y * width);
  3876. byteArray[index] = srcData[srcPos];
  3877. index++;
  3878. }
  3879. }
  3880. return byteArray;
  3881. };
  3882. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3883. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3884. if (header[off_magic] != DDS_MAGIC) {
  3885. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3886. return;
  3887. }
  3888. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3889. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3890. return;
  3891. }
  3892. if (info.isFourCC) {
  3893. fourCC = header[off_pfFourCC];
  3894. switch (fourCC) {
  3895. case FOURCC_DXT1:
  3896. blockBytes = 8;
  3897. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3898. break;
  3899. case FOURCC_DXT3:
  3900. blockBytes = 16;
  3901. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3902. break;
  3903. case FOURCC_DXT5:
  3904. blockBytes = 16;
  3905. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3906. break;
  3907. default:
  3908. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3909. return;
  3910. }
  3911. }
  3912. mipmapCount = 1;
  3913. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3914. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3915. }
  3916. var bpp = header[off_RGBbpp];
  3917. for (var face = 0; face < faces; face++) {
  3918. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3919. width = header[off_width];
  3920. height = header[off_height];
  3921. dataOffset = header[off_size] + 4;
  3922. for (i = 0; i < mipmapCount; ++i) {
  3923. if (info.isRGB) {
  3924. if (bpp == 24) {
  3925. dataLength = width * height * 3;
  3926. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3927. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3928. }
  3929. else {
  3930. dataLength = width * height * 4;
  3931. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3932. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3933. }
  3934. }
  3935. else if (info.isLuminance) {
  3936. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3937. var unpaddedRowSize = width;
  3938. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3939. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3940. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3941. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3942. }
  3943. else {
  3944. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3945. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3946. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3947. }
  3948. dataOffset += dataLength;
  3949. width *= 0.5;
  3950. height *= 0.5;
  3951. width = Math.max(1.0, width);
  3952. height = Math.max(1.0, height);
  3953. }
  3954. }
  3955. };
  3956. return DDSTools;
  3957. })();
  3958. Internals.DDSTools = DDSTools;
  3959. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3960. })(BABYLON || (BABYLON = {}));
  3961. //# sourceMappingURL=babylon.tools.dds.js.map
  3962. var BABYLON;
  3963. (function (BABYLON) {
  3964. var SmartArray = (function () {
  3965. function SmartArray(capacity) {
  3966. this.length = 0;
  3967. this._duplicateId = 0;
  3968. this.data = new Array(capacity);
  3969. this._id = SmartArray._GlobalId++;
  3970. }
  3971. SmartArray.prototype.push = function (value) {
  3972. this.data[this.length++] = value;
  3973. if (this.length > this.data.length) {
  3974. this.data.length *= 2;
  3975. }
  3976. if (!value.__smartArrayFlags) {
  3977. value.__smartArrayFlags = {};
  3978. }
  3979. value.__smartArrayFlags[this._id] = this._duplicateId;
  3980. };
  3981. SmartArray.prototype.pushNoDuplicate = function (value) {
  3982. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3983. return;
  3984. }
  3985. this.push(value);
  3986. };
  3987. SmartArray.prototype.sort = function (compareFn) {
  3988. this.data.sort(compareFn);
  3989. };
  3990. SmartArray.prototype.reset = function () {
  3991. this.length = 0;
  3992. this._duplicateId++;
  3993. };
  3994. SmartArray.prototype.concat = function (array) {
  3995. if (array.length === 0) {
  3996. return;
  3997. }
  3998. if (this.length + array.length > this.data.length) {
  3999. this.data.length = (this.length + array.length) * 2;
  4000. }
  4001. for (var index = 0; index < array.length; index++) {
  4002. this.data[this.length++] = (array.data || array)[index];
  4003. }
  4004. };
  4005. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4006. if (array.length === 0) {
  4007. return;
  4008. }
  4009. if (this.length + array.length > this.data.length) {
  4010. this.data.length = (this.length + array.length) * 2;
  4011. }
  4012. for (var index = 0; index < array.length; index++) {
  4013. var item = (array.data || array)[index];
  4014. this.pushNoDuplicate(item);
  4015. }
  4016. };
  4017. SmartArray.prototype.indexOf = function (value) {
  4018. var position = this.data.indexOf(value);
  4019. if (position >= this.length) {
  4020. return -1;
  4021. }
  4022. return position;
  4023. };
  4024. // Statics
  4025. SmartArray._GlobalId = 0;
  4026. return SmartArray;
  4027. })();
  4028. BABYLON.SmartArray = SmartArray;
  4029. })(BABYLON || (BABYLON = {}));
  4030. //# sourceMappingURL=babylon.smartArray.js.map
  4031. var BABYLON;
  4032. (function (BABYLON) {
  4033. var SmartCollection = (function () {
  4034. function SmartCollection(capacity) {
  4035. if (capacity === void 0) { capacity = 10; }
  4036. this.count = 0;
  4037. this._initialCapacity = capacity;
  4038. this.items = {};
  4039. this._keys = new Array(this._initialCapacity);
  4040. }
  4041. SmartCollection.prototype.add = function (key, item) {
  4042. if (this.items[key] != undefined) {
  4043. return -1;
  4044. }
  4045. this.items[key] = item;
  4046. //literal keys are always strings, but we keep source type of key in _keys array
  4047. this._keys[this.count++] = key;
  4048. if (this.count > this._keys.length) {
  4049. this._keys.length *= 2;
  4050. }
  4051. return this.count;
  4052. };
  4053. SmartCollection.prototype.remove = function (key) {
  4054. if (this.items[key] == undefined) {
  4055. return -1;
  4056. }
  4057. return this.removeItemOfIndex(this.indexOf(key));
  4058. };
  4059. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4060. if (index < this.count && index > -1) {
  4061. delete this.items[this._keys[index]];
  4062. //here, shifting by hand is better optimised than .splice
  4063. while (index < this.count) {
  4064. this._keys[index] = this._keys[index + 1];
  4065. index++;
  4066. }
  4067. }
  4068. else {
  4069. return -1;
  4070. }
  4071. return --this.count;
  4072. };
  4073. SmartCollection.prototype.indexOf = function (key) {
  4074. for (var i = 0; i !== this.count; i++) {
  4075. if (this._keys[i] === key) {
  4076. return i;
  4077. }
  4078. }
  4079. return -1;
  4080. };
  4081. SmartCollection.prototype.item = function (key) {
  4082. return this.items[key];
  4083. };
  4084. SmartCollection.prototype.getAllKeys = function () {
  4085. if (this.count > 0) {
  4086. var keys = new Array(this.count);
  4087. for (var i = 0; i < this.count; i++) {
  4088. keys[i] = this._keys[i];
  4089. }
  4090. return keys;
  4091. }
  4092. else {
  4093. return undefined;
  4094. }
  4095. };
  4096. SmartCollection.prototype.getKeyByIndex = function (index) {
  4097. if (index < this.count && index > -1) {
  4098. return this._keys[index];
  4099. }
  4100. else {
  4101. return undefined;
  4102. }
  4103. };
  4104. SmartCollection.prototype.getItemByIndex = function (index) {
  4105. if (index < this.count && index > -1) {
  4106. return this.items[this._keys[index]];
  4107. }
  4108. else {
  4109. return undefined;
  4110. }
  4111. };
  4112. SmartCollection.prototype.empty = function () {
  4113. if (this.count > 0) {
  4114. this.count = 0;
  4115. this.items = {};
  4116. this._keys = new Array(this._initialCapacity);
  4117. }
  4118. };
  4119. SmartCollection.prototype.forEach = function (block) {
  4120. var key;
  4121. for (key in this.items) {
  4122. if (this.items.hasOwnProperty(key)) {
  4123. block(this.items[key]);
  4124. }
  4125. }
  4126. };
  4127. return SmartCollection;
  4128. })();
  4129. BABYLON.SmartCollection = SmartCollection;
  4130. })(BABYLON || (BABYLON = {}));
  4131. //# sourceMappingURL=babylon.smartCollection.js.map
  4132. var BABYLON;
  4133. (function (BABYLON) {
  4134. // Screenshots
  4135. var screenshotCanvas;
  4136. var cloneValue = function (source, destinationObject) {
  4137. if (!source)
  4138. return null;
  4139. if (source instanceof BABYLON.Mesh) {
  4140. return null;
  4141. }
  4142. if (source instanceof BABYLON.SubMesh) {
  4143. return source.clone(destinationObject);
  4144. }
  4145. else if (source.clone) {
  4146. return source.clone();
  4147. }
  4148. return null;
  4149. };
  4150. var Tools = (function () {
  4151. function Tools() {
  4152. }
  4153. Tools.SetImmediate = function (action) {
  4154. if (window.setImmediate) {
  4155. window.setImmediate(action);
  4156. }
  4157. else {
  4158. setTimeout(action, 1);
  4159. }
  4160. };
  4161. Tools.IsExponantOfTwo = function (value) {
  4162. var count = 1;
  4163. do {
  4164. count *= 2;
  4165. } while (count < value);
  4166. return count === value;
  4167. };
  4168. Tools.GetExponantOfTwo = function (value, max) {
  4169. var count = 1;
  4170. do {
  4171. count *= 2;
  4172. } while (count < value);
  4173. if (count > max)
  4174. count = max;
  4175. return count;
  4176. };
  4177. Tools.GetFilename = function (path) {
  4178. var index = path.lastIndexOf("/");
  4179. if (index < 0)
  4180. return path;
  4181. return path.substring(index + 1);
  4182. };
  4183. Tools.GetDOMTextContent = function (element) {
  4184. var result = "";
  4185. var child = element.firstChild;
  4186. while (child) {
  4187. if (child.nodeType === 3) {
  4188. result += child.textContent;
  4189. }
  4190. child = child.nextSibling;
  4191. }
  4192. return result;
  4193. };
  4194. Tools.ToDegrees = function (angle) {
  4195. return angle * 180 / Math.PI;
  4196. };
  4197. Tools.ToRadians = function (angle) {
  4198. return angle * Math.PI / 180;
  4199. };
  4200. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4201. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4202. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4203. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4204. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4205. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4206. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4207. }
  4208. return {
  4209. minimum: minimum,
  4210. maximum: maximum
  4211. };
  4212. };
  4213. Tools.ExtractMinAndMax = function (positions, start, count) {
  4214. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4215. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4216. for (var index = start; index < start + count; index++) {
  4217. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4218. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4219. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4220. }
  4221. return {
  4222. minimum: minimum,
  4223. maximum: maximum
  4224. };
  4225. };
  4226. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4227. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4228. return undefined;
  4229. return Array.isArray(obj) ? obj : [obj];
  4230. };
  4231. // Misc.
  4232. Tools.GetPointerPrefix = function () {
  4233. var eventPrefix = "pointer";
  4234. // Check if hand.js is referenced or if the browser natively supports pointer events
  4235. if (!navigator.pointerEnabled) {
  4236. eventPrefix = "mouse";
  4237. }
  4238. return eventPrefix;
  4239. };
  4240. Tools.QueueNewFrame = function (func) {
  4241. if (window.requestAnimationFrame)
  4242. window.requestAnimationFrame(func);
  4243. else if (window.msRequestAnimationFrame)
  4244. window.msRequestAnimationFrame(func);
  4245. else if (window.webkitRequestAnimationFrame)
  4246. window.webkitRequestAnimationFrame(func);
  4247. else if (window.mozRequestAnimationFrame)
  4248. window.mozRequestAnimationFrame(func);
  4249. else if (window.oRequestAnimationFrame)
  4250. window.oRequestAnimationFrame(func);
  4251. else {
  4252. window.setTimeout(func, 16);
  4253. }
  4254. };
  4255. Tools.RequestFullscreen = function (element) {
  4256. if (element.requestFullscreen)
  4257. element.requestFullscreen();
  4258. else if (element.msRequestFullscreen)
  4259. element.msRequestFullscreen();
  4260. else if (element.webkitRequestFullscreen)
  4261. element.webkitRequestFullscreen();
  4262. else if (element.mozRequestFullScreen)
  4263. element.mozRequestFullScreen();
  4264. };
  4265. Tools.ExitFullscreen = function () {
  4266. if (document.exitFullscreen) {
  4267. document.exitFullscreen();
  4268. }
  4269. else if (document.mozCancelFullScreen) {
  4270. document.mozCancelFullScreen();
  4271. }
  4272. else if (document.webkitCancelFullScreen) {
  4273. document.webkitCancelFullScreen();
  4274. }
  4275. else if (document.msCancelFullScreen) {
  4276. document.msCancelFullScreen();
  4277. }
  4278. };
  4279. // External files
  4280. Tools.CleanUrl = function (url) {
  4281. url = url.replace(/#/mg, "%23");
  4282. return url;
  4283. };
  4284. Tools.LoadImage = function (url, onload, onerror, database) {
  4285. url = Tools.CleanUrl(url);
  4286. var img = new Image();
  4287. if (url.substr(0, 5) !== "data:")
  4288. img.crossOrigin = 'anonymous';
  4289. img.onload = function () {
  4290. onload(img);
  4291. };
  4292. img.onerror = function (err) {
  4293. onerror(img, err);
  4294. };
  4295. var noIndexedDB = function () {
  4296. img.src = url;
  4297. };
  4298. var loadFromIndexedDB = function () {
  4299. database.loadImageFromDB(url, img);
  4300. };
  4301. //ANY database to do!
  4302. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4303. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4304. }
  4305. else {
  4306. if (url.indexOf("file:") === -1) {
  4307. noIndexedDB();
  4308. }
  4309. else {
  4310. try {
  4311. var textureName = url.substring(5);
  4312. var blobURL;
  4313. try {
  4314. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4315. }
  4316. catch (ex) {
  4317. // Chrome doesn't support oneTimeOnly parameter
  4318. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4319. }
  4320. img.src = blobURL;
  4321. }
  4322. catch (e) {
  4323. Tools.Log("Error while trying to load texture: " + textureName);
  4324. img.src = null;
  4325. }
  4326. }
  4327. }
  4328. return img;
  4329. };
  4330. //ANY
  4331. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4332. url = Tools.CleanUrl(url);
  4333. var noIndexedDB = function () {
  4334. var request = new XMLHttpRequest();
  4335. var loadUrl = Tools.BaseUrl + url;
  4336. request.open('GET', loadUrl, true);
  4337. if (useArrayBuffer) {
  4338. request.responseType = "arraybuffer";
  4339. }
  4340. request.onprogress = progressCallBack;
  4341. request.onreadystatechange = function () {
  4342. if (request.readyState === 4) {
  4343. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4344. callback(!useArrayBuffer ? request.responseText : request.response);
  4345. }
  4346. else {
  4347. if (onError) {
  4348. onError();
  4349. }
  4350. else {
  4351. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4352. }
  4353. }
  4354. }
  4355. };
  4356. request.send(null);
  4357. };
  4358. var loadFromIndexedDB = function () {
  4359. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4360. };
  4361. if (url.indexOf("file:") !== -1) {
  4362. var fileName = url.substring(5);
  4363. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4364. }
  4365. else {
  4366. // Caching all files
  4367. if (database && database.enableSceneOffline) {
  4368. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4369. }
  4370. else {
  4371. noIndexedDB();
  4372. }
  4373. }
  4374. };
  4375. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4376. var reader = new FileReader();
  4377. reader.onload = function (e) {
  4378. //target doesn't have result from ts 1.3
  4379. callback(e.target['result']);
  4380. };
  4381. reader.onprogress = progressCallback;
  4382. reader.readAsDataURL(fileToLoad);
  4383. };
  4384. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4385. var reader = new FileReader();
  4386. reader.onerror = function (e) {
  4387. Tools.Log("Error while reading file: " + fileToLoad.name);
  4388. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4389. };
  4390. reader.onload = function (e) {
  4391. //target doesn't have result from ts 1.3
  4392. callback(e.target['result']);
  4393. };
  4394. reader.onprogress = progressCallBack;
  4395. if (!useArrayBuffer) {
  4396. // Asynchronous read
  4397. reader.readAsText(fileToLoad);
  4398. }
  4399. else {
  4400. reader.readAsArrayBuffer(fileToLoad);
  4401. }
  4402. };
  4403. // Misc.
  4404. Tools.Clamp = function (value, min, max) {
  4405. if (min === void 0) { min = 0; }
  4406. if (max === void 0) { max = 1; }
  4407. return Math.min(max, Math.max(min, value));
  4408. };
  4409. // Returns -1 when value is a negative number and
  4410. // +1 when value is a positive number.
  4411. Tools.Sign = function (value) {
  4412. value = +value; // convert to a number
  4413. if (value === 0 || isNaN(value))
  4414. return value;
  4415. return value > 0 ? 1 : -1;
  4416. };
  4417. Tools.Format = function (value, decimals) {
  4418. if (decimals === void 0) { decimals = 2; }
  4419. return value.toFixed(decimals);
  4420. };
  4421. Tools.CheckExtends = function (v, min, max) {
  4422. if (v.x < min.x)
  4423. min.x = v.x;
  4424. if (v.y < min.y)
  4425. min.y = v.y;
  4426. if (v.z < min.z)
  4427. min.z = v.z;
  4428. if (v.x > max.x)
  4429. max.x = v.x;
  4430. if (v.y > max.y)
  4431. max.y = v.y;
  4432. if (v.z > max.z)
  4433. max.z = v.z;
  4434. };
  4435. Tools.WithinEpsilon = function (a, b, epsilon) {
  4436. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4437. var num = a - b;
  4438. return -epsilon <= num && num <= epsilon;
  4439. };
  4440. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4441. for (var prop in source) {
  4442. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4443. continue;
  4444. }
  4445. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4446. continue;
  4447. }
  4448. var sourceValue = source[prop];
  4449. var typeOfSourceValue = typeof sourceValue;
  4450. if (typeOfSourceValue === "function") {
  4451. continue;
  4452. }
  4453. if (typeOfSourceValue === "object") {
  4454. if (sourceValue instanceof Array) {
  4455. destination[prop] = [];
  4456. if (sourceValue.length > 0) {
  4457. if (typeof sourceValue[0] == "object") {
  4458. for (var index = 0; index < sourceValue.length; index++) {
  4459. var clonedValue = cloneValue(sourceValue[index], destination);
  4460. if (destination[prop].indexOf(clonedValue) === -1) {
  4461. destination[prop].push(clonedValue);
  4462. }
  4463. }
  4464. }
  4465. else {
  4466. destination[prop] = sourceValue.slice(0);
  4467. }
  4468. }
  4469. }
  4470. else {
  4471. destination[prop] = cloneValue(sourceValue, destination);
  4472. }
  4473. }
  4474. else {
  4475. destination[prop] = sourceValue;
  4476. }
  4477. }
  4478. };
  4479. Tools.IsEmpty = function (obj) {
  4480. for (var i in obj) {
  4481. return false;
  4482. }
  4483. return true;
  4484. };
  4485. Tools.RegisterTopRootEvents = function (events) {
  4486. for (var index = 0; index < events.length; index++) {
  4487. var event = events[index];
  4488. window.addEventListener(event.name, event.handler, false);
  4489. try {
  4490. if (window.parent) {
  4491. window.parent.addEventListener(event.name, event.handler, false);
  4492. }
  4493. }
  4494. catch (e) {
  4495. }
  4496. }
  4497. };
  4498. Tools.UnregisterTopRootEvents = function (events) {
  4499. for (var index = 0; index < events.length; index++) {
  4500. var event = events[index];
  4501. window.removeEventListener(event.name, event.handler);
  4502. try {
  4503. if (window.parent) {
  4504. window.parent.removeEventListener(event.name, event.handler);
  4505. }
  4506. }
  4507. catch (e) {
  4508. }
  4509. }
  4510. };
  4511. Tools.DumpFramebuffer = function (width, height, engine) {
  4512. // Read the contents of the framebuffer
  4513. var numberOfChannelsByLine = width * 4;
  4514. var halfHeight = height / 2;
  4515. //Reading datas from WebGL
  4516. var data = engine.readPixels(0, 0, width, height);
  4517. //To flip image on Y axis.
  4518. for (var i = 0; i < halfHeight; i++) {
  4519. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4520. var currentCell = j + i * numberOfChannelsByLine;
  4521. var targetLine = height - i - 1;
  4522. var targetCell = j + targetLine * numberOfChannelsByLine;
  4523. var temp = data[currentCell];
  4524. data[currentCell] = data[targetCell];
  4525. data[targetCell] = temp;
  4526. }
  4527. }
  4528. // Create a 2D canvas to store the result
  4529. if (!screenshotCanvas) {
  4530. screenshotCanvas = document.createElement('canvas');
  4531. }
  4532. screenshotCanvas.width = width;
  4533. screenshotCanvas.height = height;
  4534. var context = screenshotCanvas.getContext('2d');
  4535. // Copy the pixels to a 2D canvas
  4536. var imageData = context.createImageData(width, height);
  4537. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4538. var castData = imageData.data;
  4539. castData.set(data);
  4540. context.putImageData(imageData, 0, 0);
  4541. var base64Image = screenshotCanvas.toDataURL();
  4542. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4543. if (("download" in document.createElement("a"))) {
  4544. var a = window.document.createElement("a");
  4545. a.href = base64Image;
  4546. var date = new Date();
  4547. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4548. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4549. window.document.body.appendChild(a);
  4550. a.addEventListener("click", function () {
  4551. a.parentElement.removeChild(a);
  4552. });
  4553. a.click();
  4554. }
  4555. else {
  4556. var newWindow = window.open("");
  4557. var img = newWindow.document.createElement("img");
  4558. img.src = base64Image;
  4559. newWindow.document.body.appendChild(img);
  4560. }
  4561. };
  4562. Tools.CreateScreenshot = function (engine, camera, size) {
  4563. var width;
  4564. var height;
  4565. var scene = camera.getScene();
  4566. var previousCamera = null;
  4567. if (scene.activeCamera !== camera) {
  4568. previousCamera = scene.activeCamera;
  4569. scene.activeCamera = camera;
  4570. }
  4571. //If a precision value is specified
  4572. if (size.precision) {
  4573. width = Math.round(engine.getRenderWidth() * size.precision);
  4574. height = Math.round(width / engine.getAspectRatio(camera));
  4575. size = { width: width, height: height };
  4576. }
  4577. else if (size.width && size.height) {
  4578. width = size.width;
  4579. height = size.height;
  4580. }
  4581. else if (size.width && !size.height) {
  4582. width = size.width;
  4583. height = Math.round(width / engine.getAspectRatio(camera));
  4584. size = { width: width, height: height };
  4585. }
  4586. else if (size.height && !size.width) {
  4587. height = size.height;
  4588. width = Math.round(height * engine.getAspectRatio(camera));
  4589. size = { width: width, height: height };
  4590. }
  4591. else if (!isNaN(size)) {
  4592. height = size;
  4593. width = size;
  4594. }
  4595. else {
  4596. Tools.Error("Invalid 'size' parameter !");
  4597. return;
  4598. }
  4599. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4600. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4601. texture.renderList = scene.meshes;
  4602. texture.onAfterRender = function () {
  4603. Tools.DumpFramebuffer(width, height, engine);
  4604. };
  4605. scene.incrementRenderId();
  4606. texture.render(true);
  4607. texture.dispose();
  4608. if (previousCamera) {
  4609. scene.activeCamera = previousCamera;
  4610. }
  4611. };
  4612. // XHR response validator for local file scenario
  4613. Tools.ValidateXHRData = function (xhr, dataType) {
  4614. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4615. if (dataType === void 0) { dataType = 7; }
  4616. try {
  4617. if (dataType & 1) {
  4618. if (xhr.responseText && xhr.responseText.length > 0) {
  4619. return true;
  4620. }
  4621. else if (dataType === 1) {
  4622. return false;
  4623. }
  4624. }
  4625. if (dataType & 2) {
  4626. // Check header width and height since there is no "TGA" magic number
  4627. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4628. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4629. return true;
  4630. }
  4631. else if (dataType === 2) {
  4632. return false;
  4633. }
  4634. }
  4635. if (dataType & 4) {
  4636. // Check for the "DDS" magic number
  4637. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4638. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4639. return true;
  4640. }
  4641. else {
  4642. return false;
  4643. }
  4644. }
  4645. }
  4646. catch (e) {
  4647. }
  4648. return false;
  4649. };
  4650. Object.defineProperty(Tools, "NoneLogLevel", {
  4651. get: function () {
  4652. return Tools._NoneLogLevel;
  4653. },
  4654. enumerable: true,
  4655. configurable: true
  4656. });
  4657. Object.defineProperty(Tools, "MessageLogLevel", {
  4658. get: function () {
  4659. return Tools._MessageLogLevel;
  4660. },
  4661. enumerable: true,
  4662. configurable: true
  4663. });
  4664. Object.defineProperty(Tools, "WarningLogLevel", {
  4665. get: function () {
  4666. return Tools._WarningLogLevel;
  4667. },
  4668. enumerable: true,
  4669. configurable: true
  4670. });
  4671. Object.defineProperty(Tools, "ErrorLogLevel", {
  4672. get: function () {
  4673. return Tools._ErrorLogLevel;
  4674. },
  4675. enumerable: true,
  4676. configurable: true
  4677. });
  4678. Object.defineProperty(Tools, "AllLogLevel", {
  4679. get: function () {
  4680. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4681. },
  4682. enumerable: true,
  4683. configurable: true
  4684. });
  4685. Tools._AddLogEntry = function (entry) {
  4686. Tools._LogCache = entry + Tools._LogCache;
  4687. if (Tools.OnNewCacheEntry) {
  4688. Tools.OnNewCacheEntry(entry);
  4689. }
  4690. };
  4691. Tools._FormatMessage = function (message) {
  4692. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4693. var date = new Date();
  4694. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4695. };
  4696. Tools._LogDisabled = function (message) {
  4697. // nothing to do
  4698. };
  4699. Tools._LogEnabled = function (message) {
  4700. var formattedMessage = Tools._FormatMessage(message);
  4701. console.log("BJS - " + formattedMessage);
  4702. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4703. Tools._AddLogEntry(entry);
  4704. };
  4705. Tools._WarnDisabled = function (message) {
  4706. // nothing to do
  4707. };
  4708. Tools._WarnEnabled = function (message) {
  4709. var formattedMessage = Tools._FormatMessage(message);
  4710. console.warn("BJS - " + formattedMessage);
  4711. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4712. Tools._AddLogEntry(entry);
  4713. };
  4714. Tools._ErrorDisabled = function (message) {
  4715. // nothing to do
  4716. };
  4717. Tools._ErrorEnabled = function (message) {
  4718. var formattedMessage = Tools._FormatMessage(message);
  4719. console.error("BJS - " + formattedMessage);
  4720. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4721. Tools._AddLogEntry(entry);
  4722. };
  4723. Object.defineProperty(Tools, "LogCache", {
  4724. get: function () {
  4725. return Tools._LogCache;
  4726. },
  4727. enumerable: true,
  4728. configurable: true
  4729. });
  4730. Object.defineProperty(Tools, "LogLevels", {
  4731. set: function (level) {
  4732. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4733. Tools.Log = Tools._LogEnabled;
  4734. }
  4735. else {
  4736. Tools.Log = Tools._LogDisabled;
  4737. }
  4738. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4739. Tools.Warn = Tools._WarnEnabled;
  4740. }
  4741. else {
  4742. Tools.Warn = Tools._WarnDisabled;
  4743. }
  4744. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4745. Tools.Error = Tools._ErrorEnabled;
  4746. }
  4747. else {
  4748. Tools.Error = Tools._ErrorDisabled;
  4749. }
  4750. },
  4751. enumerable: true,
  4752. configurable: true
  4753. });
  4754. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4755. get: function () {
  4756. return Tools._PerformanceNoneLogLevel;
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4762. get: function () {
  4763. return Tools._PerformanceUserMarkLogLevel;
  4764. },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4769. get: function () {
  4770. return Tools._PerformanceConsoleLogLevel;
  4771. },
  4772. enumerable: true,
  4773. configurable: true
  4774. });
  4775. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4776. set: function (level) {
  4777. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4778. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4779. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4780. return;
  4781. }
  4782. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4783. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4784. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4785. return;
  4786. }
  4787. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4788. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4789. },
  4790. enumerable: true,
  4791. configurable: true
  4792. });
  4793. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4794. };
  4795. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4796. };
  4797. Tools._StartUserMark = function (counterName, condition) {
  4798. if (condition === void 0) { condition = true; }
  4799. if (!condition || !Tools._performance.mark) {
  4800. return;
  4801. }
  4802. Tools._performance.mark(counterName + "-Begin");
  4803. };
  4804. Tools._EndUserMark = function (counterName, condition) {
  4805. if (condition === void 0) { condition = true; }
  4806. if (!condition || !Tools._performance.mark) {
  4807. return;
  4808. }
  4809. Tools._performance.mark(counterName + "-End");
  4810. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4811. };
  4812. Tools._StartPerformanceConsole = function (counterName, condition) {
  4813. if (condition === void 0) { condition = true; }
  4814. if (!condition) {
  4815. return;
  4816. }
  4817. Tools._StartUserMark(counterName, condition);
  4818. if (console.time) {
  4819. console.time(counterName);
  4820. }
  4821. };
  4822. Tools._EndPerformanceConsole = function (counterName, condition) {
  4823. if (condition === void 0) { condition = true; }
  4824. if (!condition) {
  4825. return;
  4826. }
  4827. Tools._EndUserMark(counterName, condition);
  4828. if (console.time) {
  4829. console.timeEnd(counterName);
  4830. }
  4831. };
  4832. Object.defineProperty(Tools, "Now", {
  4833. get: function () {
  4834. if (window.performance && window.performance.now) {
  4835. return window.performance.now();
  4836. }
  4837. return new Date().getTime();
  4838. },
  4839. enumerable: true,
  4840. configurable: true
  4841. });
  4842. // Deprecated
  4843. Tools.GetFps = function () {
  4844. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4845. return 0;
  4846. };
  4847. Tools.BaseUrl = "";
  4848. // Logs
  4849. Tools._NoneLogLevel = 0;
  4850. Tools._MessageLogLevel = 1;
  4851. Tools._WarningLogLevel = 2;
  4852. Tools._ErrorLogLevel = 4;
  4853. Tools._LogCache = "";
  4854. Tools.Log = Tools._LogEnabled;
  4855. Tools.Warn = Tools._WarnEnabled;
  4856. Tools.Error = Tools._ErrorEnabled;
  4857. // Performances
  4858. Tools._PerformanceNoneLogLevel = 0;
  4859. Tools._PerformanceUserMarkLogLevel = 1;
  4860. Tools._PerformanceConsoleLogLevel = 2;
  4861. Tools._performance = window.performance;
  4862. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4863. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4864. return Tools;
  4865. })();
  4866. BABYLON.Tools = Tools;
  4867. /**
  4868. * An implementation of a loop for asynchronous functions.
  4869. */
  4870. var AsyncLoop = (function () {
  4871. /**
  4872. * Constroctor.
  4873. * @param iterations the number of iterations.
  4874. * @param _fn the function to run each iteration
  4875. * @param _successCallback the callback that will be called upon succesful execution
  4876. * @param offset starting offset.
  4877. */
  4878. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4879. if (offset === void 0) { offset = 0; }
  4880. this.iterations = iterations;
  4881. this._fn = _fn;
  4882. this._successCallback = _successCallback;
  4883. this.index = offset - 1;
  4884. this._done = false;
  4885. }
  4886. /**
  4887. * Execute the next iteration. Must be called after the last iteration was finished.
  4888. */
  4889. AsyncLoop.prototype.executeNext = function () {
  4890. if (!this._done) {
  4891. if (this.index + 1 < this.iterations) {
  4892. ++this.index;
  4893. this._fn(this);
  4894. }
  4895. else {
  4896. this.breakLoop();
  4897. }
  4898. }
  4899. };
  4900. /**
  4901. * Break the loop and run the success callback.
  4902. */
  4903. AsyncLoop.prototype.breakLoop = function () {
  4904. this._done = true;
  4905. this._successCallback();
  4906. };
  4907. /**
  4908. * Helper function
  4909. */
  4910. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4911. if (offset === void 0) { offset = 0; }
  4912. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4913. loop.executeNext();
  4914. return loop;
  4915. };
  4916. /**
  4917. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4918. * @param iterations total number of iterations
  4919. * @param syncedIterations number of synchronous iterations in each async iteration.
  4920. * @param fn the function to call each iteration.
  4921. * @param callback a success call back that will be called when iterating stops.
  4922. * @param breakFunction a break condition (optional)
  4923. * @param timeout timeout settings for the setTimeout function. default - 0.
  4924. * @constructor
  4925. */
  4926. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4927. if (timeout === void 0) { timeout = 0; }
  4928. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4929. if (breakFunction && breakFunction())
  4930. loop.breakLoop();
  4931. else {
  4932. setTimeout(function () {
  4933. for (var i = 0; i < syncedIterations; ++i) {
  4934. var iteration = (loop.index * syncedIterations) + i;
  4935. if (iteration >= iterations)
  4936. break;
  4937. fn(iteration);
  4938. if (breakFunction && breakFunction()) {
  4939. loop.breakLoop();
  4940. break;
  4941. }
  4942. }
  4943. loop.executeNext();
  4944. }, timeout);
  4945. }
  4946. }, callback);
  4947. };
  4948. return AsyncLoop;
  4949. })();
  4950. BABYLON.AsyncLoop = AsyncLoop;
  4951. })(BABYLON || (BABYLON = {}));
  4952. //# sourceMappingURL=babylon.tools.js.map
  4953. var BABYLON;
  4954. (function (BABYLON) {
  4955. var _DepthCullingState = (function () {
  4956. function _DepthCullingState() {
  4957. this._isDepthTestDirty = false;
  4958. this._isDepthMaskDirty = false;
  4959. this._isDepthFuncDirty = false;
  4960. this._isCullFaceDirty = false;
  4961. this._isCullDirty = false;
  4962. this._isZOffsetDirty = false;
  4963. }
  4964. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4965. get: function () {
  4966. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4967. },
  4968. enumerable: true,
  4969. configurable: true
  4970. });
  4971. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4972. get: function () {
  4973. return this._zOffset;
  4974. },
  4975. set: function (value) {
  4976. if (this._zOffset === value) {
  4977. return;
  4978. }
  4979. this._zOffset = value;
  4980. this._isZOffsetDirty = true;
  4981. },
  4982. enumerable: true,
  4983. configurable: true
  4984. });
  4985. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4986. get: function () {
  4987. return this._cullFace;
  4988. },
  4989. set: function (value) {
  4990. if (this._cullFace === value) {
  4991. return;
  4992. }
  4993. this._cullFace = value;
  4994. this._isCullFaceDirty = true;
  4995. },
  4996. enumerable: true,
  4997. configurable: true
  4998. });
  4999. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5000. get: function () {
  5001. return this._cull;
  5002. },
  5003. set: function (value) {
  5004. if (this._cull === value) {
  5005. return;
  5006. }
  5007. this._cull = value;
  5008. this._isCullDirty = true;
  5009. },
  5010. enumerable: true,
  5011. configurable: true
  5012. });
  5013. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5014. get: function () {
  5015. return this._depthFunc;
  5016. },
  5017. set: function (value) {
  5018. if (this._depthFunc === value) {
  5019. return;
  5020. }
  5021. this._depthFunc = value;
  5022. this._isDepthFuncDirty = true;
  5023. },
  5024. enumerable: true,
  5025. configurable: true
  5026. });
  5027. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5028. get: function () {
  5029. return this._depthMask;
  5030. },
  5031. set: function (value) {
  5032. if (this._depthMask === value) {
  5033. return;
  5034. }
  5035. this._depthMask = value;
  5036. this._isDepthMaskDirty = true;
  5037. },
  5038. enumerable: true,
  5039. configurable: true
  5040. });
  5041. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5042. get: function () {
  5043. return this._depthTest;
  5044. },
  5045. set: function (value) {
  5046. if (this._depthTest === value) {
  5047. return;
  5048. }
  5049. this._depthTest = value;
  5050. this._isDepthTestDirty = true;
  5051. },
  5052. enumerable: true,
  5053. configurable: true
  5054. });
  5055. _DepthCullingState.prototype.reset = function () {
  5056. this._depthMask = true;
  5057. this._depthTest = true;
  5058. this._depthFunc = null;
  5059. this._cull = null;
  5060. this._cullFace = null;
  5061. this._zOffset = 0;
  5062. this._isDepthTestDirty = true;
  5063. this._isDepthMaskDirty = true;
  5064. this._isDepthFuncDirty = false;
  5065. this._isCullFaceDirty = false;
  5066. this._isCullDirty = false;
  5067. this._isZOffsetDirty = false;
  5068. };
  5069. _DepthCullingState.prototype.apply = function (gl) {
  5070. if (!this.isDirty) {
  5071. return;
  5072. }
  5073. // Cull
  5074. if (this._isCullDirty) {
  5075. if (this.cull) {
  5076. gl.enable(gl.CULL_FACE);
  5077. }
  5078. else {
  5079. gl.disable(gl.CULL_FACE);
  5080. }
  5081. this._isCullDirty = false;
  5082. }
  5083. // Cull face
  5084. if (this._isCullFaceDirty) {
  5085. gl.cullFace(this.cullFace);
  5086. this._isCullFaceDirty = false;
  5087. }
  5088. // Depth mask
  5089. if (this._isDepthMaskDirty) {
  5090. gl.depthMask(this.depthMask);
  5091. this._isDepthMaskDirty = false;
  5092. }
  5093. // Depth test
  5094. if (this._isDepthTestDirty) {
  5095. if (this.depthTest) {
  5096. gl.enable(gl.DEPTH_TEST);
  5097. }
  5098. else {
  5099. gl.disable(gl.DEPTH_TEST);
  5100. }
  5101. this._isDepthTestDirty = false;
  5102. }
  5103. // Depth func
  5104. if (this._isDepthFuncDirty) {
  5105. gl.depthFunc(this.depthFunc);
  5106. this._isDepthFuncDirty = false;
  5107. }
  5108. // zOffset
  5109. if (this._isZOffsetDirty) {
  5110. if (this.zOffset) {
  5111. gl.enable(gl.POLYGON_OFFSET_FILL);
  5112. gl.polygonOffset(this.zOffset, 0);
  5113. }
  5114. else {
  5115. gl.disable(gl.POLYGON_OFFSET_FILL);
  5116. }
  5117. this._isZOffsetDirty = false;
  5118. }
  5119. };
  5120. return _DepthCullingState;
  5121. })();
  5122. BABYLON._DepthCullingState = _DepthCullingState;
  5123. var _AlphaState = (function () {
  5124. function _AlphaState() {
  5125. this._isAlphaBlendDirty = false;
  5126. this._isBlendFunctionParametersDirty = false;
  5127. this._alphaBlend = false;
  5128. this._blendFunctionParameters = new Array(4);
  5129. }
  5130. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5131. get: function () {
  5132. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5133. },
  5134. enumerable: true,
  5135. configurable: true
  5136. });
  5137. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5138. get: function () {
  5139. return this._alphaBlend;
  5140. },
  5141. set: function (value) {
  5142. if (this._alphaBlend === value) {
  5143. return;
  5144. }
  5145. this._alphaBlend = value;
  5146. this._isAlphaBlendDirty = true;
  5147. },
  5148. enumerable: true,
  5149. configurable: true
  5150. });
  5151. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5152. if (this._blendFunctionParameters[0] === value0 &&
  5153. this._blendFunctionParameters[1] === value1 &&
  5154. this._blendFunctionParameters[2] === value2 &&
  5155. this._blendFunctionParameters[3] === value3) {
  5156. return;
  5157. }
  5158. this._blendFunctionParameters[0] = value0;
  5159. this._blendFunctionParameters[1] = value1;
  5160. this._blendFunctionParameters[2] = value2;
  5161. this._blendFunctionParameters[3] = value3;
  5162. this._isBlendFunctionParametersDirty = true;
  5163. };
  5164. _AlphaState.prototype.reset = function () {
  5165. this._alphaBlend = false;
  5166. this._blendFunctionParameters[0] = null;
  5167. this._blendFunctionParameters[1] = null;
  5168. this._blendFunctionParameters[2] = null;
  5169. this._blendFunctionParameters[3] = null;
  5170. this._isAlphaBlendDirty = true;
  5171. this._isBlendFunctionParametersDirty = false;
  5172. };
  5173. _AlphaState.prototype.apply = function (gl) {
  5174. if (!this.isDirty) {
  5175. return;
  5176. }
  5177. // Alpha blend
  5178. if (this._isAlphaBlendDirty) {
  5179. if (this._alphaBlend) {
  5180. gl.enable(gl.BLEND);
  5181. }
  5182. else {
  5183. gl.disable(gl.BLEND);
  5184. }
  5185. this._isAlphaBlendDirty = false;
  5186. }
  5187. // Alpha function
  5188. if (this._isBlendFunctionParametersDirty) {
  5189. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5190. this._isBlendFunctionParametersDirty = false;
  5191. }
  5192. };
  5193. return _AlphaState;
  5194. })();
  5195. BABYLON._AlphaState = _AlphaState;
  5196. var compileShader = function (gl, source, type, defines) {
  5197. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5198. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5199. gl.compileShader(shader);
  5200. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5201. throw new Error(gl.getShaderInfoLog(shader));
  5202. }
  5203. return shader;
  5204. };
  5205. var getWebGLTextureType = function (gl, type) {
  5206. var textureType = gl.UNSIGNED_BYTE;
  5207. if (type === Engine.TEXTURETYPE_FLOAT)
  5208. textureType = gl.FLOAT;
  5209. return textureType;
  5210. };
  5211. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5212. var magFilter = gl.NEAREST;
  5213. var minFilter = gl.NEAREST;
  5214. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5215. magFilter = gl.LINEAR;
  5216. if (generateMipMaps) {
  5217. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5218. }
  5219. else {
  5220. minFilter = gl.LINEAR;
  5221. }
  5222. }
  5223. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5224. magFilter = gl.LINEAR;
  5225. if (generateMipMaps) {
  5226. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5227. }
  5228. else {
  5229. minFilter = gl.LINEAR;
  5230. }
  5231. }
  5232. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5233. magFilter = gl.NEAREST;
  5234. if (generateMipMaps) {
  5235. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5236. }
  5237. else {
  5238. minFilter = gl.NEAREST;
  5239. }
  5240. }
  5241. return {
  5242. min: minFilter,
  5243. mag: magFilter
  5244. };
  5245. };
  5246. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5248. var engine = scene.getEngine();
  5249. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5250. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5251. gl.bindTexture(gl.TEXTURE_2D, texture);
  5252. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5253. texture._baseWidth = width;
  5254. texture._baseHeight = height;
  5255. texture._width = potWidth;
  5256. texture._height = potHeight;
  5257. texture.isReady = true;
  5258. processFunction(potWidth, potHeight);
  5259. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5262. if (!noMipmap && !isCompressed) {
  5263. gl.generateMipmap(gl.TEXTURE_2D);
  5264. }
  5265. gl.bindTexture(gl.TEXTURE_2D, null);
  5266. engine._activeTexturesCache = [];
  5267. scene._removePendingData(texture);
  5268. };
  5269. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5270. var onload = function () {
  5271. loadedImages[index] = img;
  5272. loadedImages._internalCount++;
  5273. scene._removePendingData(img);
  5274. if (loadedImages._internalCount === 6) {
  5275. onfinish(loadedImages);
  5276. }
  5277. };
  5278. var onerror = function () {
  5279. scene._removePendingData(img);
  5280. };
  5281. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5282. scene._addPendingData(img);
  5283. };
  5284. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5285. var loadedImages = [];
  5286. loadedImages._internalCount = 0;
  5287. for (var index = 0; index < 6; index++) {
  5288. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5289. }
  5290. };
  5291. var EngineCapabilities = (function () {
  5292. function EngineCapabilities() {
  5293. }
  5294. return EngineCapabilities;
  5295. })();
  5296. BABYLON.EngineCapabilities = EngineCapabilities;
  5297. /**
  5298. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5299. */
  5300. var Engine = (function () {
  5301. /**
  5302. * @constructor
  5303. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5304. * @param {boolean} [antialias] - enable antialias
  5305. * @param options - further options to be sent to the getContext function
  5306. */
  5307. function Engine(canvas, antialias, options) {
  5308. var _this = this;
  5309. // Public members
  5310. this.isFullscreen = false;
  5311. this.isPointerLock = false;
  5312. this.cullBackFaces = true;
  5313. this.renderEvenInBackground = true;
  5314. this.scenes = new Array();
  5315. this._windowIsBackground = false;
  5316. this._loadingDivBackgroundColor = "black";
  5317. this._drawCalls = 0;
  5318. this._renderingQueueLaunched = false;
  5319. this._activeRenderLoops = [];
  5320. // FPS
  5321. this.fpsRange = 60;
  5322. this.previousFramesDuration = [];
  5323. this.fps = 60;
  5324. this.deltaTime = 0;
  5325. // States
  5326. this._depthCullingState = new _DepthCullingState();
  5327. this._alphaState = new _AlphaState();
  5328. this._alphaMode = Engine.ALPHA_DISABLE;
  5329. // Cache
  5330. this._loadedTexturesCache = new Array();
  5331. this._activeTexturesCache = new Array();
  5332. this._compiledEffects = {};
  5333. this._uintIndicesCurrentlySet = false;
  5334. this._renderingCanvas = canvas;
  5335. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5336. options = options || {};
  5337. options.antialias = antialias;
  5338. // GL
  5339. try {
  5340. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5341. }
  5342. catch (e) {
  5343. throw new Error("WebGL not supported");
  5344. }
  5345. if (!this._gl) {
  5346. throw new Error("WebGL not supported");
  5347. }
  5348. this._onBlur = function () {
  5349. _this._windowIsBackground = true;
  5350. };
  5351. this._onFocus = function () {
  5352. _this._windowIsBackground = false;
  5353. };
  5354. window.addEventListener("blur", this._onBlur);
  5355. window.addEventListener("focus", this._onFocus);
  5356. // Viewport
  5357. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5358. this.resize();
  5359. // Caps
  5360. this._caps = new EngineCapabilities();
  5361. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5362. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5363. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5364. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5365. // Infos
  5366. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5367. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5368. if (rendererInfo != null) {
  5369. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5370. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5371. }
  5372. if (!this._glVendor) {
  5373. this._glVendor = "Unknown vendor";
  5374. }
  5375. if (!this._glRenderer) {
  5376. this._glRenderer = "Unknown renderer";
  5377. }
  5378. // Extensions
  5379. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5380. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5381. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5382. 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');
  5383. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5384. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5385. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5386. this._caps.highPrecisionShaderSupported = true;
  5387. if (this._gl.getShaderPrecisionFormat) {
  5388. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5389. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5390. }
  5391. // Depth buffer
  5392. this.setDepthBuffer(true);
  5393. this.setDepthFunctionToLessOrEqual();
  5394. this.setDepthWrite(true);
  5395. // Fullscreen
  5396. this._onFullscreenChange = function () {
  5397. if (document.fullscreen !== undefined) {
  5398. _this.isFullscreen = document.fullscreen;
  5399. }
  5400. else if (document.mozFullScreen !== undefined) {
  5401. _this.isFullscreen = document.mozFullScreen;
  5402. }
  5403. else if (document.webkitIsFullScreen !== undefined) {
  5404. _this.isFullscreen = document.webkitIsFullScreen;
  5405. }
  5406. else if (document.msIsFullScreen !== undefined) {
  5407. _this.isFullscreen = document.msIsFullScreen;
  5408. }
  5409. // Pointer lock
  5410. if (_this.isFullscreen && _this._pointerLockRequested) {
  5411. canvas.requestPointerLock = canvas.requestPointerLock ||
  5412. canvas.msRequestPointerLock ||
  5413. canvas.mozRequestPointerLock ||
  5414. canvas.webkitRequestPointerLock;
  5415. if (canvas.requestPointerLock) {
  5416. canvas.requestPointerLock();
  5417. }
  5418. }
  5419. };
  5420. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5421. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5422. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5423. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5424. // Pointer lock
  5425. this._onPointerLockChange = function () {
  5426. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5427. document.webkitPointerLockElement === canvas ||
  5428. document.msPointerLockElement === canvas ||
  5429. document.pointerLockElement === canvas);
  5430. };
  5431. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5432. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5433. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5434. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5435. if (!Engine.audioEngine) {
  5436. Engine.audioEngine = new BABYLON.AudioEngine();
  5437. }
  5438. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5439. }
  5440. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5441. get: function () {
  5442. return Engine._ALPHA_DISABLE;
  5443. },
  5444. enumerable: true,
  5445. configurable: true
  5446. });
  5447. Object.defineProperty(Engine, "ALPHA_ADD", {
  5448. get: function () {
  5449. return Engine._ALPHA_ADD;
  5450. },
  5451. enumerable: true,
  5452. configurable: true
  5453. });
  5454. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5455. get: function () {
  5456. return Engine._ALPHA_COMBINE;
  5457. },
  5458. enumerable: true,
  5459. configurable: true
  5460. });
  5461. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5462. get: function () {
  5463. return Engine._DELAYLOADSTATE_NONE;
  5464. },
  5465. enumerable: true,
  5466. configurable: true
  5467. });
  5468. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5469. get: function () {
  5470. return Engine._DELAYLOADSTATE_LOADED;
  5471. },
  5472. enumerable: true,
  5473. configurable: true
  5474. });
  5475. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5476. get: function () {
  5477. return Engine._DELAYLOADSTATE_LOADING;
  5478. },
  5479. enumerable: true,
  5480. configurable: true
  5481. });
  5482. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5483. get: function () {
  5484. return Engine._DELAYLOADSTATE_NOTLOADED;
  5485. },
  5486. enumerable: true,
  5487. configurable: true
  5488. });
  5489. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5490. get: function () {
  5491. return Engine._TEXTUREFORMAT_ALPHA;
  5492. },
  5493. enumerable: true,
  5494. configurable: true
  5495. });
  5496. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5497. get: function () {
  5498. return Engine._TEXTUREFORMAT_LUMINANCE;
  5499. },
  5500. enumerable: true,
  5501. configurable: true
  5502. });
  5503. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5504. get: function () {
  5505. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5506. },
  5507. enumerable: true,
  5508. configurable: true
  5509. });
  5510. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5511. get: function () {
  5512. return Engine._TEXTUREFORMAT_RGB;
  5513. },
  5514. enumerable: true,
  5515. configurable: true
  5516. });
  5517. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5518. get: function () {
  5519. return Engine._TEXTUREFORMAT_RGBA;
  5520. },
  5521. enumerable: true,
  5522. configurable: true
  5523. });
  5524. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5525. get: function () {
  5526. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5527. },
  5528. enumerable: true,
  5529. configurable: true
  5530. });
  5531. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5532. get: function () {
  5533. return Engine._TEXTURETYPE_FLOAT;
  5534. },
  5535. enumerable: true,
  5536. configurable: true
  5537. });
  5538. Object.defineProperty(Engine, "Version", {
  5539. get: function () {
  5540. return "2.1.0";
  5541. },
  5542. enumerable: true,
  5543. configurable: true
  5544. });
  5545. Engine.prototype._prepareWorkingCanvas = function () {
  5546. if (this._workingCanvas) {
  5547. return;
  5548. }
  5549. this._workingCanvas = document.createElement("canvas");
  5550. this._workingContext = this._workingCanvas.getContext("2d");
  5551. };
  5552. Engine.prototype.getGlInfo = function () {
  5553. return {
  5554. vendor: this._glVendor,
  5555. renderer: this._glRenderer,
  5556. version: this._glVersion
  5557. };
  5558. };
  5559. Engine.prototype.getAspectRatio = function (camera) {
  5560. var viewport = camera.viewport;
  5561. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5562. };
  5563. Engine.prototype.getRenderWidth = function () {
  5564. if (this._currentRenderTarget) {
  5565. return this._currentRenderTarget._width;
  5566. }
  5567. return this._renderingCanvas.width;
  5568. };
  5569. Engine.prototype.getRenderHeight = function () {
  5570. if (this._currentRenderTarget) {
  5571. return this._currentRenderTarget._height;
  5572. }
  5573. return this._renderingCanvas.height;
  5574. };
  5575. Engine.prototype.getRenderingCanvas = function () {
  5576. return this._renderingCanvas;
  5577. };
  5578. Engine.prototype.getRenderingCanvasClientRect = function () {
  5579. return this._renderingCanvas.getBoundingClientRect();
  5580. };
  5581. Engine.prototype.setHardwareScalingLevel = function (level) {
  5582. this._hardwareScalingLevel = level;
  5583. this.resize();
  5584. };
  5585. Engine.prototype.getHardwareScalingLevel = function () {
  5586. return this._hardwareScalingLevel;
  5587. };
  5588. Engine.prototype.getLoadedTexturesCache = function () {
  5589. return this._loadedTexturesCache;
  5590. };
  5591. Engine.prototype.getCaps = function () {
  5592. return this._caps;
  5593. };
  5594. Object.defineProperty(Engine.prototype, "drawCalls", {
  5595. get: function () {
  5596. return this._drawCalls;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. // Methods
  5602. Engine.prototype.resetDrawCalls = function () {
  5603. this._drawCalls = 0;
  5604. };
  5605. Engine.prototype.setDepthFunctionToGreater = function () {
  5606. this._depthCullingState.depthFunc = this._gl.GREATER;
  5607. };
  5608. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5609. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5610. };
  5611. Engine.prototype.setDepthFunctionToLess = function () {
  5612. this._depthCullingState.depthFunc = this._gl.LESS;
  5613. };
  5614. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5615. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5616. };
  5617. /**
  5618. * stop executing a render loop function and remove it from the execution array
  5619. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5620. */
  5621. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5622. if (!renderFunction) {
  5623. this._activeRenderLoops = [];
  5624. return;
  5625. }
  5626. var index = this._activeRenderLoops.indexOf(renderFunction);
  5627. if (index >= 0) {
  5628. this._activeRenderLoops.splice(index, 1);
  5629. }
  5630. };
  5631. Engine.prototype._renderLoop = function () {
  5632. var _this = this;
  5633. var shouldRender = true;
  5634. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5635. shouldRender = false;
  5636. }
  5637. if (shouldRender) {
  5638. // Start new frame
  5639. this.beginFrame();
  5640. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5641. var renderFunction = this._activeRenderLoops[index];
  5642. renderFunction();
  5643. }
  5644. // Present
  5645. this.endFrame();
  5646. }
  5647. if (this._activeRenderLoops.length > 0) {
  5648. // Register new frame
  5649. BABYLON.Tools.QueueNewFrame(function () {
  5650. _this._renderLoop();
  5651. });
  5652. }
  5653. else {
  5654. this._renderingQueueLaunched = false;
  5655. }
  5656. };
  5657. /**
  5658. * Register and execute a render loop. The engine can have more than one render function.
  5659. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5660. * @example
  5661. * engine.runRenderLoop(function () {
  5662. * scene.render()
  5663. * })
  5664. */
  5665. Engine.prototype.runRenderLoop = function (renderFunction) {
  5666. var _this = this;
  5667. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5668. return;
  5669. }
  5670. this._activeRenderLoops.push(renderFunction);
  5671. if (!this._renderingQueueLaunched) {
  5672. this._renderingQueueLaunched = true;
  5673. BABYLON.Tools.QueueNewFrame(function () {
  5674. _this._renderLoop();
  5675. });
  5676. }
  5677. };
  5678. /**
  5679. * Toggle full screen mode.
  5680. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5681. */
  5682. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5683. if (this.isFullscreen) {
  5684. BABYLON.Tools.ExitFullscreen();
  5685. }
  5686. else {
  5687. this._pointerLockRequested = requestPointerLock;
  5688. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5689. }
  5690. };
  5691. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5692. this.applyStates();
  5693. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5694. if (this._depthCullingState.depthMask) {
  5695. this._gl.clearDepth(1.0);
  5696. }
  5697. var mode = 0;
  5698. if (backBuffer)
  5699. mode |= this._gl.COLOR_BUFFER_BIT;
  5700. if (depthStencil && this._depthCullingState.depthMask)
  5701. mode |= this._gl.DEPTH_BUFFER_BIT;
  5702. this._gl.clear(mode);
  5703. };
  5704. /**
  5705. * Set the WebGL's viewport
  5706. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5707. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5708. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5709. */
  5710. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5711. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5712. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5713. var x = viewport.x || 0;
  5714. var y = viewport.y || 0;
  5715. this._cachedViewport = viewport;
  5716. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5717. };
  5718. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5719. this._cachedViewport = null;
  5720. this._gl.viewport(x, y, width, height);
  5721. };
  5722. Engine.prototype.beginFrame = function () {
  5723. this._measureFps();
  5724. };
  5725. Engine.prototype.endFrame = function () {
  5726. //this.flushFramebuffer();
  5727. };
  5728. /**
  5729. * resize the view according to the canvas' size.
  5730. * @example
  5731. * window.addEventListener("resize", function () {
  5732. * engine.resize();
  5733. * });
  5734. */
  5735. Engine.prototype.resize = function () {
  5736. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5737. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5738. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5739. };
  5740. /**
  5741. * force a specific size of the canvas
  5742. * @param {number} width - the new canvas' width
  5743. * @param {number} height - the new canvas' height
  5744. */
  5745. Engine.prototype.setSize = function (width, height) {
  5746. this._renderingCanvas.width = width;
  5747. this._renderingCanvas.height = height;
  5748. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5749. for (var index = 0; index < this.scenes.length; index++) {
  5750. var scene = this.scenes[index];
  5751. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5752. var cam = scene.cameras[camIndex];
  5753. cam._currentRenderId = 0;
  5754. }
  5755. }
  5756. };
  5757. Engine.prototype.bindFramebuffer = function (texture) {
  5758. this._currentRenderTarget = texture;
  5759. var gl = this._gl;
  5760. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5761. this._gl.viewport(0, 0, texture._width, texture._height);
  5762. this.wipeCaches();
  5763. };
  5764. Engine.prototype.unBindFramebuffer = function (texture) {
  5765. this._currentRenderTarget = null;
  5766. if (texture.generateMipMaps) {
  5767. var gl = this._gl;
  5768. gl.bindTexture(gl.TEXTURE_2D, texture);
  5769. gl.generateMipmap(gl.TEXTURE_2D);
  5770. gl.bindTexture(gl.TEXTURE_2D, null);
  5771. }
  5772. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5773. };
  5774. Engine.prototype.flushFramebuffer = function () {
  5775. this._gl.flush();
  5776. };
  5777. Engine.prototype.restoreDefaultFramebuffer = function () {
  5778. this._currentRenderTarget = null;
  5779. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5780. this.setViewport(this._cachedViewport);
  5781. this.wipeCaches();
  5782. };
  5783. // VBOs
  5784. Engine.prototype._resetVertexBufferBinding = function () {
  5785. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5786. this._cachedVertexBuffers = null;
  5787. };
  5788. Engine.prototype.createVertexBuffer = function (vertices) {
  5789. var vbo = this._gl.createBuffer();
  5790. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5791. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5792. this._resetVertexBufferBinding();
  5793. vbo.references = 1;
  5794. return vbo;
  5795. };
  5796. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5797. var vbo = this._gl.createBuffer();
  5798. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5799. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5800. this._resetVertexBufferBinding();
  5801. vbo.references = 1;
  5802. return vbo;
  5803. };
  5804. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5805. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5806. if (offset === undefined) {
  5807. offset = 0;
  5808. }
  5809. if (vertices instanceof Float32Array) {
  5810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5811. }
  5812. else {
  5813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5814. }
  5815. this._resetVertexBufferBinding();
  5816. };
  5817. Engine.prototype._resetIndexBufferBinding = function () {
  5818. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5819. this._cachedIndexBuffer = null;
  5820. };
  5821. Engine.prototype.createIndexBuffer = function (indices) {
  5822. var vbo = this._gl.createBuffer();
  5823. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5824. // Check for 32 bits indices
  5825. var arrayBuffer;
  5826. var need32Bits = false;
  5827. if (this._caps.uintIndices) {
  5828. for (var index = 0; index < indices.length; index++) {
  5829. if (indices[index] > 65535) {
  5830. need32Bits = true;
  5831. break;
  5832. }
  5833. }
  5834. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5835. }
  5836. else {
  5837. arrayBuffer = new Uint16Array(indices);
  5838. }
  5839. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5840. this._resetIndexBufferBinding();
  5841. vbo.references = 1;
  5842. vbo.is32Bits = need32Bits;
  5843. return vbo;
  5844. };
  5845. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5846. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5847. this._cachedVertexBuffers = vertexBuffer;
  5848. this._cachedEffectForVertexBuffers = effect;
  5849. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5850. var offset = 0;
  5851. for (var index = 0; index < vertexDeclaration.length; index++) {
  5852. var order = effect.getAttributeLocation(index);
  5853. if (order >= 0) {
  5854. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5855. }
  5856. offset += vertexDeclaration[index] * 4;
  5857. }
  5858. }
  5859. if (this._cachedIndexBuffer !== indexBuffer) {
  5860. this._cachedIndexBuffer = indexBuffer;
  5861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5862. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5863. }
  5864. };
  5865. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5866. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5867. this._cachedVertexBuffers = vertexBuffers;
  5868. this._cachedEffectForVertexBuffers = effect;
  5869. var attributes = effect.getAttributesNames();
  5870. for (var index = 0; index < attributes.length; index++) {
  5871. var order = effect.getAttributeLocation(index);
  5872. if (order >= 0) {
  5873. var vertexBuffer = vertexBuffers[attributes[index]];
  5874. if (!vertexBuffer) {
  5875. continue;
  5876. }
  5877. var stride = vertexBuffer.getStrideSize();
  5878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5879. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5880. }
  5881. }
  5882. }
  5883. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5884. this._cachedIndexBuffer = indexBuffer;
  5885. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5886. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5887. }
  5888. };
  5889. Engine.prototype._releaseBuffer = function (buffer) {
  5890. buffer.references--;
  5891. if (buffer.references === 0) {
  5892. this._gl.deleteBuffer(buffer);
  5893. return true;
  5894. }
  5895. return false;
  5896. };
  5897. Engine.prototype.createInstancesBuffer = function (capacity) {
  5898. var buffer = this._gl.createBuffer();
  5899. buffer.capacity = capacity;
  5900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5902. return buffer;
  5903. };
  5904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5905. this._gl.deleteBuffer(buffer);
  5906. };
  5907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5910. for (var index = 0; index < 4; index++) {
  5911. var offsetLocation = offsetLocations[index];
  5912. this._gl.enableVertexAttribArray(offsetLocation);
  5913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5915. }
  5916. };
  5917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5919. for (var index = 0; index < 4; index++) {
  5920. var offsetLocation = offsetLocations[index];
  5921. this._gl.disableVertexAttribArray(offsetLocation);
  5922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5923. }
  5924. };
  5925. Engine.prototype.applyStates = function () {
  5926. this._depthCullingState.apply(this._gl);
  5927. this._alphaState.apply(this._gl);
  5928. };
  5929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5930. // Apply states
  5931. this.applyStates();
  5932. this._drawCalls++;
  5933. // Render
  5934. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5935. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5936. if (instancesCount) {
  5937. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5938. return;
  5939. }
  5940. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5941. };
  5942. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5943. // Apply states
  5944. this.applyStates();
  5945. this._drawCalls++;
  5946. if (instancesCount) {
  5947. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5948. return;
  5949. }
  5950. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5951. };
  5952. // Shaders
  5953. Engine.prototype._releaseEffect = function (effect) {
  5954. if (this._compiledEffects[effect._key]) {
  5955. delete this._compiledEffects[effect._key];
  5956. if (effect.getProgram()) {
  5957. this._gl.deleteProgram(effect.getProgram());
  5958. }
  5959. }
  5960. };
  5961. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5962. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5963. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5964. var name = vertex + "+" + fragment + "@" + defines;
  5965. if (this._compiledEffects[name]) {
  5966. return this._compiledEffects[name];
  5967. }
  5968. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5969. effect._key = name;
  5970. this._compiledEffects[name] = effect;
  5971. return effect;
  5972. };
  5973. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5974. if (uniformsNames === void 0) { uniformsNames = []; }
  5975. if (samplers === void 0) { samplers = []; }
  5976. if (defines === void 0) { defines = ""; }
  5977. return this.createEffect({
  5978. vertex: "particles",
  5979. fragmentElement: fragmentName
  5980. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5981. };
  5982. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5983. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5984. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5985. var shaderProgram = this._gl.createProgram();
  5986. this._gl.attachShader(shaderProgram, vertexShader);
  5987. this._gl.attachShader(shaderProgram, fragmentShader);
  5988. this._gl.linkProgram(shaderProgram);
  5989. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5990. if (!linked) {
  5991. var error = this._gl.getProgramInfoLog(shaderProgram);
  5992. if (error) {
  5993. throw new Error(error);
  5994. }
  5995. }
  5996. this._gl.deleteShader(vertexShader);
  5997. this._gl.deleteShader(fragmentShader);
  5998. return shaderProgram;
  5999. };
  6000. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6001. var results = [];
  6002. for (var index = 0; index < uniformsNames.length; index++) {
  6003. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6004. }
  6005. return results;
  6006. };
  6007. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6008. var results = [];
  6009. for (var index = 0; index < attributesNames.length; index++) {
  6010. try {
  6011. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6012. }
  6013. catch (e) {
  6014. results.push(-1);
  6015. }
  6016. }
  6017. return results;
  6018. };
  6019. Engine.prototype.enableEffect = function (effect) {
  6020. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6021. if (effect && effect.onBind) {
  6022. effect.onBind(effect);
  6023. }
  6024. return;
  6025. }
  6026. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6027. // Use program
  6028. this._gl.useProgram(effect.getProgram());
  6029. for (var i in this._vertexAttribArrays) {
  6030. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6031. continue;
  6032. }
  6033. this._vertexAttribArrays[i] = false;
  6034. this._gl.disableVertexAttribArray(i);
  6035. }
  6036. var attributesCount = effect.getAttributesCount();
  6037. for (var index = 0; index < attributesCount; index++) {
  6038. // Attributes
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._vertexAttribArrays[order] = true;
  6042. this._gl.enableVertexAttribArray(order);
  6043. }
  6044. }
  6045. this._currentEffect = effect;
  6046. if (effect.onBind) {
  6047. effect.onBind(effect);
  6048. }
  6049. };
  6050. Engine.prototype.setArray = function (uniform, array) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray2 = function (uniform, array) {
  6056. if (!uniform || array.length % 2 !== 0)
  6057. return;
  6058. this._gl.uniform2fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray3 = function (uniform, array) {
  6061. if (!uniform || array.length % 3 !== 0)
  6062. return;
  6063. this._gl.uniform3fv(uniform, array);
  6064. };
  6065. Engine.prototype.setArray4 = function (uniform, array) {
  6066. if (!uniform || array.length % 4 !== 0)
  6067. return;
  6068. this._gl.uniform4fv(uniform, array);
  6069. };
  6070. Engine.prototype.setMatrices = function (uniform, matrices) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6074. };
  6075. Engine.prototype.setMatrix = function (uniform, matrix) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6079. };
  6080. Engine.prototype.setFloat = function (uniform, value) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniform1f(uniform, value);
  6084. };
  6085. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniform2f(uniform, x, y);
  6089. };
  6090. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform3f(uniform, x, y, z);
  6094. };
  6095. Engine.prototype.setBool = function (uniform, bool) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform1i(uniform, bool);
  6099. };
  6100. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform4f(uniform, x, y, z, w);
  6104. };
  6105. Engine.prototype.setColor3 = function (uniform, color3) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6109. };
  6110. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6114. };
  6115. // States
  6116. Engine.prototype.setState = function (culling, zOffset, force) {
  6117. if (zOffset === void 0) { zOffset = 0; }
  6118. // Culling
  6119. if (this._depthCullingState.cull !== culling || force) {
  6120. if (culling) {
  6121. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6122. this._depthCullingState.cull = true;
  6123. }
  6124. else {
  6125. this._depthCullingState.cull = false;
  6126. }
  6127. }
  6128. // Z offset
  6129. this._depthCullingState.zOffset = zOffset;
  6130. };
  6131. Engine.prototype.setDepthBuffer = function (enable) {
  6132. this._depthCullingState.depthTest = enable;
  6133. };
  6134. Engine.prototype.getDepthWrite = function () {
  6135. return this._depthCullingState.depthMask;
  6136. };
  6137. Engine.prototype.setDepthWrite = function (enable) {
  6138. this._depthCullingState.depthMask = enable;
  6139. };
  6140. Engine.prototype.setColorWrite = function (enable) {
  6141. this._gl.colorMask(enable, enable, enable, enable);
  6142. };
  6143. Engine.prototype.setAlphaMode = function (mode) {
  6144. switch (mode) {
  6145. case Engine.ALPHA_DISABLE:
  6146. this.setDepthWrite(true);
  6147. this._alphaState.alphaBlend = false;
  6148. break;
  6149. case Engine.ALPHA_COMBINE:
  6150. this.setDepthWrite(false);
  6151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6152. this._alphaState.alphaBlend = true;
  6153. break;
  6154. case Engine.ALPHA_ADD:
  6155. this.setDepthWrite(false);
  6156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6157. this._alphaState.alphaBlend = true;
  6158. break;
  6159. }
  6160. this._alphaMode = mode;
  6161. };
  6162. Engine.prototype.getAlphaMode = function () {
  6163. return this._alphaMode;
  6164. };
  6165. Engine.prototype.setAlphaTesting = function (enable) {
  6166. this._alphaTest = enable;
  6167. };
  6168. Engine.prototype.getAlphaTesting = function () {
  6169. return this._alphaTest;
  6170. };
  6171. // Textures
  6172. Engine.prototype.wipeCaches = function () {
  6173. this._activeTexturesCache = [];
  6174. this._currentEffect = null;
  6175. this._depthCullingState.reset();
  6176. this._alphaState.reset();
  6177. this._cachedVertexBuffers = null;
  6178. this._cachedIndexBuffer = null;
  6179. this._cachedEffectForVertexBuffers = null;
  6180. };
  6181. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6182. var gl = this._gl;
  6183. gl.bindTexture(gl.TEXTURE_2D, texture);
  6184. var magFilter = gl.NEAREST;
  6185. var minFilter = gl.NEAREST;
  6186. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6187. magFilter = gl.LINEAR;
  6188. minFilter = gl.LINEAR;
  6189. }
  6190. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6191. magFilter = gl.LINEAR;
  6192. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6193. }
  6194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6196. gl.bindTexture(gl.TEXTURE_2D, null);
  6197. texture.samplingMode = samplingMode;
  6198. };
  6199. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6200. var _this = this;
  6201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6202. if (onLoad === void 0) { onLoad = null; }
  6203. if (onError === void 0) { onError = null; }
  6204. if (buffer === void 0) { buffer = null; }
  6205. var texture = this._gl.createTexture();
  6206. var extension;
  6207. var fromData = false;
  6208. if (url.substr(0, 5) === "data:") {
  6209. fromData = true;
  6210. }
  6211. if (!fromData)
  6212. extension = url.substr(url.length - 4, 4).toLowerCase();
  6213. else {
  6214. var oldUrl = url;
  6215. fromData = oldUrl.split(':');
  6216. url = oldUrl;
  6217. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6218. }
  6219. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6220. var isTGA = (extension === ".tga");
  6221. scene._addPendingData(texture);
  6222. texture.url = url;
  6223. texture.noMipmap = noMipmap;
  6224. texture.references = 1;
  6225. texture.samplingMode = samplingMode;
  6226. this._loadedTexturesCache.push(texture);
  6227. var onerror = function () {
  6228. scene._removePendingData(texture);
  6229. if (onError) {
  6230. onError();
  6231. }
  6232. };
  6233. if (isTGA) {
  6234. var callback = function (arrayBuffer) {
  6235. var data = new Uint8Array(arrayBuffer);
  6236. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6237. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6238. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6239. if (onLoad) {
  6240. onLoad();
  6241. }
  6242. }, samplingMode);
  6243. };
  6244. if (!(fromData instanceof Array))
  6245. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6246. callback(arrayBuffer);
  6247. }, onerror, scene.database, true);
  6248. else
  6249. callback(buffer);
  6250. }
  6251. else if (isDDS) {
  6252. callback = function (data) {
  6253. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6254. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6255. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6256. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6257. if (onLoad) {
  6258. onLoad();
  6259. }
  6260. }, samplingMode);
  6261. };
  6262. if (!(fromData instanceof Array))
  6263. BABYLON.Tools.LoadFile(url, function (data) {
  6264. callback(data);
  6265. }, onerror, scene.database, true);
  6266. else
  6267. callback(buffer);
  6268. }
  6269. else {
  6270. var onload = function (img) {
  6271. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6272. var isPot = (img.width === potWidth && img.height === potHeight);
  6273. if (!isPot) {
  6274. _this._prepareWorkingCanvas();
  6275. _this._workingCanvas.width = potWidth;
  6276. _this._workingCanvas.height = potHeight;
  6277. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6278. _this._workingContext.imageSmoothingEnabled = false;
  6279. _this._workingContext.mozImageSmoothingEnabled = false;
  6280. _this._workingContext.oImageSmoothingEnabled = false;
  6281. _this._workingContext.webkitImageSmoothingEnabled = false;
  6282. _this._workingContext.msImageSmoothingEnabled = false;
  6283. }
  6284. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6285. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6286. _this._workingContext.imageSmoothingEnabled = true;
  6287. _this._workingContext.mozImageSmoothingEnabled = true;
  6288. _this._workingContext.oImageSmoothingEnabled = true;
  6289. _this._workingContext.webkitImageSmoothingEnabled = true;
  6290. _this._workingContext.msImageSmoothingEnabled = true;
  6291. }
  6292. }
  6293. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6294. if (onLoad) {
  6295. onLoad();
  6296. }
  6297. }, samplingMode);
  6298. };
  6299. if (!(fromData instanceof Array))
  6300. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6301. else
  6302. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6303. }
  6304. return texture;
  6305. };
  6306. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6307. var texture = this._gl.createTexture();
  6308. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6309. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6310. // Format
  6311. var internalFormat = this._gl.RGBA;
  6312. switch (format) {
  6313. case Engine.TEXTUREFORMAT_ALPHA:
  6314. internalFormat = this._gl.ALPHA;
  6315. break;
  6316. case Engine.TEXTUREFORMAT_LUMINANCE:
  6317. internalFormat = this._gl.LUMINANCE;
  6318. break;
  6319. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6320. internalFormat = this._gl.LUMINANCE_ALPHA;
  6321. break;
  6322. case Engine.TEXTUREFORMAT_RGB:
  6323. internalFormat = this._gl.RGB;
  6324. break;
  6325. case Engine.TEXTUREFORMAT_RGBA:
  6326. internalFormat = this._gl.RGBA;
  6327. break;
  6328. }
  6329. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6330. if (generateMipMaps) {
  6331. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6332. }
  6333. // Filters
  6334. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6335. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6336. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6337. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6338. this._activeTexturesCache = [];
  6339. texture._baseWidth = width;
  6340. texture._baseHeight = height;
  6341. texture._width = width;
  6342. texture._height = height;
  6343. texture.isReady = true;
  6344. texture.references = 1;
  6345. texture.samplingMode = samplingMode;
  6346. this._loadedTexturesCache.push(texture);
  6347. return texture;
  6348. };
  6349. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6350. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6351. var texture = this._gl.createTexture();
  6352. texture._baseWidth = width;
  6353. texture._baseHeight = height;
  6354. if (forceExponantOfTwo) {
  6355. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6356. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6357. }
  6358. this._activeTexturesCache = [];
  6359. texture._width = width;
  6360. texture._height = height;
  6361. texture.isReady = false;
  6362. texture.generateMipMaps = generateMipMaps;
  6363. texture.references = 1;
  6364. texture.samplingMode = samplingMode;
  6365. this.updateTextureSamplingMode(samplingMode, texture);
  6366. this._loadedTexturesCache.push(texture);
  6367. return texture;
  6368. };
  6369. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6370. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6371. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6372. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6373. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6374. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6375. };
  6376. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6377. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6378. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6379. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6380. if (texture.generateMipMaps) {
  6381. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6382. }
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6384. this._activeTexturesCache = [];
  6385. texture.isReady = true;
  6386. };
  6387. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6388. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6389. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6390. // Testing video texture support
  6391. if (this._videoTextureSupported === undefined) {
  6392. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6393. if (this._gl.getError() !== 0) {
  6394. this._videoTextureSupported = false;
  6395. }
  6396. else {
  6397. this._videoTextureSupported = true;
  6398. }
  6399. }
  6400. // Copy video through the current working canvas if video texture is not supported
  6401. if (!this._videoTextureSupported) {
  6402. if (!texture._workingCanvas) {
  6403. texture._workingCanvas = document.createElement("canvas");
  6404. texture._workingContext = texture._workingCanvas.getContext("2d");
  6405. texture._workingCanvas.width = texture._width;
  6406. texture._workingCanvas.height = texture._height;
  6407. }
  6408. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6410. }
  6411. else {
  6412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6413. }
  6414. if (texture.generateMipMaps) {
  6415. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6416. }
  6417. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6418. this._activeTexturesCache = [];
  6419. texture.isReady = true;
  6420. };
  6421. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6422. // old version had a "generateMipMaps" arg instead of options.
  6423. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6424. // in the same way, generateDepthBuffer is defaulted to true
  6425. var generateMipMaps = false;
  6426. var generateDepthBuffer = true;
  6427. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6428. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6429. if (options !== undefined) {
  6430. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6431. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6432. type = options.type === undefined ? type : options.type;
  6433. if (options.samplingMode !== undefined) {
  6434. samplingMode = options.samplingMode;
  6435. }
  6436. if (type === Engine.TEXTURETYPE_FLOAT) {
  6437. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6438. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6439. }
  6440. }
  6441. var gl = this._gl;
  6442. var texture = gl.createTexture();
  6443. gl.bindTexture(gl.TEXTURE_2D, texture);
  6444. var width = size.width || size;
  6445. var height = size.height || size;
  6446. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6448. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6449. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6450. }
  6451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6455. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6456. var depthBuffer;
  6457. // Create the depth buffer
  6458. if (generateDepthBuffer) {
  6459. depthBuffer = gl.createRenderbuffer();
  6460. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6461. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6462. }
  6463. // Create the framebuffer
  6464. var framebuffer = gl.createFramebuffer();
  6465. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6466. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6467. if (generateDepthBuffer) {
  6468. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6469. }
  6470. // Unbind
  6471. gl.bindTexture(gl.TEXTURE_2D, null);
  6472. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6473. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6474. texture._framebuffer = framebuffer;
  6475. if (generateDepthBuffer) {
  6476. texture._depthBuffer = depthBuffer;
  6477. }
  6478. texture._width = width;
  6479. texture._height = height;
  6480. texture.isReady = true;
  6481. texture.generateMipMaps = generateMipMaps;
  6482. texture.references = 1;
  6483. texture.samplingMode = samplingMode;
  6484. this._activeTexturesCache = [];
  6485. this._loadedTexturesCache.push(texture);
  6486. return texture;
  6487. };
  6488. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6489. var _this = this;
  6490. var gl = this._gl;
  6491. var texture = gl.createTexture();
  6492. texture.isCube = true;
  6493. texture.url = rootUrl;
  6494. texture.references = 1;
  6495. this._loadedTexturesCache.push(texture);
  6496. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6497. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6498. if (isDDS) {
  6499. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6500. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6501. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6502. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6503. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6504. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6505. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6506. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6507. }
  6508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6512. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6513. _this._activeTexturesCache = [];
  6514. texture._width = info.width;
  6515. texture._height = info.height;
  6516. texture.isReady = true;
  6517. }, null, null, true);
  6518. }
  6519. else {
  6520. cascadeLoad(rootUrl, scene, function (imgs) {
  6521. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6522. var height = width;
  6523. _this._prepareWorkingCanvas();
  6524. _this._workingCanvas.width = width;
  6525. _this._workingCanvas.height = height;
  6526. var faces = [
  6527. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6528. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6529. ];
  6530. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6531. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6532. for (var index = 0; index < faces.length; index++) {
  6533. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6534. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6535. }
  6536. if (!noMipmap) {
  6537. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6538. }
  6539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6543. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6544. _this._activeTexturesCache = [];
  6545. texture._width = width;
  6546. texture._height = height;
  6547. texture.isReady = true;
  6548. }, extensions);
  6549. }
  6550. return texture;
  6551. };
  6552. Engine.prototype._releaseTexture = function (texture) {
  6553. var gl = this._gl;
  6554. if (texture._framebuffer) {
  6555. gl.deleteFramebuffer(texture._framebuffer);
  6556. }
  6557. if (texture._depthBuffer) {
  6558. gl.deleteRenderbuffer(texture._depthBuffer);
  6559. }
  6560. gl.deleteTexture(texture);
  6561. // Unbind channels
  6562. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6563. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6564. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6565. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6566. this._activeTexturesCache[channel] = null;
  6567. }
  6568. var index = this._loadedTexturesCache.indexOf(texture);
  6569. if (index !== -1) {
  6570. this._loadedTexturesCache.splice(index, 1);
  6571. }
  6572. };
  6573. Engine.prototype.bindSamplers = function (effect) {
  6574. this._gl.useProgram(effect.getProgram());
  6575. var samplers = effect.getSamplers();
  6576. for (var index = 0; index < samplers.length; index++) {
  6577. var uniform = effect.getUniform(samplers[index]);
  6578. this._gl.uniform1i(uniform, index);
  6579. }
  6580. this._currentEffect = null;
  6581. };
  6582. Engine.prototype._bindTexture = function (channel, texture) {
  6583. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6584. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6585. this._activeTexturesCache[channel] = null;
  6586. };
  6587. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6588. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6589. };
  6590. Engine.prototype.setTexture = function (channel, texture) {
  6591. if (channel < 0) {
  6592. return;
  6593. }
  6594. // Not ready?
  6595. if (!texture || !texture.isReady()) {
  6596. if (this._activeTexturesCache[channel] != null) {
  6597. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6598. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6599. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6600. this._activeTexturesCache[channel] = null;
  6601. }
  6602. return;
  6603. }
  6604. // Video
  6605. if (texture instanceof BABYLON.VideoTexture) {
  6606. if (texture.update()) {
  6607. this._activeTexturesCache[channel] = null;
  6608. }
  6609. }
  6610. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6611. texture.delayLoad();
  6612. return;
  6613. }
  6614. if (this._activeTexturesCache[channel] === texture) {
  6615. return;
  6616. }
  6617. this._activeTexturesCache[channel] = texture;
  6618. var internalTexture = texture.getInternalTexture();
  6619. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6620. if (internalTexture.isCube) {
  6621. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6622. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6623. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6624. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6625. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6626. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6627. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6628. }
  6629. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6630. }
  6631. else {
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6633. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6634. internalTexture._cachedWrapU = texture.wrapU;
  6635. switch (texture.wrapU) {
  6636. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6638. break;
  6639. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6641. break;
  6642. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6644. break;
  6645. }
  6646. }
  6647. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6648. internalTexture._cachedWrapV = texture.wrapV;
  6649. switch (texture.wrapV) {
  6650. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6651. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6652. break;
  6653. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6654. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6655. break;
  6656. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6658. break;
  6659. }
  6660. }
  6661. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6662. }
  6663. };
  6664. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6665. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6666. var value = texture.anisotropicFilteringLevel;
  6667. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6668. value = 1;
  6669. }
  6670. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6671. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6672. texture._cachedAnisotropicFilteringLevel = value;
  6673. }
  6674. };
  6675. Engine.prototype.readPixels = function (x, y, width, height) {
  6676. var data = new Uint8Array(height * width * 4);
  6677. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6678. return data;
  6679. };
  6680. // Dispose
  6681. Engine.prototype.dispose = function () {
  6682. this.hideLoadingUI();
  6683. this.stopRenderLoop();
  6684. // Release scenes
  6685. while (this.scenes.length) {
  6686. this.scenes[0].dispose();
  6687. }
  6688. // Release audio engine
  6689. Engine.audioEngine.dispose();
  6690. // Release effects
  6691. for (var name in this._compiledEffects) {
  6692. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6693. }
  6694. // Unbind
  6695. for (var i in this._vertexAttribArrays) {
  6696. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6697. continue;
  6698. }
  6699. this._gl.disableVertexAttribArray(i);
  6700. }
  6701. // Events
  6702. window.removeEventListener("blur", this._onBlur);
  6703. window.removeEventListener("focus", this._onFocus);
  6704. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6705. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6706. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6707. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6708. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6709. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6710. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6711. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6712. };
  6713. // Loading screen
  6714. Engine.prototype.displayLoadingUI = function () {
  6715. var _this = this;
  6716. this._loadingDiv = document.createElement("div");
  6717. this._loadingDiv.style.opacity = "0";
  6718. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6719. // Loading text
  6720. this._loadingTextDiv = document.createElement("div");
  6721. this._loadingTextDiv.style.position = "absolute";
  6722. this._loadingTextDiv.style.left = "0";
  6723. this._loadingTextDiv.style.top = "50%";
  6724. this._loadingTextDiv.style.marginTop = "80px";
  6725. this._loadingTextDiv.style.width = "100%";
  6726. this._loadingTextDiv.style.height = "20px";
  6727. this._loadingTextDiv.style.fontFamily = "Arial";
  6728. this._loadingTextDiv.style.fontSize = "14px";
  6729. this._loadingTextDiv.style.color = "white";
  6730. this._loadingTextDiv.style.textAlign = "center";
  6731. this._loadingTextDiv.innerHTML = "Loading";
  6732. this._loadingDiv.appendChild(this._loadingTextDiv);
  6733. // Loading img
  6734. var imgBack = new Image();
  6735. 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==";
  6736. imgBack.style.position = "absolute";
  6737. imgBack.style.left = "50%";
  6738. imgBack.style.top = "50%";
  6739. imgBack.style.marginLeft = "-50px";
  6740. imgBack.style.marginTop = "-50px";
  6741. imgBack.style.transition = "transform 1.0s ease";
  6742. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6743. var deg = 360;
  6744. var onTransitionEnd = function () {
  6745. deg += 360;
  6746. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6747. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6748. };
  6749. imgBack.addEventListener("transitionend", onTransitionEnd);
  6750. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6751. this._loadingDiv.appendChild(imgBack);
  6752. // front image
  6753. var imgFront = new Image();
  6754. 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=";
  6755. imgFront.style.position = "absolute";
  6756. imgFront.style.left = "50%";
  6757. imgFront.style.top = "50%";
  6758. imgFront.style.marginLeft = "-50px";
  6759. imgFront.style.marginTop = "-50px";
  6760. this._loadingDiv.appendChild(imgFront);
  6761. // Resize
  6762. this._resizeLoadingUI = function () {
  6763. var canvasRect = _this.getRenderingCanvasClientRect();
  6764. _this._loadingDiv.style.position = "absolute";
  6765. _this._loadingDiv.style.left = canvasRect.left + "px";
  6766. _this._loadingDiv.style.top = canvasRect.top + "px";
  6767. _this._loadingDiv.style.width = canvasRect.width + "px";
  6768. _this._loadingDiv.style.height = canvasRect.height + "px";
  6769. };
  6770. this._resizeLoadingUI();
  6771. window.addEventListener("resize", this._resizeLoadingUI);
  6772. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6773. document.body.appendChild(this._loadingDiv);
  6774. setTimeout(function () {
  6775. _this._loadingDiv.style.opacity = "1";
  6776. imgBack.style.transform = "rotateZ(360deg)";
  6777. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6778. }, 0);
  6779. };
  6780. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6781. set: function (text) {
  6782. if (!this._loadingDiv) {
  6783. return;
  6784. }
  6785. this._loadingTextDiv.innerHTML = text;
  6786. },
  6787. enumerable: true,
  6788. configurable: true
  6789. });
  6790. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6791. get: function () {
  6792. return this._loadingDivBackgroundColor;
  6793. },
  6794. set: function (color) {
  6795. this._loadingDivBackgroundColor = color;
  6796. if (!this._loadingDiv) {
  6797. return;
  6798. }
  6799. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6800. },
  6801. enumerable: true,
  6802. configurable: true
  6803. });
  6804. Engine.prototype.hideLoadingUI = function () {
  6805. var _this = this;
  6806. if (!this._loadingDiv) {
  6807. return;
  6808. }
  6809. var onTransitionEnd = function () {
  6810. if (!_this._loadingDiv) {
  6811. return;
  6812. }
  6813. document.body.removeChild(_this._loadingDiv);
  6814. window.removeEventListener("resize", _this._resizeLoadingUI);
  6815. _this._loadingDiv = null;
  6816. };
  6817. this._loadingDiv.style.opacity = "0";
  6818. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6819. };
  6820. // FPS
  6821. Engine.prototype.getFps = function () {
  6822. return this.fps;
  6823. };
  6824. Engine.prototype.getDeltaTime = function () {
  6825. return this.deltaTime;
  6826. };
  6827. Engine.prototype._measureFps = function () {
  6828. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6829. var length = this.previousFramesDuration.length;
  6830. if (length >= 2) {
  6831. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6832. }
  6833. if (length >= this.fpsRange) {
  6834. if (length > this.fpsRange) {
  6835. this.previousFramesDuration.splice(0, 1);
  6836. length = this.previousFramesDuration.length;
  6837. }
  6838. var sum = 0;
  6839. for (var id = 0; id < length - 1; id++) {
  6840. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6841. }
  6842. this.fps = 1000.0 / (sum / (length - 1));
  6843. }
  6844. };
  6845. // Statics
  6846. Engine.isSupported = function () {
  6847. try {
  6848. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6849. if (navigator.isCocoonJS) {
  6850. return true;
  6851. }
  6852. var tempcanvas = document.createElement("canvas");
  6853. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6854. return gl != null && !!window.WebGLRenderingContext;
  6855. }
  6856. catch (e) {
  6857. return false;
  6858. }
  6859. };
  6860. // Const statics
  6861. Engine._ALPHA_DISABLE = 0;
  6862. Engine._ALPHA_ADD = 1;
  6863. Engine._ALPHA_COMBINE = 2;
  6864. Engine._DELAYLOADSTATE_NONE = 0;
  6865. Engine._DELAYLOADSTATE_LOADED = 1;
  6866. Engine._DELAYLOADSTATE_LOADING = 2;
  6867. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6868. Engine._TEXTUREFORMAT_ALPHA = 0;
  6869. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6870. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6871. Engine._TEXTUREFORMAT_RGB = 4;
  6872. Engine._TEXTUREFORMAT_RGBA = 4;
  6873. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6874. Engine._TEXTURETYPE_FLOAT = 1;
  6875. // Updatable statics so stick with vars here
  6876. Engine.Epsilon = 0.001;
  6877. Engine.CollisionsEpsilon = 0.001;
  6878. Engine.CodeRepository = "Babylon/";
  6879. Engine.ShadersRepository = "Babylon/Shaders/";
  6880. return Engine;
  6881. })();
  6882. BABYLON.Engine = Engine;
  6883. })(BABYLON || (BABYLON = {}));
  6884. //# sourceMappingURL=babylon.engine.js.map
  6885. var BABYLON;
  6886. (function (BABYLON) {
  6887. /**
  6888. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6889. */
  6890. var Node = (function () {
  6891. /**
  6892. * @constructor
  6893. * @param {string} name - the name and id to be given to this node
  6894. * @param {BABYLON.Scene} the scene this node will be added to
  6895. */
  6896. function Node(name, scene) {
  6897. this.state = "";
  6898. this.animations = new Array();
  6899. this._childrenFlag = -1;
  6900. this._isEnabled = true;
  6901. this._isReady = true;
  6902. this._currentRenderId = -1;
  6903. this._parentRenderId = -1;
  6904. this.name = name;
  6905. this.id = name;
  6906. this._scene = scene;
  6907. this._initCache();
  6908. }
  6909. Node.prototype.getScene = function () {
  6910. return this._scene;
  6911. };
  6912. Node.prototype.getEngine = function () {
  6913. return this._scene.getEngine();
  6914. };
  6915. // override it in derived class
  6916. Node.prototype.getWorldMatrix = function () {
  6917. return BABYLON.Matrix.Identity();
  6918. };
  6919. // override it in derived class if you add new variables to the cache
  6920. // and call the parent class method
  6921. Node.prototype._initCache = function () {
  6922. this._cache = {};
  6923. this._cache.parent = undefined;
  6924. };
  6925. Node.prototype.updateCache = function (force) {
  6926. if (!force && this.isSynchronized())
  6927. return;
  6928. this._cache.parent = this.parent;
  6929. this._updateCache();
  6930. };
  6931. // override it in derived class if you add new variables to the cache
  6932. // and call the parent class method if !ignoreParentClass
  6933. Node.prototype._updateCache = function (ignoreParentClass) {
  6934. };
  6935. // override it in derived class if you add new variables to the cache
  6936. Node.prototype._isSynchronized = function () {
  6937. return true;
  6938. };
  6939. Node.prototype._markSyncedWithParent = function () {
  6940. this._parentRenderId = this.parent._currentRenderId;
  6941. };
  6942. Node.prototype.isSynchronizedWithParent = function () {
  6943. if (!this.parent) {
  6944. return true;
  6945. }
  6946. if (this._parentRenderId !== this.parent._currentRenderId) {
  6947. return false;
  6948. }
  6949. return this.parent.isSynchronized();
  6950. };
  6951. Node.prototype.isSynchronized = function (updateCache) {
  6952. var check = this.hasNewParent();
  6953. check = check || !this.isSynchronizedWithParent();
  6954. check = check || !this._isSynchronized();
  6955. if (updateCache)
  6956. this.updateCache(true);
  6957. return !check;
  6958. };
  6959. Node.prototype.hasNewParent = function (update) {
  6960. if (this._cache.parent === this.parent)
  6961. return false;
  6962. if (update)
  6963. this._cache.parent = this.parent;
  6964. return true;
  6965. };
  6966. /**
  6967. * Is this node ready to be used/rendered
  6968. * @return {boolean} is it ready
  6969. */
  6970. Node.prototype.isReady = function () {
  6971. return this._isReady;
  6972. };
  6973. /**
  6974. * Is this node enabled.
  6975. * If the node has a parent and is enabled, the parent will be inspected as well.
  6976. * @return {boolean} whether this node (and its parent) is enabled.
  6977. * @see setEnabled
  6978. */
  6979. Node.prototype.isEnabled = function () {
  6980. if (!this._isEnabled) {
  6981. return false;
  6982. }
  6983. if (this.parent) {
  6984. return this.parent.isEnabled();
  6985. }
  6986. return true;
  6987. };
  6988. /**
  6989. * Set the enabled state of this node.
  6990. * @param {boolean} value - the new enabled state
  6991. * @see isEnabled
  6992. */
  6993. Node.prototype.setEnabled = function (value) {
  6994. this._isEnabled = value;
  6995. };
  6996. /**
  6997. * Is this node a descendant of the given node.
  6998. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6999. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7000. * @see parent
  7001. */
  7002. Node.prototype.isDescendantOf = function (ancestor) {
  7003. if (this.parent) {
  7004. if (this.parent === ancestor) {
  7005. return true;
  7006. }
  7007. return this.parent.isDescendantOf(ancestor);
  7008. }
  7009. return false;
  7010. };
  7011. Node.prototype._getDescendants = function (list, results) {
  7012. for (var index = 0; index < list.length; index++) {
  7013. var item = list[index];
  7014. if (item.isDescendantOf(this)) {
  7015. results.push(item);
  7016. }
  7017. }
  7018. };
  7019. /**
  7020. * Will return all nodes that have this node as parent.
  7021. * @return {BABYLON.Node[]} all children nodes of all types.
  7022. */
  7023. Node.prototype.getDescendants = function () {
  7024. var results = [];
  7025. this._getDescendants(this._scene.meshes, results);
  7026. this._getDescendants(this._scene.lights, results);
  7027. this._getDescendants(this._scene.cameras, results);
  7028. return results;
  7029. };
  7030. Node.prototype._setReady = function (state) {
  7031. if (state == this._isReady) {
  7032. return;
  7033. }
  7034. if (!state) {
  7035. this._isReady = false;
  7036. return;
  7037. }
  7038. this._isReady = true;
  7039. if (this.onReady) {
  7040. this.onReady(this);
  7041. }
  7042. };
  7043. return Node;
  7044. })();
  7045. BABYLON.Node = Node;
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.node.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var FilesInput = (function () {
  7051. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7052. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7053. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7054. this._engine = p_engine;
  7055. this._canvas = p_canvas;
  7056. this._currentScene = p_scene;
  7057. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7058. this._progressCallback = p_progressCallback;
  7059. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7060. this._textureLoadingCallback = p_textureLoadingCallback;
  7061. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7062. }
  7063. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7064. var _this = this;
  7065. if (p_elementToMonitor) {
  7066. this._elementToMonitor = p_elementToMonitor;
  7067. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7068. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7069. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7070. }
  7071. };
  7072. FilesInput.prototype.renderFunction = function () {
  7073. if (this._additionnalRenderLoopLogicCallback) {
  7074. this._additionnalRenderLoopLogicCallback();
  7075. }
  7076. if (this._currentScene) {
  7077. if (this._textureLoadingCallback) {
  7078. var remaining = this._currentScene.getWaitingItemsCount();
  7079. if (remaining > 0) {
  7080. this._textureLoadingCallback(remaining);
  7081. }
  7082. }
  7083. this._currentScene.render();
  7084. }
  7085. };
  7086. FilesInput.prototype.drag = function (e) {
  7087. e.stopPropagation();
  7088. e.preventDefault();
  7089. };
  7090. FilesInput.prototype.drop = function (eventDrop) {
  7091. eventDrop.stopPropagation();
  7092. eventDrop.preventDefault();
  7093. this.loadFiles(eventDrop);
  7094. };
  7095. FilesInput.prototype.loadFiles = function (event) {
  7096. if (this._startingProcessingFilesCallback)
  7097. this._startingProcessingFilesCallback();
  7098. // Handling data transfer via drag'n'drop
  7099. if (event && event.dataTransfer && event.dataTransfer.files) {
  7100. this._filesToLoad = event.dataTransfer.files;
  7101. }
  7102. // Handling files from input files
  7103. if (event && event.target && event.target.files) {
  7104. this._filesToLoad = event.target.files;
  7105. }
  7106. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7107. for (var i = 0; i < this._filesToLoad.length; i++) {
  7108. switch (this._filesToLoad[i].type) {
  7109. case "image/jpeg":
  7110. case "image/png":
  7111. case "image/bmp":
  7112. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7113. break;
  7114. case "image/targa":
  7115. case "image/vnd.ms-dds":
  7116. case "audio/wav":
  7117. case "audio/x-wav":
  7118. case "audio/mp3":
  7119. case "audio/mpeg":
  7120. case "audio/mpeg3":
  7121. case "audio/x-mpeg-3":
  7122. case "audio/ogg":
  7123. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7124. break;
  7125. default:
  7126. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7127. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7128. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7129. this._sceneFileToLoad = this._filesToLoad[i];
  7130. }
  7131. break;
  7132. }
  7133. }
  7134. this.reload();
  7135. }
  7136. };
  7137. FilesInput.prototype.reload = function () {
  7138. var _this = this;
  7139. var that = this;
  7140. // If a ".babylon" file has been provided
  7141. if (this._sceneFileToLoad) {
  7142. if (this._currentScene) {
  7143. this._engine.stopRenderLoop();
  7144. this._currentScene.dispose();
  7145. }
  7146. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7147. that._currentScene = newScene;
  7148. // Wait for textures and shaders to be ready
  7149. that._currentScene.executeWhenReady(function () {
  7150. // Attach camera to canvas inputs
  7151. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7152. that._currentScene.createDefaultCameraOrLight();
  7153. }
  7154. that._currentScene.activeCamera.attachControl(that._canvas);
  7155. if (that._sceneLoadedCallback) {
  7156. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7157. }
  7158. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7159. });
  7160. }, function (progress) {
  7161. if (_this._progressCallback) {
  7162. _this._progressCallback(progress);
  7163. }
  7164. });
  7165. }
  7166. else {
  7167. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7168. }
  7169. };
  7170. FilesInput.FilesTextures = new Array();
  7171. FilesInput.FilesToLoad = new Array();
  7172. return FilesInput;
  7173. })();
  7174. BABYLON.FilesInput = FilesInput;
  7175. })(BABYLON || (BABYLON = {}));
  7176. //# sourceMappingURL=babylon.filesInput.js.map
  7177. var BABYLON;
  7178. (function (BABYLON) {
  7179. var IntersectionInfo = (function () {
  7180. function IntersectionInfo(bu, bv, distance) {
  7181. this.bu = bu;
  7182. this.bv = bv;
  7183. this.distance = distance;
  7184. this.faceId = 0;
  7185. this.subMeshId = 0;
  7186. }
  7187. return IntersectionInfo;
  7188. })();
  7189. BABYLON.IntersectionInfo = IntersectionInfo;
  7190. var PickingInfo = (function () {
  7191. function PickingInfo() {
  7192. this.hit = false;
  7193. this.distance = 0;
  7194. this.pickedPoint = null;
  7195. this.pickedMesh = null;
  7196. this.bu = 0;
  7197. this.bv = 0;
  7198. this.faceId = -1;
  7199. this.subMeshId = 0;
  7200. }
  7201. // Methods
  7202. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7203. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7204. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7205. return null;
  7206. }
  7207. var indices = this.pickedMesh.getIndices();
  7208. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7209. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7210. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7211. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7212. normal0 = normal0.scale(this.bu);
  7213. normal1 = normal1.scale(this.bv);
  7214. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7215. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7216. if (useWorldCoordinates) {
  7217. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7218. }
  7219. return result;
  7220. };
  7221. PickingInfo.prototype.getTextureCoordinates = function () {
  7222. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7223. return null;
  7224. }
  7225. var indices = this.pickedMesh.getIndices();
  7226. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7227. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7228. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7229. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7230. uv0 = uv0.scale(this.bu);
  7231. uv1 = uv1.scale(this.bv);
  7232. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7233. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7234. };
  7235. return PickingInfo;
  7236. })();
  7237. BABYLON.PickingInfo = PickingInfo;
  7238. })(BABYLON || (BABYLON = {}));
  7239. //# sourceMappingURL=babylon.pickingInfo.js.map
  7240. var BABYLON;
  7241. (function (BABYLON) {
  7242. var BoundingSphere = (function () {
  7243. function BoundingSphere(minimum, maximum) {
  7244. this.minimum = minimum;
  7245. this.maximum = maximum;
  7246. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7247. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7248. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7249. this.radius = distance * 0.5;
  7250. this.centerWorld = BABYLON.Vector3.Zero();
  7251. this._update(BABYLON.Matrix.Identity());
  7252. }
  7253. // Methods
  7254. BoundingSphere.prototype._update = function (world) {
  7255. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7256. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7257. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7258. };
  7259. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7260. for (var i = 0; i < 6; i++) {
  7261. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7262. return false;
  7263. }
  7264. return true;
  7265. };
  7266. BoundingSphere.prototype.intersectsPoint = function (point) {
  7267. var x = this.centerWorld.x - point.x;
  7268. var y = this.centerWorld.y - point.y;
  7269. var z = this.centerWorld.z - point.z;
  7270. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7271. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7272. return false;
  7273. return true;
  7274. };
  7275. // Statics
  7276. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7277. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7278. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7279. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7280. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7281. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7282. return false;
  7283. return true;
  7284. };
  7285. return BoundingSphere;
  7286. })();
  7287. BABYLON.BoundingSphere = BoundingSphere;
  7288. })(BABYLON || (BABYLON = {}));
  7289. //# sourceMappingURL=babylon.boundingSphere.js.map
  7290. var BABYLON;
  7291. (function (BABYLON) {
  7292. var BoundingBox = (function () {
  7293. function BoundingBox(minimum, maximum) {
  7294. this.minimum = minimum;
  7295. this.maximum = maximum;
  7296. this.vectors = new Array();
  7297. this.vectorsWorld = new Array();
  7298. // Bounding vectors
  7299. this.vectors.push(this.minimum.clone());
  7300. this.vectors.push(this.maximum.clone());
  7301. this.vectors.push(this.minimum.clone());
  7302. this.vectors[2].x = this.maximum.x;
  7303. this.vectors.push(this.minimum.clone());
  7304. this.vectors[3].y = this.maximum.y;
  7305. this.vectors.push(this.minimum.clone());
  7306. this.vectors[4].z = this.maximum.z;
  7307. this.vectors.push(this.maximum.clone());
  7308. this.vectors[5].z = this.minimum.z;
  7309. this.vectors.push(this.maximum.clone());
  7310. this.vectors[6].x = this.minimum.x;
  7311. this.vectors.push(this.maximum.clone());
  7312. this.vectors[7].y = this.minimum.y;
  7313. // OBB
  7314. this.center = this.maximum.add(this.minimum).scale(0.5);
  7315. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7316. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7317. // World
  7318. for (var index = 0; index < this.vectors.length; index++) {
  7319. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7320. }
  7321. this.minimumWorld = BABYLON.Vector3.Zero();
  7322. this.maximumWorld = BABYLON.Vector3.Zero();
  7323. this._update(BABYLON.Matrix.Identity());
  7324. }
  7325. // Methods
  7326. BoundingBox.prototype.getWorldMatrix = function () {
  7327. return this._worldMatrix;
  7328. };
  7329. BoundingBox.prototype._update = function (world) {
  7330. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7331. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7332. for (var index = 0; index < this.vectors.length; index++) {
  7333. var v = this.vectorsWorld[index];
  7334. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7335. if (v.x < this.minimumWorld.x)
  7336. this.minimumWorld.x = v.x;
  7337. if (v.y < this.minimumWorld.y)
  7338. this.minimumWorld.y = v.y;
  7339. if (v.z < this.minimumWorld.z)
  7340. this.minimumWorld.z = v.z;
  7341. if (v.x > this.maximumWorld.x)
  7342. this.maximumWorld.x = v.x;
  7343. if (v.y > this.maximumWorld.y)
  7344. this.maximumWorld.y = v.y;
  7345. if (v.z > this.maximumWorld.z)
  7346. this.maximumWorld.z = v.z;
  7347. }
  7348. // OBB
  7349. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7350. this.center.scaleInPlace(0.5);
  7351. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7352. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7353. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7354. this._worldMatrix = world;
  7355. };
  7356. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7357. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7358. };
  7359. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7360. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7361. };
  7362. BoundingBox.prototype.intersectsPoint = function (point) {
  7363. var delta = -BABYLON.Engine.Epsilon;
  7364. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7365. return false;
  7366. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7367. return false;
  7368. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7369. return false;
  7370. return true;
  7371. };
  7372. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7373. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7374. };
  7375. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7376. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7377. return false;
  7378. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7379. return false;
  7380. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7381. return false;
  7382. return true;
  7383. };
  7384. // Statics
  7385. BoundingBox.Intersects = function (box0, box1) {
  7386. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7387. return false;
  7388. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7389. return false;
  7390. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7391. return false;
  7392. return true;
  7393. };
  7394. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7395. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7396. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7397. return (num <= (sphereRadius * sphereRadius));
  7398. };
  7399. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7400. for (var p = 0; p < 6; p++) {
  7401. for (var i = 0; i < 8; i++) {
  7402. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7403. return false;
  7404. }
  7405. }
  7406. }
  7407. return true;
  7408. };
  7409. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7410. for (var p = 0; p < 6; p++) {
  7411. var inCount = 8;
  7412. for (var i = 0; i < 8; i++) {
  7413. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7414. --inCount;
  7415. }
  7416. else {
  7417. break;
  7418. }
  7419. }
  7420. if (inCount === 0)
  7421. return false;
  7422. }
  7423. return true;
  7424. };
  7425. return BoundingBox;
  7426. })();
  7427. BABYLON.BoundingBox = BoundingBox;
  7428. })(BABYLON || (BABYLON = {}));
  7429. //# sourceMappingURL=babylon.boundingBox.js.map
  7430. var BABYLON;
  7431. (function (BABYLON) {
  7432. var computeBoxExtents = function (axis, box) {
  7433. var p = BABYLON.Vector3.Dot(box.center, axis);
  7434. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7435. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7436. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7437. var r = r0 + r1 + r2;
  7438. return {
  7439. min: p - r,
  7440. max: p + r
  7441. };
  7442. };
  7443. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7444. var axisOverlap = function (axis, box0, box1) {
  7445. var result0 = computeBoxExtents(axis, box0);
  7446. var result1 = computeBoxExtents(axis, box1);
  7447. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7448. };
  7449. var BoundingInfo = (function () {
  7450. function BoundingInfo(minimum, maximum) {
  7451. this.minimum = minimum;
  7452. this.maximum = maximum;
  7453. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7454. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7455. }
  7456. // Methods
  7457. BoundingInfo.prototype._update = function (world) {
  7458. this.boundingBox._update(world);
  7459. this.boundingSphere._update(world);
  7460. };
  7461. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7462. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7463. return false;
  7464. return this.boundingBox.isInFrustum(frustumPlanes);
  7465. };
  7466. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7467. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7468. };
  7469. BoundingInfo.prototype._checkCollision = function (collider) {
  7470. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7471. };
  7472. BoundingInfo.prototype.intersectsPoint = function (point) {
  7473. if (!this.boundingSphere.centerWorld) {
  7474. return false;
  7475. }
  7476. if (!this.boundingSphere.intersectsPoint(point)) {
  7477. return false;
  7478. }
  7479. if (!this.boundingBox.intersectsPoint(point)) {
  7480. return false;
  7481. }
  7482. return true;
  7483. };
  7484. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7485. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7486. return false;
  7487. }
  7488. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7489. return false;
  7490. }
  7491. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7492. return false;
  7493. }
  7494. if (!precise) {
  7495. return true;
  7496. }
  7497. var box0 = this.boundingBox;
  7498. var box1 = boundingInfo.boundingBox;
  7499. if (!axisOverlap(box0.directions[0], box0, box1))
  7500. return false;
  7501. if (!axisOverlap(box0.directions[1], box0, box1))
  7502. return false;
  7503. if (!axisOverlap(box0.directions[2], box0, box1))
  7504. return false;
  7505. if (!axisOverlap(box1.directions[0], box0, box1))
  7506. return false;
  7507. if (!axisOverlap(box1.directions[1], box0, box1))
  7508. return false;
  7509. if (!axisOverlap(box1.directions[2], box0, box1))
  7510. return false;
  7511. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7512. return false;
  7513. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7514. return false;
  7515. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7516. return false;
  7517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7518. return false;
  7519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7520. return false;
  7521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7522. return false;
  7523. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7524. return false;
  7525. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7526. return false;
  7527. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7528. return false;
  7529. return true;
  7530. };
  7531. return BoundingInfo;
  7532. })();
  7533. BABYLON.BoundingInfo = BoundingInfo;
  7534. })(BABYLON || (BABYLON = {}));
  7535. //# sourceMappingURL=babylon.boundingInfo.js.map
  7536. var BABYLON;
  7537. (function (BABYLON) {
  7538. var AbstractMesh = (function (_super) {
  7539. __extends(AbstractMesh, _super);
  7540. function AbstractMesh(name, scene) {
  7541. var _this = this;
  7542. _super.call(this, name, scene);
  7543. // Properties
  7544. this.definedFacingForward = true; // orientation for POV movement & rotation
  7545. this.position = new BABYLON.Vector3(0, 0, 0);
  7546. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7547. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7548. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7549. this.visibility = 1.0;
  7550. this.alphaIndex = Number.MAX_VALUE;
  7551. this.infiniteDistance = false;
  7552. this.isVisible = true;
  7553. this.isPickable = true;
  7554. this.showBoundingBox = false;
  7555. this.showSubMeshesBoundingBox = false;
  7556. this.onDispose = null;
  7557. this.checkCollisions = false;
  7558. this.isBlocker = false;
  7559. this.renderingGroupId = 0;
  7560. this.receiveShadows = false;
  7561. this.renderOutline = false;
  7562. this.outlineColor = BABYLON.Color3.Red();
  7563. this.outlineWidth = 0.02;
  7564. this.renderOverlay = false;
  7565. this.overlayColor = BABYLON.Color3.Red();
  7566. this.overlayAlpha = 0.5;
  7567. this.hasVertexAlpha = false;
  7568. this.useVertexColors = true;
  7569. this.applyFog = true;
  7570. this.useOctreeForRenderingSelection = true;
  7571. this.useOctreeForPicking = true;
  7572. this.useOctreeForCollisions = true;
  7573. this.layerMask = 0x0FFFFFFF;
  7574. this.alwaysSelectAsActiveMesh = false;
  7575. // Physics
  7576. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7577. // Collisions
  7578. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7579. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7580. this._collider = new BABYLON.Collider();
  7581. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7582. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7583. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7584. // Cache
  7585. this._localScaling = BABYLON.Matrix.Zero();
  7586. this._localRotation = BABYLON.Matrix.Zero();
  7587. this._localTranslation = BABYLON.Matrix.Zero();
  7588. this._localBillboard = BABYLON.Matrix.Zero();
  7589. this._localPivotScaling = BABYLON.Matrix.Zero();
  7590. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7591. this._localWorld = BABYLON.Matrix.Zero();
  7592. this._worldMatrix = BABYLON.Matrix.Zero();
  7593. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7594. this._absolutePosition = BABYLON.Vector3.Zero();
  7595. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7596. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7597. this._isDirty = false;
  7598. this._pivotMatrix = BABYLON.Matrix.Identity();
  7599. this._isDisposed = false;
  7600. this._renderId = 0;
  7601. this._intersectionsInProgress = new Array();
  7602. this._onAfterWorldMatrixUpdate = new Array();
  7603. this._isWorldMatrixFrozen = false;
  7604. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7605. if (collidedMesh === void 0) { collidedMesh = null; }
  7606. //TODO move this to the collision coordinator!
  7607. if (_this.getScene().workerCollisions)
  7608. newPosition.multiplyInPlace(_this._collider.radius);
  7609. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7610. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7611. _this.position.addInPlace(_this._diffPositionForCollisions);
  7612. }
  7613. };
  7614. scene.addMesh(this);
  7615. }
  7616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7617. get: function () {
  7618. return AbstractMesh._BILLBOARDMODE_NONE;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7624. get: function () {
  7625. return AbstractMesh._BILLBOARDMODE_X;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7631. get: function () {
  7632. return AbstractMesh._BILLBOARDMODE_Y;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7638. get: function () {
  7639. return AbstractMesh._BILLBOARDMODE_Z;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7645. get: function () {
  7646. return AbstractMesh._BILLBOARDMODE_ALL;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7652. // Methods
  7653. get: function () {
  7654. return false;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. AbstractMesh.prototype.getLOD = function (camera) {
  7660. return this;
  7661. };
  7662. AbstractMesh.prototype.getTotalVertices = function () {
  7663. return 0;
  7664. };
  7665. AbstractMesh.prototype.getIndices = function () {
  7666. return null;
  7667. };
  7668. AbstractMesh.prototype.getVerticesData = function (kind) {
  7669. return null;
  7670. };
  7671. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7672. return false;
  7673. };
  7674. AbstractMesh.prototype.getBoundingInfo = function () {
  7675. if (this._masterMesh) {
  7676. return this._masterMesh.getBoundingInfo();
  7677. }
  7678. if (!this._boundingInfo) {
  7679. this._updateBoundingInfo();
  7680. }
  7681. return this._boundingInfo;
  7682. };
  7683. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7684. get: function () {
  7685. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7686. },
  7687. enumerable: true,
  7688. configurable: true
  7689. });
  7690. AbstractMesh.prototype._preActivate = function () {
  7691. };
  7692. AbstractMesh.prototype._activate = function (renderId) {
  7693. this._renderId = renderId;
  7694. };
  7695. AbstractMesh.prototype.getWorldMatrix = function () {
  7696. if (this._masterMesh) {
  7697. return this._masterMesh.getWorldMatrix();
  7698. }
  7699. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7700. this.computeWorldMatrix();
  7701. }
  7702. return this._worldMatrix;
  7703. };
  7704. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7705. get: function () {
  7706. return this._worldMatrix;
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7712. get: function () {
  7713. return this._absolutePosition;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7719. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7720. this.computeWorldMatrix(true);
  7721. this._isWorldMatrixFrozen = true;
  7722. };
  7723. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7724. this._isWorldMatrixFrozen = false;
  7725. this.computeWorldMatrix(true);
  7726. };
  7727. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7728. get: function () {
  7729. return this._isWorldMatrixFrozen;
  7730. },
  7731. enumerable: true,
  7732. configurable: true
  7733. });
  7734. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7735. axis.normalize();
  7736. if (!this.rotationQuaternion) {
  7737. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7738. this.rotation = BABYLON.Vector3.Zero();
  7739. }
  7740. if (!space || space === BABYLON.Space.LOCAL) {
  7741. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7742. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7743. }
  7744. else {
  7745. if (this.parent) {
  7746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7747. invertParentWorldMatrix.invert();
  7748. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7749. }
  7750. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7751. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7752. }
  7753. };
  7754. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7755. var displacementVector = axis.scale(distance);
  7756. if (!space || space === BABYLON.Space.LOCAL) {
  7757. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7758. this.setPositionWithLocalVector(tempV3);
  7759. }
  7760. else {
  7761. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7762. }
  7763. };
  7764. AbstractMesh.prototype.getAbsolutePosition = function () {
  7765. this.computeWorldMatrix();
  7766. return this._absolutePosition;
  7767. };
  7768. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7769. if (!absolutePosition) {
  7770. return;
  7771. }
  7772. var absolutePositionX;
  7773. var absolutePositionY;
  7774. var absolutePositionZ;
  7775. if (absolutePosition.x === undefined) {
  7776. if (arguments.length < 3) {
  7777. return;
  7778. }
  7779. absolutePositionX = arguments[0];
  7780. absolutePositionY = arguments[1];
  7781. absolutePositionZ = arguments[2];
  7782. }
  7783. else {
  7784. absolutePositionX = absolutePosition.x;
  7785. absolutePositionY = absolutePosition.y;
  7786. absolutePositionZ = absolutePosition.z;
  7787. }
  7788. if (this.parent) {
  7789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7790. invertParentWorldMatrix.invert();
  7791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7793. }
  7794. else {
  7795. this.position.x = absolutePositionX;
  7796. this.position.y = absolutePositionY;
  7797. this.position.z = absolutePositionZ;
  7798. }
  7799. };
  7800. // ================================== Point of View Movement =================================
  7801. /**
  7802. * Perform relative position change from the point of view of behind the front of the mesh.
  7803. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7804. * Supports definition of mesh facing forward or backward.
  7805. * @param {number} amountRight
  7806. * @param {number} amountUp
  7807. * @param {number} amountForward
  7808. */
  7809. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7810. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7811. };
  7812. /**
  7813. * Calculate relative position change from the point of view of behind the front of the mesh.
  7814. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7815. * Supports definition of mesh facing forward or backward.
  7816. * @param {number} amountRight
  7817. * @param {number} amountUp
  7818. * @param {number} amountForward
  7819. */
  7820. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7821. var rotMatrix = new BABYLON.Matrix();
  7822. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7823. rotQuaternion.toRotationMatrix(rotMatrix);
  7824. var translationDelta = BABYLON.Vector3.Zero();
  7825. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7827. return translationDelta;
  7828. };
  7829. // ================================== Point of View Rotation =================================
  7830. /**
  7831. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7832. * Supports definition of mesh facing forward or backward.
  7833. * @param {number} flipBack
  7834. * @param {number} twirlClockwise
  7835. * @param {number} tiltRight
  7836. */
  7837. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7839. };
  7840. /**
  7841. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7842. * Supports definition of mesh facing forward or backward.
  7843. * @param {number} flipBack
  7844. * @param {number} twirlClockwise
  7845. * @param {number} tiltRight
  7846. */
  7847. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7848. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7849. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7850. };
  7851. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7852. this._pivotMatrix = matrix;
  7853. this._cache.pivotMatrixUpdated = true;
  7854. };
  7855. AbstractMesh.prototype.getPivotMatrix = function () {
  7856. return this._pivotMatrix;
  7857. };
  7858. AbstractMesh.prototype._isSynchronized = function () {
  7859. if (this._isDirty) {
  7860. return false;
  7861. }
  7862. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7863. return false;
  7864. if (this._cache.pivotMatrixUpdated) {
  7865. return false;
  7866. }
  7867. if (this.infiniteDistance) {
  7868. return false;
  7869. }
  7870. if (!this._cache.position.equals(this.position))
  7871. return false;
  7872. if (this.rotationQuaternion) {
  7873. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7874. return false;
  7875. }
  7876. else {
  7877. if (!this._cache.rotation.equals(this.rotation))
  7878. return false;
  7879. }
  7880. if (!this._cache.scaling.equals(this.scaling))
  7881. return false;
  7882. return true;
  7883. };
  7884. AbstractMesh.prototype._initCache = function () {
  7885. _super.prototype._initCache.call(this);
  7886. this._cache.localMatrixUpdated = false;
  7887. this._cache.position = BABYLON.Vector3.Zero();
  7888. this._cache.scaling = BABYLON.Vector3.Zero();
  7889. this._cache.rotation = BABYLON.Vector3.Zero();
  7890. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7891. };
  7892. AbstractMesh.prototype.markAsDirty = function (property) {
  7893. if (property === "rotation") {
  7894. this.rotationQuaternion = null;
  7895. }
  7896. this._currentRenderId = Number.MAX_VALUE;
  7897. this._isDirty = true;
  7898. };
  7899. AbstractMesh.prototype._updateBoundingInfo = function () {
  7900. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7901. this._boundingInfo._update(this.worldMatrixFromCache);
  7902. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7903. };
  7904. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7905. if (!this.subMeshes) {
  7906. return;
  7907. }
  7908. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7909. var subMesh = this.subMeshes[subIndex];
  7910. subMesh.updateBoundingInfo(matrix);
  7911. }
  7912. };
  7913. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7914. if (this._isWorldMatrixFrozen) {
  7915. return this._worldMatrix;
  7916. }
  7917. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7918. return this._worldMatrix;
  7919. }
  7920. this._cache.position.copyFrom(this.position);
  7921. this._cache.scaling.copyFrom(this.scaling);
  7922. this._cache.pivotMatrixUpdated = false;
  7923. this._currentRenderId = this.getScene().getRenderId();
  7924. this._isDirty = false;
  7925. // Scaling
  7926. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7927. // Rotation
  7928. if (this.rotationQuaternion) {
  7929. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7930. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7931. }
  7932. else {
  7933. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7934. this._cache.rotation.copyFrom(this.rotation);
  7935. }
  7936. // Translation
  7937. if (this.infiniteDistance && !this.parent) {
  7938. var camera = this.getScene().activeCamera;
  7939. var cameraWorldMatrix = camera.getWorldMatrix();
  7940. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7941. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7942. }
  7943. else {
  7944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7945. }
  7946. // Composing transformations
  7947. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7948. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7949. // Billboarding
  7950. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7951. var localPosition = this.position.clone();
  7952. var zero = this.getScene().activeCamera.globalPosition.clone();
  7953. if (this.parent && this.parent.position) {
  7954. localPosition.addInPlace(this.parent.position);
  7955. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7956. }
  7957. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7958. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7959. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7960. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7961. zero.y = localPosition.y + 0.001;
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7963. zero.z = localPosition.z + 0.001;
  7964. }
  7965. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7966. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7967. this._localBillboard.invert();
  7968. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7969. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7970. }
  7971. // Local world
  7972. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7973. // Parent
  7974. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7975. this._markSyncedWithParent();
  7976. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7977. }
  7978. else {
  7979. this._worldMatrix.copyFrom(this._localWorld);
  7980. }
  7981. // Bounding info
  7982. this._updateBoundingInfo();
  7983. // Absolute position
  7984. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7985. // Callbacks
  7986. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7987. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7988. }
  7989. return this._worldMatrix;
  7990. };
  7991. /**
  7992. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7993. * @param func: callback function to add
  7994. */
  7995. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7996. this._onAfterWorldMatrixUpdate.push(func);
  7997. };
  7998. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7999. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8000. if (index > -1) {
  8001. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8002. }
  8003. };
  8004. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8005. this.computeWorldMatrix();
  8006. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8007. };
  8008. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8009. this.computeWorldMatrix();
  8010. var invLocalWorldMatrix = this._localWorld.clone();
  8011. invLocalWorldMatrix.invert();
  8012. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8013. };
  8014. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8015. this.computeWorldMatrix(true);
  8016. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8017. };
  8018. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8019. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8020. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8021. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8022. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8023. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8024. /// <returns>Mesh oriented towards targetMesh</returns>
  8025. yawCor = yawCor || 0; // default to zero if undefined
  8026. pitchCor = pitchCor || 0;
  8027. rollCor = rollCor || 0;
  8028. var dv = targetPoint.subtract(this.position);
  8029. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8030. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8031. var pitch = Math.atan2(dv.y, len);
  8032. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8033. };
  8034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8035. return this._boundingInfo.isInFrustum(frustumPlanes);
  8036. };
  8037. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8038. if (!camera) {
  8039. camera = this.getScene().activeCamera;
  8040. }
  8041. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8042. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8043. return false;
  8044. }
  8045. return true;
  8046. };
  8047. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8048. if (!this._boundingInfo || !mesh._boundingInfo) {
  8049. return false;
  8050. }
  8051. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8052. };
  8053. AbstractMesh.prototype.intersectsPoint = function (point) {
  8054. if (!this._boundingInfo) {
  8055. return false;
  8056. }
  8057. return this._boundingInfo.intersectsPoint(point);
  8058. };
  8059. // Physics
  8060. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8061. var physicsEngine = this.getScene().getPhysicsEngine();
  8062. if (!physicsEngine) {
  8063. return;
  8064. }
  8065. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8066. if (impostor.impostor) {
  8067. // Old API
  8068. options = impostor;
  8069. impostor = impostor.impostor;
  8070. }
  8071. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8072. physicsEngine._unregisterMesh(this);
  8073. return;
  8074. }
  8075. if (!options) {
  8076. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8077. }
  8078. else {
  8079. if (!options.mass && options.mass !== 0)
  8080. options.mass = 0;
  8081. if (!options.friction && options.friction !== 0)
  8082. options.friction = 0.2;
  8083. if (!options.restitution && options.restitution !== 0)
  8084. options.restitution = 0.2;
  8085. }
  8086. this._physicImpostor = impostor;
  8087. this._physicsMass = options.mass;
  8088. this._physicsFriction = options.friction;
  8089. this._physicRestitution = options.restitution;
  8090. return physicsEngine._registerMesh(this, impostor, options);
  8091. };
  8092. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8093. if (!this._physicImpostor) {
  8094. return BABYLON.PhysicsEngine.NoImpostor;
  8095. }
  8096. return this._physicImpostor;
  8097. };
  8098. AbstractMesh.prototype.getPhysicsMass = function () {
  8099. if (!this._physicsMass) {
  8100. return 0;
  8101. }
  8102. return this._physicsMass;
  8103. };
  8104. AbstractMesh.prototype.getPhysicsFriction = function () {
  8105. if (!this._physicsFriction) {
  8106. return 0;
  8107. }
  8108. return this._physicsFriction;
  8109. };
  8110. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8111. if (!this._physicRestitution) {
  8112. return 0;
  8113. }
  8114. return this._physicRestitution;
  8115. };
  8116. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8117. if (!camera) {
  8118. camera = this.getScene().activeCamera;
  8119. }
  8120. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8121. };
  8122. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8123. if (!camera) {
  8124. camera = this.getScene().activeCamera;
  8125. }
  8126. return this.absolutePosition.subtract(camera.position).length();
  8127. };
  8128. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8129. if (!this._physicImpostor) {
  8130. return;
  8131. }
  8132. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8133. };
  8134. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8135. if (!this._physicImpostor) {
  8136. return;
  8137. }
  8138. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8139. };
  8140. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8141. if (!this._physicImpostor) {
  8142. return;
  8143. }
  8144. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8145. };
  8146. // Collisions
  8147. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8148. var globalPosition = this.getAbsolutePosition();
  8149. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8150. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8151. this._collider.radius = this.ellipsoid;
  8152. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8153. };
  8154. // Submeshes octree
  8155. /**
  8156. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8157. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8158. */
  8159. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8160. if (maxCapacity === void 0) { maxCapacity = 64; }
  8161. if (maxDepth === void 0) { maxDepth = 2; }
  8162. if (!this._submeshesOctree) {
  8163. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8164. }
  8165. this.computeWorldMatrix(true);
  8166. // Update octree
  8167. var bbox = this.getBoundingInfo().boundingBox;
  8168. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8169. return this._submeshesOctree;
  8170. };
  8171. // Collisions
  8172. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8173. this._generatePointsArray();
  8174. // Transformation
  8175. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8176. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8177. subMesh._lastColliderWorldVertices = [];
  8178. subMesh._trianglePlanes = [];
  8179. var start = subMesh.verticesStart;
  8180. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8181. for (var i = start; i < end; i++) {
  8182. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8183. }
  8184. }
  8185. // Collide
  8186. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8187. if (collider.collisionFound) {
  8188. collider.collidedMesh = this;
  8189. }
  8190. };
  8191. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8192. var subMeshes;
  8193. var len;
  8194. // Octrees
  8195. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8196. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8197. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8198. len = intersections.length;
  8199. subMeshes = intersections.data;
  8200. }
  8201. else {
  8202. subMeshes = this.subMeshes;
  8203. len = subMeshes.length;
  8204. }
  8205. for (var index = 0; index < len; index++) {
  8206. var subMesh = subMeshes[index];
  8207. // Bounding test
  8208. if (len > 1 && !subMesh._checkCollision(collider))
  8209. continue;
  8210. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8211. }
  8212. };
  8213. AbstractMesh.prototype._checkCollision = function (collider) {
  8214. // Bounding box test
  8215. if (!this._boundingInfo._checkCollision(collider))
  8216. return;
  8217. // Transformation matrix
  8218. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8219. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8220. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8221. };
  8222. // Picking
  8223. AbstractMesh.prototype._generatePointsArray = function () {
  8224. return false;
  8225. };
  8226. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8227. var pickingInfo = new BABYLON.PickingInfo();
  8228. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8229. return pickingInfo;
  8230. }
  8231. if (!this._generatePointsArray()) {
  8232. return pickingInfo;
  8233. }
  8234. var intersectInfo = null;
  8235. // Octrees
  8236. var subMeshes;
  8237. var len;
  8238. if (this._submeshesOctree && this.useOctreeForPicking) {
  8239. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8240. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8241. len = intersections.length;
  8242. subMeshes = intersections.data;
  8243. }
  8244. else {
  8245. subMeshes = this.subMeshes;
  8246. len = subMeshes.length;
  8247. }
  8248. for (var index = 0; index < len; index++) {
  8249. var subMesh = subMeshes[index];
  8250. // Bounding test
  8251. if (len > 1 && !subMesh.canIntersects(ray))
  8252. continue;
  8253. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8254. if (currentIntersectInfo) {
  8255. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8256. intersectInfo = currentIntersectInfo;
  8257. intersectInfo.subMeshId = index;
  8258. if (fastCheck) {
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (intersectInfo) {
  8265. // Get picked point
  8266. var world = this.getWorldMatrix();
  8267. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8268. var direction = ray.direction.clone();
  8269. direction = direction.scale(intersectInfo.distance);
  8270. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8271. var pickedPoint = worldOrigin.add(worldDirection);
  8272. // Return result
  8273. pickingInfo.hit = true;
  8274. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8275. pickingInfo.pickedPoint = pickedPoint;
  8276. pickingInfo.pickedMesh = this;
  8277. pickingInfo.bu = intersectInfo.bu;
  8278. pickingInfo.bv = intersectInfo.bv;
  8279. pickingInfo.faceId = intersectInfo.faceId;
  8280. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8281. return pickingInfo;
  8282. }
  8283. return pickingInfo;
  8284. };
  8285. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8286. return null;
  8287. };
  8288. AbstractMesh.prototype.releaseSubMeshes = function () {
  8289. if (this.subMeshes) {
  8290. while (this.subMeshes.length) {
  8291. this.subMeshes[0].dispose();
  8292. }
  8293. }
  8294. else {
  8295. this.subMeshes = new Array();
  8296. }
  8297. };
  8298. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8299. var index;
  8300. // Physics
  8301. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8302. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8303. }
  8304. // Intersections in progress
  8305. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8306. var other = this._intersectionsInProgress[index];
  8307. var pos = other._intersectionsInProgress.indexOf(this);
  8308. other._intersectionsInProgress.splice(pos, 1);
  8309. }
  8310. this._intersectionsInProgress = [];
  8311. // SubMeshes
  8312. this.releaseSubMeshes();
  8313. // Remove from scene
  8314. this.getScene().removeMesh(this);
  8315. if (!doNotRecurse) {
  8316. // Particles
  8317. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8318. if (this.getScene().particleSystems[index].emitter === this) {
  8319. this.getScene().particleSystems[index].dispose();
  8320. index--;
  8321. }
  8322. }
  8323. // Children
  8324. var objects = this.getScene().meshes.slice(0);
  8325. for (index = 0; index < objects.length; index++) {
  8326. if (objects[index].parent === this) {
  8327. objects[index].dispose();
  8328. }
  8329. }
  8330. }
  8331. else {
  8332. for (index = 0; index < this.getScene().meshes.length; index++) {
  8333. var obj = this.getScene().meshes[index];
  8334. if (obj.parent === this) {
  8335. obj.parent = null;
  8336. obj.computeWorldMatrix(true);
  8337. }
  8338. }
  8339. }
  8340. this._onAfterWorldMatrixUpdate = [];
  8341. this._isDisposed = true;
  8342. // Callback
  8343. if (this.onDispose) {
  8344. this.onDispose();
  8345. }
  8346. };
  8347. // Statics
  8348. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8349. AbstractMesh._BILLBOARDMODE_X = 1;
  8350. AbstractMesh._BILLBOARDMODE_Y = 2;
  8351. AbstractMesh._BILLBOARDMODE_Z = 4;
  8352. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8353. return AbstractMesh;
  8354. })(BABYLON.Node);
  8355. BABYLON.AbstractMesh = AbstractMesh;
  8356. })(BABYLON || (BABYLON = {}));
  8357. //# sourceMappingURL=babylon.abstractMesh.js.map
  8358. var BABYLON;
  8359. (function (BABYLON) {
  8360. var Light = (function (_super) {
  8361. __extends(Light, _super);
  8362. function Light(name, scene) {
  8363. _super.call(this, name, scene);
  8364. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8365. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8366. this.intensity = 1.0;
  8367. this.range = Number.MAX_VALUE;
  8368. this.includeOnlyWithLayerMask = 0;
  8369. this.includedOnlyMeshes = new Array();
  8370. this.excludedMeshes = new Array();
  8371. this.excludeWithLayerMask = 0;
  8372. this._excludedMeshesIds = new Array();
  8373. this._includedOnlyMeshesIds = new Array();
  8374. scene.addLight(this);
  8375. }
  8376. Light.prototype.getShadowGenerator = function () {
  8377. return this._shadowGenerator;
  8378. };
  8379. Light.prototype.getAbsolutePosition = function () {
  8380. return BABYLON.Vector3.Zero();
  8381. };
  8382. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8383. };
  8384. Light.prototype._getWorldMatrix = function () {
  8385. return BABYLON.Matrix.Identity();
  8386. };
  8387. Light.prototype.canAffectMesh = function (mesh) {
  8388. if (!mesh) {
  8389. return true;
  8390. }
  8391. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8392. return false;
  8393. }
  8394. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8395. return false;
  8396. }
  8397. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8398. return false;
  8399. }
  8400. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8401. return false;
  8402. }
  8403. return true;
  8404. };
  8405. Light.prototype.getWorldMatrix = function () {
  8406. this._currentRenderId = this.getScene().getRenderId();
  8407. var worldMatrix = this._getWorldMatrix();
  8408. if (this.parent && this.parent.getWorldMatrix) {
  8409. if (!this._parentedWorldMatrix) {
  8410. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8411. }
  8412. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8413. this._markSyncedWithParent();
  8414. return this._parentedWorldMatrix;
  8415. }
  8416. return worldMatrix;
  8417. };
  8418. Light.prototype.dispose = function () {
  8419. if (this._shadowGenerator) {
  8420. this._shadowGenerator.dispose();
  8421. this._shadowGenerator = null;
  8422. }
  8423. // Remove from scene
  8424. this.getScene().removeLight(this);
  8425. };
  8426. return Light;
  8427. })(BABYLON.Node);
  8428. BABYLON.Light = Light;
  8429. })(BABYLON || (BABYLON = {}));
  8430. //# sourceMappingURL=babylon.light.js.map
  8431. var BABYLON;
  8432. (function (BABYLON) {
  8433. var PointLight = (function (_super) {
  8434. __extends(PointLight, _super);
  8435. function PointLight(name, position, scene) {
  8436. _super.call(this, name, scene);
  8437. this.position = position;
  8438. }
  8439. PointLight.prototype.getAbsolutePosition = function () {
  8440. return this._transformedPosition ? this._transformedPosition : this.position;
  8441. };
  8442. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8443. if (this.parent && this.parent.getWorldMatrix) {
  8444. if (!this._transformedPosition) {
  8445. this._transformedPosition = BABYLON.Vector3.Zero();
  8446. }
  8447. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8448. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8449. return;
  8450. }
  8451. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8452. };
  8453. PointLight.prototype.getShadowGenerator = function () {
  8454. return null;
  8455. };
  8456. PointLight.prototype._getWorldMatrix = function () {
  8457. if (!this._worldMatrix) {
  8458. this._worldMatrix = BABYLON.Matrix.Identity();
  8459. }
  8460. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8461. return this._worldMatrix;
  8462. };
  8463. return PointLight;
  8464. })(BABYLON.Light);
  8465. BABYLON.PointLight = PointLight;
  8466. })(BABYLON || (BABYLON = {}));
  8467. //# sourceMappingURL=babylon.pointLight.js.map
  8468. var BABYLON;
  8469. (function (BABYLON) {
  8470. var SpotLight = (function (_super) {
  8471. __extends(SpotLight, _super);
  8472. function SpotLight(name, position, direction, angle, exponent, scene) {
  8473. _super.call(this, name, scene);
  8474. this.position = position;
  8475. this.direction = direction;
  8476. this.angle = angle;
  8477. this.exponent = exponent;
  8478. }
  8479. SpotLight.prototype.getAbsolutePosition = function () {
  8480. return this.transformedPosition ? this.transformedPosition : this.position;
  8481. };
  8482. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8483. var activeCamera = this.getScene().activeCamera;
  8484. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8485. };
  8486. SpotLight.prototype.supportsVSM = function () {
  8487. return true;
  8488. };
  8489. SpotLight.prototype.needRefreshPerFrame = function () {
  8490. return false;
  8491. };
  8492. SpotLight.prototype.setDirectionToTarget = function (target) {
  8493. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8494. return this.direction;
  8495. };
  8496. SpotLight.prototype.computeTransformedPosition = function () {
  8497. if (this.parent && this.parent.getWorldMatrix) {
  8498. if (!this.transformedPosition) {
  8499. this.transformedPosition = BABYLON.Vector3.Zero();
  8500. }
  8501. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8502. return true;
  8503. }
  8504. return false;
  8505. };
  8506. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8507. var normalizeDirection;
  8508. if (this.parent && this.parent.getWorldMatrix) {
  8509. if (!this._transformedDirection) {
  8510. this._transformedDirection = BABYLON.Vector3.Zero();
  8511. }
  8512. this.computeTransformedPosition();
  8513. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8514. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8515. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8516. }
  8517. else {
  8518. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8519. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8520. }
  8521. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8522. };
  8523. SpotLight.prototype._getWorldMatrix = function () {
  8524. if (!this._worldMatrix) {
  8525. this._worldMatrix = BABYLON.Matrix.Identity();
  8526. }
  8527. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8528. return this._worldMatrix;
  8529. };
  8530. return SpotLight;
  8531. })(BABYLON.Light);
  8532. BABYLON.SpotLight = SpotLight;
  8533. })(BABYLON || (BABYLON = {}));
  8534. //# sourceMappingURL=babylon.spotLight.js.map
  8535. var BABYLON;
  8536. (function (BABYLON) {
  8537. var HemisphericLight = (function (_super) {
  8538. __extends(HemisphericLight, _super);
  8539. function HemisphericLight(name, direction, scene) {
  8540. _super.call(this, name, scene);
  8541. this.direction = direction;
  8542. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8543. }
  8544. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8545. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8546. return this.direction;
  8547. };
  8548. HemisphericLight.prototype.getShadowGenerator = function () {
  8549. return null;
  8550. };
  8551. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8552. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8553. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8554. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8555. };
  8556. HemisphericLight.prototype._getWorldMatrix = function () {
  8557. if (!this._worldMatrix) {
  8558. this._worldMatrix = BABYLON.Matrix.Identity();
  8559. }
  8560. return this._worldMatrix;
  8561. };
  8562. return HemisphericLight;
  8563. })(BABYLON.Light);
  8564. BABYLON.HemisphericLight = HemisphericLight;
  8565. })(BABYLON || (BABYLON = {}));
  8566. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8567. var BABYLON;
  8568. (function (BABYLON) {
  8569. var DirectionalLight = (function (_super) {
  8570. __extends(DirectionalLight, _super);
  8571. function DirectionalLight(name, direction, scene) {
  8572. _super.call(this, name, scene);
  8573. this.direction = direction;
  8574. this.shadowOrthoScale = 0.5;
  8575. this.position = direction.scale(-1);
  8576. }
  8577. DirectionalLight.prototype.getAbsolutePosition = function () {
  8578. return this.transformedPosition ? this.transformedPosition : this.position;
  8579. };
  8580. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8581. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8582. return this.direction;
  8583. };
  8584. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8585. var orthoLeft = Number.MAX_VALUE;
  8586. var orthoRight = Number.MIN_VALUE;
  8587. var orthoTop = Number.MIN_VALUE;
  8588. var orthoBottom = Number.MAX_VALUE;
  8589. var tempVector3 = BABYLON.Vector3.Zero();
  8590. var activeCamera = this.getScene().activeCamera;
  8591. // Check extends
  8592. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8593. var mesh = renderList[meshIndex];
  8594. if (!mesh) {
  8595. continue;
  8596. }
  8597. var boundingInfo = mesh.getBoundingInfo();
  8598. if (!boundingInfo) {
  8599. continue;
  8600. }
  8601. var boundingBox = boundingInfo.boundingBox;
  8602. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8603. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8604. if (tempVector3.x < orthoLeft)
  8605. orthoLeft = tempVector3.x;
  8606. if (tempVector3.y < orthoBottom)
  8607. orthoBottom = tempVector3.y;
  8608. if (tempVector3.x > orthoRight)
  8609. orthoRight = tempVector3.x;
  8610. if (tempVector3.y > orthoTop)
  8611. orthoTop = tempVector3.y;
  8612. }
  8613. }
  8614. var xOffset = orthoRight - orthoLeft;
  8615. var yOffset = orthoTop - orthoBottom;
  8616. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8617. };
  8618. DirectionalLight.prototype.supportsVSM = function () {
  8619. return true;
  8620. };
  8621. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8622. return true;
  8623. };
  8624. DirectionalLight.prototype.computeTransformedPosition = function () {
  8625. if (this.parent && this.parent.getWorldMatrix) {
  8626. if (!this.transformedPosition) {
  8627. this.transformedPosition = BABYLON.Vector3.Zero();
  8628. }
  8629. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8630. return true;
  8631. }
  8632. return false;
  8633. };
  8634. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8635. if (this.parent && this.parent.getWorldMatrix) {
  8636. if (!this._transformedDirection) {
  8637. this._transformedDirection = BABYLON.Vector3.Zero();
  8638. }
  8639. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8640. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8641. return;
  8642. }
  8643. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8644. };
  8645. DirectionalLight.prototype._getWorldMatrix = function () {
  8646. if (!this._worldMatrix) {
  8647. this._worldMatrix = BABYLON.Matrix.Identity();
  8648. }
  8649. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8650. return this._worldMatrix;
  8651. };
  8652. return DirectionalLight;
  8653. })(BABYLON.Light);
  8654. BABYLON.DirectionalLight = DirectionalLight;
  8655. })(BABYLON || (BABYLON = {}));
  8656. //# sourceMappingURL=babylon.directionalLight.js.map
  8657. var BABYLON;
  8658. (function (BABYLON) {
  8659. var ShadowGenerator = (function () {
  8660. function ShadowGenerator(mapSize, light) {
  8661. var _this = this;
  8662. // Members
  8663. this._filter = ShadowGenerator.FILTER_NONE;
  8664. this.blurScale = 2;
  8665. this._blurBoxOffset = 0;
  8666. this._bias = 0.00005;
  8667. this._darkness = 0;
  8668. this._transparencyShadow = false;
  8669. this._viewMatrix = BABYLON.Matrix.Zero();
  8670. this._projectionMatrix = BABYLON.Matrix.Zero();
  8671. this._transformMatrix = BABYLON.Matrix.Zero();
  8672. this._worldViewProjection = BABYLON.Matrix.Zero();
  8673. this._light = light;
  8674. this._scene = light.getScene();
  8675. this._mapSize = mapSize;
  8676. light._shadowGenerator = this;
  8677. // Render target
  8678. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8679. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8680. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8681. this._shadowMap.anisotropicFilteringLevel = 1;
  8682. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8683. this._shadowMap.renderParticles = false;
  8684. this._shadowMap.onAfterUnbind = function () {
  8685. if (!_this.useBlurVarianceShadowMap) {
  8686. return;
  8687. }
  8688. if (!_this._shadowMap2) {
  8689. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8690. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8691. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8692. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8693. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8694. _this._downSamplePostprocess.onApply = function (effect) {
  8695. effect.setTexture("textureSampler", _this._shadowMap);
  8696. };
  8697. _this.blurBoxOffset = 1;
  8698. }
  8699. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8700. };
  8701. // Custom render function
  8702. var renderSubMesh = function (subMesh) {
  8703. var mesh = subMesh.getRenderingMesh();
  8704. var scene = _this._scene;
  8705. var engine = scene.getEngine();
  8706. // Culling
  8707. engine.setState(subMesh.getMaterial().backFaceCulling);
  8708. // Managing instances
  8709. var batch = mesh._getInstancesRenderList(subMesh._id);
  8710. if (batch.mustReturn) {
  8711. return;
  8712. }
  8713. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8714. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8715. engine.enableEffect(_this._effect);
  8716. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8717. var material = subMesh.getMaterial();
  8718. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8719. // Alpha test
  8720. if (material && material.needAlphaTesting()) {
  8721. var alphaTexture = material.getAlphaTestTexture();
  8722. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8723. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8724. }
  8725. // Bones
  8726. if (mesh.useBones) {
  8727. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8728. }
  8729. // Draw
  8730. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8731. }
  8732. else {
  8733. // Need to reset refresh rate of the shadowMap
  8734. _this._shadowMap.resetRefreshCounter();
  8735. }
  8736. };
  8737. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8738. var index;
  8739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8740. renderSubMesh(opaqueSubMeshes.data[index]);
  8741. }
  8742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8743. renderSubMesh(alphaTestSubMeshes.data[index]);
  8744. }
  8745. if (_this._transparencyShadow) {
  8746. for (index = 0; index < transparentSubMeshes.length; index++) {
  8747. renderSubMesh(transparentSubMeshes.data[index]);
  8748. }
  8749. }
  8750. };
  8751. this._shadowMap.onClear = function (engine) {
  8752. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8753. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8754. }
  8755. else {
  8756. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8757. }
  8758. };
  8759. }
  8760. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8761. // Static
  8762. get: function () {
  8763. return ShadowGenerator._FILTER_NONE;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8769. get: function () {
  8770. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8771. },
  8772. enumerable: true,
  8773. configurable: true
  8774. });
  8775. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8776. get: function () {
  8777. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8783. get: function () {
  8784. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8790. get: function () {
  8791. return this._bias;
  8792. },
  8793. set: function (bias) {
  8794. this._bias = bias;
  8795. },
  8796. enumerable: true,
  8797. configurable: true
  8798. });
  8799. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8800. get: function () {
  8801. return this._blurBoxOffset;
  8802. },
  8803. set: function (value) {
  8804. var _this = this;
  8805. if (this._blurBoxOffset === value) {
  8806. return;
  8807. }
  8808. this._blurBoxOffset = value;
  8809. if (this._boxBlurPostprocess) {
  8810. this._boxBlurPostprocess.dispose();
  8811. }
  8812. 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);
  8813. this._boxBlurPostprocess.onApply = function (effect) {
  8814. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8815. };
  8816. },
  8817. enumerable: true,
  8818. configurable: true
  8819. });
  8820. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8821. get: function () {
  8822. return this._filter;
  8823. },
  8824. set: function (value) {
  8825. if (this._filter === value) {
  8826. return;
  8827. }
  8828. this._filter = value;
  8829. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8830. this._shadowMap.anisotropicFilteringLevel = 16;
  8831. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8832. }
  8833. else {
  8834. this._shadowMap.anisotropicFilteringLevel = 1;
  8835. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8836. }
  8837. },
  8838. enumerable: true,
  8839. configurable: true
  8840. });
  8841. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8842. get: function () {
  8843. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8844. },
  8845. set: function (value) {
  8846. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8847. },
  8848. enumerable: true,
  8849. configurable: true
  8850. });
  8851. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8852. get: function () {
  8853. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8854. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8855. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8856. },
  8857. set: function (value) {
  8858. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8859. },
  8860. enumerable: true,
  8861. configurable: true
  8862. });
  8863. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8864. get: function () {
  8865. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8866. },
  8867. set: function (value) {
  8868. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8874. var defines = [];
  8875. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8876. defines.push("#define VSM");
  8877. }
  8878. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8879. var mesh = subMesh.getMesh();
  8880. var material = subMesh.getMaterial();
  8881. // Alpha test
  8882. if (material && material.needAlphaTesting()) {
  8883. defines.push("#define ALPHATEST");
  8884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8885. attribs.push(BABYLON.VertexBuffer.UVKind);
  8886. defines.push("#define UV1");
  8887. }
  8888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8889. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8890. defines.push("#define UV2");
  8891. }
  8892. }
  8893. // Bones
  8894. if (mesh.useBones) {
  8895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8897. defines.push("#define BONES");
  8898. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8899. }
  8900. // Instances
  8901. if (useInstances) {
  8902. defines.push("#define INSTANCES");
  8903. attribs.push("world0");
  8904. attribs.push("world1");
  8905. attribs.push("world2");
  8906. attribs.push("world3");
  8907. }
  8908. // Get correct effect
  8909. var join = defines.join("\n");
  8910. if (this._cachedDefines !== join) {
  8911. this._cachedDefines = join;
  8912. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8913. }
  8914. return this._effect.isReady();
  8915. };
  8916. ShadowGenerator.prototype.getShadowMap = function () {
  8917. return this._shadowMap;
  8918. };
  8919. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8920. if (this._shadowMap2) {
  8921. return this._shadowMap2;
  8922. }
  8923. return this._shadowMap;
  8924. };
  8925. ShadowGenerator.prototype.getLight = function () {
  8926. return this._light;
  8927. };
  8928. // Methods
  8929. ShadowGenerator.prototype.getTransformMatrix = function () {
  8930. var scene = this._scene;
  8931. if (this._currentRenderID === scene.getRenderId()) {
  8932. return this._transformMatrix;
  8933. }
  8934. this._currentRenderID = scene.getRenderId();
  8935. var lightPosition = this._light.position;
  8936. var lightDirection = this._light.direction;
  8937. if (this._light.computeTransformedPosition()) {
  8938. lightPosition = this._light.transformedPosition;
  8939. }
  8940. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8941. this._cachedPosition = lightPosition.clone();
  8942. this._cachedDirection = lightDirection.clone();
  8943. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8944. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8945. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8946. }
  8947. return this._transformMatrix;
  8948. };
  8949. ShadowGenerator.prototype.getDarkness = function () {
  8950. return this._darkness;
  8951. };
  8952. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8953. if (darkness >= 1.0)
  8954. this._darkness = 1.0;
  8955. else if (darkness <= 0.0)
  8956. this._darkness = 0.0;
  8957. else
  8958. this._darkness = darkness;
  8959. };
  8960. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8961. this._transparencyShadow = hasShadow;
  8962. };
  8963. ShadowGenerator.prototype._packHalf = function (depth) {
  8964. var scale = depth * 255.0;
  8965. var fract = scale - Math.floor(scale);
  8966. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8967. };
  8968. ShadowGenerator.prototype.dispose = function () {
  8969. this._shadowMap.dispose();
  8970. if (this._shadowMap2) {
  8971. this._shadowMap2.dispose();
  8972. }
  8973. if (this._downSamplePostprocess) {
  8974. this._downSamplePostprocess.dispose();
  8975. }
  8976. if (this._boxBlurPostprocess) {
  8977. this._boxBlurPostprocess.dispose();
  8978. }
  8979. };
  8980. ShadowGenerator._FILTER_NONE = 0;
  8981. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8982. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8983. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8984. return ShadowGenerator;
  8985. })();
  8986. BABYLON.ShadowGenerator = ShadowGenerator;
  8987. })(BABYLON || (BABYLON = {}));
  8988. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8989. var BABYLON;
  8990. (function (BABYLON) {
  8991. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8992. if (boxMin.x > sphereCenter.x + sphereRadius)
  8993. return false;
  8994. if (sphereCenter.x - sphereRadius > boxMax.x)
  8995. return false;
  8996. if (boxMin.y > sphereCenter.y + sphereRadius)
  8997. return false;
  8998. if (sphereCenter.y - sphereRadius > boxMax.y)
  8999. return false;
  9000. if (boxMin.z > sphereCenter.z + sphereRadius)
  9001. return false;
  9002. if (sphereCenter.z - sphereRadius > boxMax.z)
  9003. return false;
  9004. return true;
  9005. };
  9006. var getLowestRoot = function (a, b, c, maxR) {
  9007. var determinant = b * b - 4.0 * a * c;
  9008. var result = { root: 0, found: false };
  9009. if (determinant < 0)
  9010. return result;
  9011. var sqrtD = Math.sqrt(determinant);
  9012. var r1 = (-b - sqrtD) / (2.0 * a);
  9013. var r2 = (-b + sqrtD) / (2.0 * a);
  9014. if (r1 > r2) {
  9015. var temp = r2;
  9016. r2 = r1;
  9017. r1 = temp;
  9018. }
  9019. if (r1 > 0 && r1 < maxR) {
  9020. result.root = r1;
  9021. result.found = true;
  9022. return result;
  9023. }
  9024. if (r2 > 0 && r2 < maxR) {
  9025. result.root = r2;
  9026. result.found = true;
  9027. return result;
  9028. }
  9029. return result;
  9030. };
  9031. var Collider = (function () {
  9032. function Collider() {
  9033. this.radius = new BABYLON.Vector3(1, 1, 1);
  9034. this.retry = 0;
  9035. this.basePointWorld = BABYLON.Vector3.Zero();
  9036. this.velocityWorld = BABYLON.Vector3.Zero();
  9037. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9038. this._collisionPoint = BABYLON.Vector3.Zero();
  9039. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9040. this._tempVector = BABYLON.Vector3.Zero();
  9041. this._tempVector2 = BABYLON.Vector3.Zero();
  9042. this._tempVector3 = BABYLON.Vector3.Zero();
  9043. this._tempVector4 = BABYLON.Vector3.Zero();
  9044. this._edge = BABYLON.Vector3.Zero();
  9045. this._baseToVertex = BABYLON.Vector3.Zero();
  9046. this._destinationPoint = BABYLON.Vector3.Zero();
  9047. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9048. this._displacementVector = BABYLON.Vector3.Zero();
  9049. }
  9050. // Methods
  9051. Collider.prototype._initialize = function (source, dir, e) {
  9052. this.velocity = dir;
  9053. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9054. this.basePoint = source;
  9055. source.multiplyToRef(this.radius, this.basePointWorld);
  9056. dir.multiplyToRef(this.radius, this.velocityWorld);
  9057. this.velocityWorldLength = this.velocityWorld.length();
  9058. this.epsilon = e;
  9059. this.collisionFound = false;
  9060. };
  9061. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9062. pa.subtractToRef(point, this._tempVector);
  9063. pb.subtractToRef(point, this._tempVector2);
  9064. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9065. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9066. if (d < 0)
  9067. return false;
  9068. pc.subtractToRef(point, this._tempVector3);
  9069. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9070. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9071. if (d < 0)
  9072. return false;
  9073. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9074. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9075. return d >= 0;
  9076. };
  9077. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9078. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9079. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9080. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9081. return false;
  9082. }
  9083. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9084. return false;
  9085. return true;
  9086. };
  9087. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9088. var t0;
  9089. var embeddedInPlane = false;
  9090. //defensive programming, actually not needed.
  9091. if (!trianglePlaneArray) {
  9092. trianglePlaneArray = [];
  9093. }
  9094. if (!trianglePlaneArray[faceIndex]) {
  9095. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9096. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9097. }
  9098. var trianglePlane = trianglePlaneArray[faceIndex];
  9099. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9100. return;
  9101. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9102. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9103. if (normalDotVelocity == 0) {
  9104. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9105. return;
  9106. embeddedInPlane = true;
  9107. t0 = 0;
  9108. }
  9109. else {
  9110. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9111. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9112. if (t0 > t1) {
  9113. var temp = t1;
  9114. t1 = t0;
  9115. t0 = temp;
  9116. }
  9117. if (t0 > 1.0 || t1 < 0.0)
  9118. return;
  9119. if (t0 < 0)
  9120. t0 = 0;
  9121. if (t0 > 1.0)
  9122. t0 = 1.0;
  9123. }
  9124. this._collisionPoint.copyFromFloats(0, 0, 0);
  9125. var found = false;
  9126. var t = 1.0;
  9127. if (!embeddedInPlane) {
  9128. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9129. this.velocity.scaleToRef(t0, this._tempVector);
  9130. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9131. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9132. found = true;
  9133. t = t0;
  9134. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9135. }
  9136. }
  9137. if (!found) {
  9138. var velocitySquaredLength = this.velocity.lengthSquared();
  9139. var a = velocitySquaredLength;
  9140. this.basePoint.subtractToRef(p1, this._tempVector);
  9141. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9142. var c = this._tempVector.lengthSquared() - 1.0;
  9143. var lowestRoot = getLowestRoot(a, b, c, t);
  9144. if (lowestRoot.found) {
  9145. t = lowestRoot.root;
  9146. found = true;
  9147. this._collisionPoint.copyFrom(p1);
  9148. }
  9149. this.basePoint.subtractToRef(p2, this._tempVector);
  9150. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9151. c = this._tempVector.lengthSquared() - 1.0;
  9152. lowestRoot = getLowestRoot(a, b, c, t);
  9153. if (lowestRoot.found) {
  9154. t = lowestRoot.root;
  9155. found = true;
  9156. this._collisionPoint.copyFrom(p2);
  9157. }
  9158. this.basePoint.subtractToRef(p3, this._tempVector);
  9159. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9160. c = this._tempVector.lengthSquared() - 1.0;
  9161. lowestRoot = getLowestRoot(a, b, c, t);
  9162. if (lowestRoot.found) {
  9163. t = lowestRoot.root;
  9164. found = true;
  9165. this._collisionPoint.copyFrom(p3);
  9166. }
  9167. p2.subtractToRef(p1, this._edge);
  9168. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9169. var edgeSquaredLength = this._edge.lengthSquared();
  9170. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9171. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9172. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9173. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9174. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9175. lowestRoot = getLowestRoot(a, b, c, t);
  9176. if (lowestRoot.found) {
  9177. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9178. if (f >= 0.0 && f <= 1.0) {
  9179. t = lowestRoot.root;
  9180. found = true;
  9181. this._edge.scaleInPlace(f);
  9182. p1.addToRef(this._edge, this._collisionPoint);
  9183. }
  9184. }
  9185. p3.subtractToRef(p2, this._edge);
  9186. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9187. edgeSquaredLength = this._edge.lengthSquared();
  9188. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9189. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9190. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9191. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9192. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9193. lowestRoot = getLowestRoot(a, b, c, t);
  9194. if (lowestRoot.found) {
  9195. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9196. if (f >= 0.0 && f <= 1.0) {
  9197. t = lowestRoot.root;
  9198. found = true;
  9199. this._edge.scaleInPlace(f);
  9200. p2.addToRef(this._edge, this._collisionPoint);
  9201. }
  9202. }
  9203. p1.subtractToRef(p3, this._edge);
  9204. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9205. edgeSquaredLength = this._edge.lengthSquared();
  9206. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9207. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9208. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9209. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9210. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9211. lowestRoot = getLowestRoot(a, b, c, t);
  9212. if (lowestRoot.found) {
  9213. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9214. if (f >= 0.0 && f <= 1.0) {
  9215. t = lowestRoot.root;
  9216. found = true;
  9217. this._edge.scaleInPlace(f);
  9218. p3.addToRef(this._edge, this._collisionPoint);
  9219. }
  9220. }
  9221. }
  9222. if (found) {
  9223. var distToCollision = t * this.velocity.length();
  9224. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9225. if (!this.intersectionPoint) {
  9226. this.intersectionPoint = this._collisionPoint.clone();
  9227. }
  9228. else {
  9229. this.intersectionPoint.copyFrom(this._collisionPoint);
  9230. }
  9231. this.nearestDistance = distToCollision;
  9232. this.collisionFound = true;
  9233. }
  9234. }
  9235. };
  9236. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9237. for (var i = indexStart; i < indexEnd; i += 3) {
  9238. var p1 = pts[indices[i] - decal];
  9239. var p2 = pts[indices[i + 1] - decal];
  9240. var p3 = pts[indices[i + 2] - decal];
  9241. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9242. }
  9243. };
  9244. Collider.prototype._getResponse = function (pos, vel) {
  9245. pos.addToRef(vel, this._destinationPoint);
  9246. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9247. this.basePoint.addToRef(vel, pos);
  9248. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9249. this._slidePlaneNormal.normalize();
  9250. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9251. pos.addInPlace(this._displacementVector);
  9252. this.intersectionPoint.addInPlace(this._displacementVector);
  9253. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9254. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9255. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9256. };
  9257. return Collider;
  9258. })();
  9259. BABYLON.Collider = Collider;
  9260. })(BABYLON || (BABYLON = {}));
  9261. //# sourceMappingURL=babylon.collider.js.map
  9262. var BABYLON;
  9263. (function (BABYLON) {
  9264. //WebWorker code will be inserted to this variable.
  9265. BABYLON.CollisionWorker = "";
  9266. (function (WorkerTaskType) {
  9267. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9268. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9269. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9270. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9271. var WorkerTaskType = BABYLON.WorkerTaskType;
  9272. (function (WorkerReplyType) {
  9273. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9274. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9275. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9276. var WorkerReplyType = BABYLON.WorkerReplyType;
  9277. var CollisionCoordinatorWorker = (function () {
  9278. function CollisionCoordinatorWorker() {
  9279. var _this = this;
  9280. this._scaledPosition = BABYLON.Vector3.Zero();
  9281. this._scaledVelocity = BABYLON.Vector3.Zero();
  9282. this.onMeshUpdated = function (mesh) {
  9283. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9284. };
  9285. this.onGeometryUpdated = function (geometry) {
  9286. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9287. };
  9288. this._afterRender = function () {
  9289. if (!_this._init)
  9290. return;
  9291. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9292. return;
  9293. }
  9294. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9295. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9296. if (_this._runningUpdated > 4) {
  9297. return;
  9298. }
  9299. ++_this._runningUpdated;
  9300. var payload = {
  9301. updatedMeshes: _this._addUpdateMeshesList,
  9302. updatedGeometries: _this._addUpdateGeometriesList,
  9303. removedGeometries: _this._toRemoveGeometryArray,
  9304. removedMeshes: _this._toRemoveMeshesArray
  9305. };
  9306. var message = {
  9307. payload: payload,
  9308. taskType: WorkerTaskType.UPDATE
  9309. };
  9310. var serializable = [];
  9311. for (var id in payload.updatedGeometries) {
  9312. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9313. //prepare transferables
  9314. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9315. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9316. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9317. }
  9318. }
  9319. _this._worker.postMessage(message, serializable);
  9320. _this._addUpdateMeshesList = {};
  9321. _this._addUpdateGeometriesList = {};
  9322. _this._toRemoveGeometryArray = [];
  9323. _this._toRemoveMeshesArray = [];
  9324. };
  9325. this._onMessageFromWorker = function (e) {
  9326. var returnData = e.data;
  9327. if (returnData.error != WorkerReplyType.SUCCESS) {
  9328. //TODO what errors can be returned from the worker?
  9329. BABYLON.Tools.Warn("error returned from worker!");
  9330. return;
  9331. }
  9332. switch (returnData.taskType) {
  9333. case WorkerTaskType.INIT:
  9334. _this._init = true;
  9335. //Update the worked with ALL of the scene's current state
  9336. _this._scene.meshes.forEach(function (mesh) {
  9337. _this.onMeshAdded(mesh);
  9338. });
  9339. _this._scene.getGeometries().forEach(function (geometry) {
  9340. _this.onGeometryAdded(geometry);
  9341. });
  9342. break;
  9343. case WorkerTaskType.UPDATE:
  9344. _this._runningUpdated--;
  9345. break;
  9346. case WorkerTaskType.COLLIDE:
  9347. _this._runningCollisionTask = false;
  9348. var returnPayload = returnData.payload;
  9349. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9350. return;
  9351. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9352. //cleanup
  9353. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9354. break;
  9355. }
  9356. };
  9357. this._collisionsCallbackArray = [];
  9358. this._init = false;
  9359. this._runningUpdated = 0;
  9360. this._runningCollisionTask = false;
  9361. this._addUpdateMeshesList = {};
  9362. this._addUpdateGeometriesList = {};
  9363. this._toRemoveGeometryArray = [];
  9364. this._toRemoveMeshesArray = [];
  9365. }
  9366. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9367. if (!this._init)
  9368. return;
  9369. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9370. return;
  9371. position.divideToRef(collider.radius, this._scaledPosition);
  9372. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9373. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9374. var payload = {
  9375. collider: {
  9376. position: this._scaledPosition.asArray(),
  9377. velocity: this._scaledVelocity.asArray(),
  9378. radius: collider.radius.asArray()
  9379. },
  9380. collisionId: collisionIndex,
  9381. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9382. maximumRetry: maximumRetry
  9383. };
  9384. var message = {
  9385. payload: payload,
  9386. taskType: WorkerTaskType.COLLIDE
  9387. };
  9388. this._worker.postMessage(message);
  9389. };
  9390. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9391. this._scene = scene;
  9392. this._scene.registerAfterRender(this._afterRender);
  9393. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9394. this._worker = new Worker(workerUrl);
  9395. this._worker.onmessage = this._onMessageFromWorker;
  9396. var message = {
  9397. payload: {},
  9398. taskType: WorkerTaskType.INIT
  9399. };
  9400. this._worker.postMessage(message);
  9401. };
  9402. CollisionCoordinatorWorker.prototype.destroy = function () {
  9403. this._scene.unregisterAfterRender(this._afterRender);
  9404. this._worker.terminate();
  9405. };
  9406. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9407. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9408. this.onMeshUpdated(mesh);
  9409. };
  9410. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9411. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9412. };
  9413. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9414. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9415. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9416. this.onGeometryUpdated(geometry);
  9417. };
  9418. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9419. this._toRemoveGeometryArray.push(geometry.id);
  9420. };
  9421. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9422. var submeshes = [];
  9423. if (mesh.subMeshes) {
  9424. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9425. return {
  9426. position: idx,
  9427. verticesStart: sm.verticesStart,
  9428. verticesCount: sm.verticesCount,
  9429. indexStart: sm.indexStart,
  9430. indexCount: sm.indexCount,
  9431. hasMaterial: !!sm.getMaterial(),
  9432. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9433. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9434. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9435. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9436. };
  9437. });
  9438. }
  9439. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9440. return {
  9441. uniqueId: mesh.uniqueId,
  9442. id: mesh.id,
  9443. name: mesh.name,
  9444. geometryId: geometryId,
  9445. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9446. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9447. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9448. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9449. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9450. subMeshes: submeshes,
  9451. checkCollisions: mesh.checkCollisions
  9452. };
  9453. };
  9454. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9455. return {
  9456. id: geometry.id,
  9457. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9458. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9459. indices: new Int32Array(geometry.getIndices() || []),
  9460. };
  9461. };
  9462. return CollisionCoordinatorWorker;
  9463. })();
  9464. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9465. var CollisionCoordinatorLegacy = (function () {
  9466. function CollisionCoordinatorLegacy() {
  9467. this._scaledPosition = BABYLON.Vector3.Zero();
  9468. this._scaledVelocity = BABYLON.Vector3.Zero();
  9469. this._finalPosition = BABYLON.Vector3.Zero();
  9470. }
  9471. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9472. position.divideToRef(collider.radius, this._scaledPosition);
  9473. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9474. collider.collidedMesh = null;
  9475. collider.retry = 0;
  9476. collider.initialVelocity = this._scaledVelocity;
  9477. collider.initialPosition = this._scaledPosition;
  9478. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9479. this._finalPosition.multiplyInPlace(collider.radius);
  9480. //run the callback
  9481. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9482. };
  9483. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9484. this._scene = scene;
  9485. };
  9486. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9487. //Legacy need no destruction method.
  9488. };
  9489. //No update in legacy mode
  9490. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9491. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9492. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9493. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9494. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9495. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9496. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9497. if (excludedMesh === void 0) { excludedMesh = null; }
  9498. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9499. if (collider.retry >= maximumRetry) {
  9500. finalPosition.copyFrom(position);
  9501. return;
  9502. }
  9503. collider._initialize(position, velocity, closeDistance);
  9504. // Check all meshes
  9505. for (var index = 0; index < this._scene.meshes.length; index++) {
  9506. var mesh = this._scene.meshes[index];
  9507. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9508. mesh._checkCollision(collider);
  9509. }
  9510. }
  9511. if (!collider.collisionFound) {
  9512. position.addToRef(velocity, finalPosition);
  9513. return;
  9514. }
  9515. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9516. collider._getResponse(position, velocity);
  9517. }
  9518. if (velocity.length() <= closeDistance) {
  9519. finalPosition.copyFrom(position);
  9520. return;
  9521. }
  9522. collider.retry++;
  9523. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9524. };
  9525. return CollisionCoordinatorLegacy;
  9526. })();
  9527. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9528. })(BABYLON || (BABYLON = {}));
  9529. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9530. var BABYLON;
  9531. (function (BABYLON) {
  9532. var VRCameraMetrics = (function () {
  9533. function VRCameraMetrics() {
  9534. this.compensateDistorsion = true;
  9535. }
  9536. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9537. get: function () {
  9538. return this.hResolution / (2 * this.vResolution);
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9544. get: function () {
  9545. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9551. get: function () {
  9552. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9553. var h = (4 * meters) / this.hScreenSize;
  9554. return BABYLON.Matrix.Translation(h, 0, 0);
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9560. get: function () {
  9561. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9562. var h = (4 * meters) / this.hScreenSize;
  9563. return BABYLON.Matrix.Translation(-h, 0, 0);
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9569. get: function () {
  9570. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9576. get: function () {
  9577. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. VRCameraMetrics.GetDefault = function () {
  9583. var result = new VRCameraMetrics();
  9584. result.hResolution = 1280;
  9585. result.vResolution = 800;
  9586. result.hScreenSize = 0.149759993;
  9587. result.vScreenSize = 0.0935999975;
  9588. result.vScreenCenter = 0.0467999987,
  9589. result.eyeToScreenDistance = 0.0410000011;
  9590. result.lensSeparationDistance = 0.0635000020;
  9591. result.interpupillaryDistance = 0.0640000030;
  9592. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9593. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9594. result.postProcessScaleFactor = 1.714605507808412;
  9595. result.lensCenterOffset = 0.151976421;
  9596. return result;
  9597. };
  9598. return VRCameraMetrics;
  9599. })();
  9600. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9601. var Camera = (function (_super) {
  9602. __extends(Camera, _super);
  9603. function Camera(name, position, scene) {
  9604. _super.call(this, name, scene);
  9605. this.position = position;
  9606. // Members
  9607. this.upVector = BABYLON.Vector3.Up();
  9608. this.orthoLeft = null;
  9609. this.orthoRight = null;
  9610. this.orthoBottom = null;
  9611. this.orthoTop = null;
  9612. this.fov = 0.8;
  9613. this.minZ = 1.0;
  9614. this.maxZ = 10000.0;
  9615. this.inertia = 0.9;
  9616. this.mode = Camera.PERSPECTIVE_CAMERA;
  9617. this.isIntermediate = false;
  9618. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9619. this.layerMask = 0x0FFFFFFF;
  9620. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9621. // Subcamera members
  9622. this.subCameras = new Array();
  9623. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9624. // Cache
  9625. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9626. this._projectionMatrix = new BABYLON.Matrix();
  9627. this._postProcesses = new Array();
  9628. this._postProcessesTakenIndices = [];
  9629. this._activeMeshes = new BABYLON.SmartArray(256);
  9630. this._globalPosition = BABYLON.Vector3.Zero();
  9631. scene.addCamera(this);
  9632. if (!scene.activeCamera) {
  9633. scene.activeCamera = this;
  9634. }
  9635. }
  9636. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9637. get: function () {
  9638. return Camera._PERSPECTIVE_CAMERA;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9644. get: function () {
  9645. return Camera._ORTHOGRAPHIC_CAMERA;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9651. get: function () {
  9652. return Camera._FOVMODE_VERTICAL_FIXED;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9658. get: function () {
  9659. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9665. get: function () {
  9666. return Camera._SUB_CAMERA_MODE_NONE;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9672. get: function () {
  9673. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC", {
  9679. get: function () {
  9680. return Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC", {
  9686. get: function () {
  9687. return Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9693. get: function () {
  9694. return Camera._SUB_CAMERA_MODE_VR;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9700. get: function () {
  9701. return Camera._SUB_CAMERAID_A;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9707. get: function () {
  9708. return Camera._SUB_CAMERAID_B;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Camera.prototype, "globalPosition", {
  9714. get: function () {
  9715. return this._globalPosition;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Camera.prototype.getActiveMeshes = function () {
  9721. return this._activeMeshes;
  9722. };
  9723. Camera.prototype.isActiveMesh = function (mesh) {
  9724. return (this._activeMeshes.indexOf(mesh) !== -1);
  9725. };
  9726. //Cache
  9727. Camera.prototype._initCache = function () {
  9728. _super.prototype._initCache.call(this);
  9729. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9730. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9731. this._cache.mode = undefined;
  9732. this._cache.minZ = undefined;
  9733. this._cache.maxZ = undefined;
  9734. this._cache.fov = undefined;
  9735. this._cache.aspectRatio = undefined;
  9736. this._cache.orthoLeft = undefined;
  9737. this._cache.orthoRight = undefined;
  9738. this._cache.orthoBottom = undefined;
  9739. this._cache.orthoTop = undefined;
  9740. this._cache.renderWidth = undefined;
  9741. this._cache.renderHeight = undefined;
  9742. };
  9743. Camera.prototype._updateCache = function (ignoreParentClass) {
  9744. if (!ignoreParentClass) {
  9745. _super.prototype._updateCache.call(this);
  9746. }
  9747. var engine = this.getEngine();
  9748. this._cache.position.copyFrom(this.position);
  9749. this._cache.upVector.copyFrom(this.upVector);
  9750. this._cache.mode = this.mode;
  9751. this._cache.minZ = this.minZ;
  9752. this._cache.maxZ = this.maxZ;
  9753. this._cache.fov = this.fov;
  9754. this._cache.aspectRatio = engine.getAspectRatio(this);
  9755. this._cache.orthoLeft = this.orthoLeft;
  9756. this._cache.orthoRight = this.orthoRight;
  9757. this._cache.orthoBottom = this.orthoBottom;
  9758. this._cache.orthoTop = this.orthoTop;
  9759. this._cache.renderWidth = engine.getRenderWidth();
  9760. this._cache.renderHeight = engine.getRenderHeight();
  9761. };
  9762. Camera.prototype._updateFromScene = function () {
  9763. this.updateCache();
  9764. this._update();
  9765. };
  9766. // Synchronized
  9767. Camera.prototype._isSynchronized = function () {
  9768. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9769. };
  9770. Camera.prototype._isSynchronizedViewMatrix = function () {
  9771. if (!_super.prototype._isSynchronized.call(this))
  9772. return false;
  9773. return this._cache.position.equals(this.position)
  9774. && this._cache.upVector.equals(this.upVector)
  9775. && this.isSynchronizedWithParent();
  9776. };
  9777. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9778. var check = this._cache.mode === this.mode
  9779. && this._cache.minZ === this.minZ
  9780. && this._cache.maxZ === this.maxZ;
  9781. if (!check) {
  9782. return false;
  9783. }
  9784. var engine = this.getEngine();
  9785. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9786. check = this._cache.fov === this.fov
  9787. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9788. }
  9789. else {
  9790. check = this._cache.orthoLeft === this.orthoLeft
  9791. && this._cache.orthoRight === this.orthoRight
  9792. && this._cache.orthoBottom === this.orthoBottom
  9793. && this._cache.orthoTop === this.orthoTop
  9794. && this._cache.renderWidth === engine.getRenderWidth()
  9795. && this._cache.renderHeight === engine.getRenderHeight();
  9796. }
  9797. return check;
  9798. };
  9799. // Controls
  9800. Camera.prototype.attachControl = function (element) {
  9801. };
  9802. Camera.prototype.detachControl = function (element) {
  9803. };
  9804. Camera.prototype._update = function () {
  9805. this._checkInputs();
  9806. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9807. this._updateSubCameras();
  9808. }
  9809. };
  9810. Camera.prototype._checkInputs = function () {
  9811. };
  9812. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9813. if (insertAt === void 0) { insertAt = null; }
  9814. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9815. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9816. return 0;
  9817. }
  9818. if (insertAt == null || insertAt < 0) {
  9819. this._postProcesses.push(postProcess);
  9820. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9821. return this._postProcesses.length - 1;
  9822. }
  9823. var add = 0;
  9824. if (this._postProcesses[insertAt]) {
  9825. var start = this._postProcesses.length - 1;
  9826. for (var i = start; i >= insertAt + 1; --i) {
  9827. this._postProcesses[i + 1] = this._postProcesses[i];
  9828. }
  9829. add = 1;
  9830. }
  9831. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9832. if (this._postProcessesTakenIndices[i] < insertAt) {
  9833. continue;
  9834. }
  9835. start = this._postProcessesTakenIndices.length - 1;
  9836. for (var j = start; j >= i; --j) {
  9837. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9838. }
  9839. this._postProcessesTakenIndices[i] = insertAt;
  9840. break;
  9841. }
  9842. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9843. this._postProcessesTakenIndices.push(insertAt);
  9844. }
  9845. var result = insertAt + add;
  9846. this._postProcesses[result] = postProcess;
  9847. return result;
  9848. };
  9849. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9850. if (atIndices === void 0) { atIndices = null; }
  9851. var result = [];
  9852. if (!atIndices) {
  9853. var length = this._postProcesses.length;
  9854. for (var i = 0; i < length; i++) {
  9855. if (this._postProcesses[i] !== postProcess) {
  9856. continue;
  9857. }
  9858. delete this._postProcesses[i];
  9859. var index = this._postProcessesTakenIndices.indexOf(i);
  9860. this._postProcessesTakenIndices.splice(index, 1);
  9861. }
  9862. }
  9863. else {
  9864. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9865. for (i = 0; i < atIndices.length; i++) {
  9866. var foundPostProcess = this._postProcesses[atIndices[i]];
  9867. if (foundPostProcess !== postProcess) {
  9868. result.push(i);
  9869. continue;
  9870. }
  9871. delete this._postProcesses[atIndices[i]];
  9872. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9873. this._postProcessesTakenIndices.splice(index, 1);
  9874. }
  9875. }
  9876. return result;
  9877. };
  9878. Camera.prototype.getWorldMatrix = function () {
  9879. if (!this._worldMatrix) {
  9880. this._worldMatrix = BABYLON.Matrix.Identity();
  9881. }
  9882. var viewMatrix = this.getViewMatrix();
  9883. viewMatrix.invertToRef(this._worldMatrix);
  9884. return this._worldMatrix;
  9885. };
  9886. Camera.prototype._getViewMatrix = function () {
  9887. return BABYLON.Matrix.Identity();
  9888. };
  9889. Camera.prototype.getViewMatrix = function (force) {
  9890. this._computedViewMatrix = this._computeViewMatrix(force);
  9891. if (!force && this._isSynchronizedViewMatrix()) {
  9892. return this._computedViewMatrix;
  9893. }
  9894. if (!this.parent || !this.parent.getWorldMatrix) {
  9895. this._globalPosition.copyFrom(this.position);
  9896. }
  9897. else {
  9898. if (!this._worldMatrix) {
  9899. this._worldMatrix = BABYLON.Matrix.Identity();
  9900. }
  9901. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9902. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9903. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9904. this._computedViewMatrix.invert();
  9905. this._markSyncedWithParent();
  9906. }
  9907. this._currentRenderId = this.getScene().getRenderId();
  9908. return this._computedViewMatrix;
  9909. };
  9910. Camera.prototype._computeViewMatrix = function (force) {
  9911. if (!force && this._isSynchronizedViewMatrix()) {
  9912. return this._computedViewMatrix;
  9913. }
  9914. this._computedViewMatrix = this._getViewMatrix();
  9915. this._currentRenderId = this.getScene().getRenderId();
  9916. return this._computedViewMatrix;
  9917. };
  9918. Camera.prototype.getProjectionMatrix = function (force) {
  9919. if (!force && this._isSynchronizedProjectionMatrix()) {
  9920. return this._projectionMatrix;
  9921. }
  9922. var engine = this.getEngine();
  9923. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9924. if (this.minZ <= 0) {
  9925. this.minZ = 0.1;
  9926. }
  9927. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9928. return this._projectionMatrix;
  9929. }
  9930. var halfWidth = engine.getRenderWidth() / 2.0;
  9931. var halfHeight = engine.getRenderHeight() / 2.0;
  9932. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9933. return this._projectionMatrix;
  9934. };
  9935. Camera.prototype.dispose = function () {
  9936. // Remove from scene
  9937. this.getScene().removeCamera(this);
  9938. while (this.subCameras.length > 0) {
  9939. this.subCameras.pop().dispose();
  9940. }
  9941. // Postprocesses
  9942. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9943. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9944. }
  9945. };
  9946. // ---- 3D cameras section ----
  9947. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9948. if (halfSpace === void 0) { halfSpace = 0; }
  9949. while (this.subCameras.length > 0) {
  9950. this.subCameras.pop().dispose();
  9951. }
  9952. this._subCameraMode = mode;
  9953. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9954. var camA = this.getSubCamera(this.name + "_A", true);
  9955. var camB = this.getSubCamera(this.name + "_B", false);
  9956. var postProcessA;
  9957. var postProcessB;
  9958. switch (this._subCameraMode) {
  9959. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9960. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9961. camA.isIntermediate = true;
  9962. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9963. postProcessB.onApply = function (effect) {
  9964. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  9965. };
  9966. break;
  9967. case Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC:
  9968. case Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC:
  9969. var isStereoscopicHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  9970. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  9971. camA.isIntermediate = true;
  9972. postProcessB = new BABYLON.StereoscopicInterlacePostProcess("st_interlace", camB, postProcessA, isStereoscopicHoriz);
  9973. break;
  9974. case Camera.SUB_CAMERA_MODE_VR:
  9975. metrics = metrics || VRCameraMetrics.GetDefault();
  9976. camA._vrMetrics = metrics;
  9977. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9978. camA._vrWorkMatrix = new BABYLON.Matrix();
  9979. camA._vrHMatrix = metrics.leftHMatrix;
  9980. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  9981. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  9982. if (metrics.compensateDistorsion) {
  9983. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  9984. }
  9985. camB._vrMetrics = camA._vrMetrics;
  9986. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9987. camB._vrWorkMatrix = new BABYLON.Matrix();
  9988. camB._vrHMatrix = metrics.rightHMatrix;
  9989. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  9990. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  9991. if (metrics.compensateDistorsion) {
  9992. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  9993. }
  9994. }
  9995. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9996. this.subCameras.push(camA);
  9997. this.subCameras.push(camB);
  9998. }
  9999. this._update();
  10000. };
  10001. Camera.prototype._getVRProjectionMatrix = function () {
  10002. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10003. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10004. return this._projectionMatrix;
  10005. };
  10006. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10007. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10008. };
  10009. /**
  10010. * May needs to be overridden by children so sub has required properties to be copied
  10011. */
  10012. Camera.prototype.getSubCamera = function (name, isA) {
  10013. return null;
  10014. };
  10015. /**
  10016. * May needs to be overridden by children
  10017. */
  10018. Camera.prototype._updateSubCameras = function () {
  10019. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10020. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10021. camA.minZ = camB.minZ = this.minZ;
  10022. camA.maxZ = camB.maxZ = this.maxZ;
  10023. camA.fov = camB.fov = this.fov;
  10024. // only update viewport, when ANAGLYPH
  10025. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10026. camA.viewport = camB.viewport = this.viewport;
  10027. }
  10028. };
  10029. // Statics
  10030. Camera._PERSPECTIVE_CAMERA = 0;
  10031. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10032. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10033. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10034. Camera._SUB_CAMERA_MODE_NONE = 0;
  10035. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10036. Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC = 2;
  10037. Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC = 3;
  10038. Camera._SUB_CAMERA_MODE_VR = 4;
  10039. Camera._SUB_CAMERAID_A = 0;
  10040. Camera._SUB_CAMERAID_B = 1;
  10041. return Camera;
  10042. })(BABYLON.Node);
  10043. BABYLON.Camera = Camera;
  10044. })(BABYLON || (BABYLON = {}));
  10045. //# sourceMappingURL=babylon.camera.js.map
  10046. var BABYLON;
  10047. (function (BABYLON) {
  10048. var TargetCamera = (function (_super) {
  10049. __extends(TargetCamera, _super);
  10050. function TargetCamera(name, position, scene) {
  10051. _super.call(this, name, position, scene);
  10052. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10053. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10054. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10055. this.speed = 2.0;
  10056. this.noRotationConstraint = false;
  10057. this.lockedTarget = null;
  10058. this._currentTarget = BABYLON.Vector3.Zero();
  10059. this._viewMatrix = BABYLON.Matrix.Zero();
  10060. this._camMatrix = BABYLON.Matrix.Zero();
  10061. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10062. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10063. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10064. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10065. this._lookAtTemp = BABYLON.Matrix.Zero();
  10066. this._tempMatrix = BABYLON.Matrix.Zero();
  10067. }
  10068. TargetCamera.prototype._getLockedTargetPosition = function () {
  10069. if (!this.lockedTarget) {
  10070. return null;
  10071. }
  10072. return this.lockedTarget.position || this.lockedTarget;
  10073. };
  10074. // Cache
  10075. TargetCamera.prototype._initCache = function () {
  10076. _super.prototype._initCache.call(this);
  10077. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10078. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10079. };
  10080. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10081. if (!ignoreParentClass) {
  10082. _super.prototype._updateCache.call(this);
  10083. }
  10084. var lockedTargetPosition = this._getLockedTargetPosition();
  10085. if (!lockedTargetPosition) {
  10086. this._cache.lockedTarget = null;
  10087. }
  10088. else {
  10089. if (!this._cache.lockedTarget) {
  10090. this._cache.lockedTarget = lockedTargetPosition.clone();
  10091. }
  10092. else {
  10093. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10094. }
  10095. }
  10096. this._cache.rotation.copyFrom(this.rotation);
  10097. };
  10098. // Synchronized
  10099. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10100. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10101. return false;
  10102. }
  10103. var lockedTargetPosition = this._getLockedTargetPosition();
  10104. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10105. && this._cache.rotation.equals(this.rotation);
  10106. };
  10107. // Methods
  10108. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10109. var engine = this.getEngine();
  10110. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10111. };
  10112. // Target
  10113. TargetCamera.prototype.setTarget = function (target) {
  10114. this.upVector.normalize();
  10115. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10116. this._camMatrix.invert();
  10117. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10118. var vDir = target.subtract(this.position);
  10119. if (vDir.x >= 0.0) {
  10120. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10121. }
  10122. else {
  10123. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10124. }
  10125. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10126. if (isNaN(this.rotation.x)) {
  10127. this.rotation.x = 0;
  10128. }
  10129. if (isNaN(this.rotation.y)) {
  10130. this.rotation.y = 0;
  10131. }
  10132. if (isNaN(this.rotation.z)) {
  10133. this.rotation.z = 0;
  10134. }
  10135. };
  10136. TargetCamera.prototype.getTarget = function () {
  10137. return this._currentTarget;
  10138. };
  10139. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10140. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10141. };
  10142. TargetCamera.prototype._updatePosition = function () {
  10143. this.position.addInPlace(this.cameraDirection);
  10144. };
  10145. TargetCamera.prototype._checkInputs = function () {
  10146. var needToMove = this._decideIfNeedsToMove();
  10147. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10148. // Move
  10149. if (needToMove) {
  10150. this._updatePosition();
  10151. }
  10152. // Rotate
  10153. if (needToRotate) {
  10154. this.rotation.x += this.cameraRotation.x;
  10155. this.rotation.y += this.cameraRotation.y;
  10156. if (!this.noRotationConstraint) {
  10157. var limit = (Math.PI / 2) * 0.95;
  10158. if (this.rotation.x > limit)
  10159. this.rotation.x = limit;
  10160. if (this.rotation.x < -limit)
  10161. this.rotation.x = -limit;
  10162. }
  10163. }
  10164. // Inertia
  10165. if (needToMove) {
  10166. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10167. this.cameraDirection.x = 0;
  10168. }
  10169. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10170. this.cameraDirection.y = 0;
  10171. }
  10172. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10173. this.cameraDirection.z = 0;
  10174. }
  10175. this.cameraDirection.scaleInPlace(this.inertia);
  10176. }
  10177. if (needToRotate) {
  10178. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10179. this.cameraRotation.x = 0;
  10180. }
  10181. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10182. this.cameraRotation.y = 0;
  10183. }
  10184. this.cameraRotation.scaleInPlace(this.inertia);
  10185. }
  10186. _super.prototype._checkInputs.call(this);
  10187. };
  10188. TargetCamera.prototype._getViewMatrix = function () {
  10189. if (!this.lockedTarget) {
  10190. // Compute
  10191. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10192. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10193. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10194. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10195. this._lookAtTemp.invert();
  10196. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10197. }
  10198. else {
  10199. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10200. }
  10201. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10202. // Computing target and final matrix
  10203. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10204. }
  10205. else {
  10206. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10207. }
  10208. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10209. return this._viewMatrix;
  10210. };
  10211. TargetCamera.prototype._getVRViewMatrix = function () {
  10212. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10213. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10214. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10215. // Computing target and final matrix
  10216. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10217. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10218. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10219. return this._viewMatrix;
  10220. };
  10221. /**
  10222. * @override
  10223. * needs to be overridden, so sub has required properties to be copied
  10224. */
  10225. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10226. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10227. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10228. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10229. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10230. }
  10231. return subCamera;
  10232. };
  10233. /**
  10234. * @override
  10235. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10236. */
  10237. TargetCamera.prototype._updateSubCameras = function () {
  10238. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10239. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10240. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10241. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10242. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10243. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10244. camA.position.copyFrom(this.position);
  10245. camB.position.copyFrom(this.position);
  10246. }
  10247. else {
  10248. camA.setTarget(this.getTarget());
  10249. camB.setTarget(this.getTarget());
  10250. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10251. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10252. }
  10253. _super.prototype._updateSubCameras.call(this);
  10254. };
  10255. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10256. if (!this._subCamTransformMatrix) {
  10257. this._subCamTransformMatrix = new BABYLON.Matrix();
  10258. }
  10259. var target = this.getTarget();
  10260. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10261. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10262. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10263. };
  10264. return TargetCamera;
  10265. })(BABYLON.Camera);
  10266. BABYLON.TargetCamera = TargetCamera;
  10267. })(BABYLON || (BABYLON = {}));
  10268. //# sourceMappingURL=babylon.targetCamera.js.map
  10269. var BABYLON;
  10270. (function (BABYLON) {
  10271. var FreeCamera = (function (_super) {
  10272. __extends(FreeCamera, _super);
  10273. function FreeCamera(name, position, scene) {
  10274. var _this = this;
  10275. _super.call(this, name, position, scene);
  10276. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10277. this.keysUp = [38];
  10278. this.keysDown = [40];
  10279. this.keysLeft = [37];
  10280. this.keysRight = [39];
  10281. this.checkCollisions = false;
  10282. this.applyGravity = false;
  10283. this.angularSensibility = 2000.0;
  10284. this._keys = [];
  10285. this._collider = new BABYLON.Collider();
  10286. this._needMoveForGravity = false;
  10287. this._oldPosition = BABYLON.Vector3.Zero();
  10288. this._diffPosition = BABYLON.Vector3.Zero();
  10289. this._newPosition = BABYLON.Vector3.Zero();
  10290. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10291. if (collidedMesh === void 0) { collidedMesh = null; }
  10292. //TODO move this to the collision coordinator!
  10293. if (_this.getScene().workerCollisions)
  10294. newPosition.multiplyInPlace(_this._collider.radius);
  10295. var updatePosition = function (newPos) {
  10296. _this._newPosition.copyFrom(newPos);
  10297. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10298. var oldPosition = _this.position.clone();
  10299. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10300. _this.position.addInPlace(_this._diffPosition);
  10301. if (_this.onCollide && collidedMesh) {
  10302. _this.onCollide(collidedMesh);
  10303. }
  10304. }
  10305. };
  10306. updatePosition(newPosition);
  10307. };
  10308. }
  10309. // Controls
  10310. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10311. var _this = this;
  10312. var previousPosition;
  10313. var engine = this.getEngine();
  10314. if (this._attachedElement) {
  10315. return;
  10316. }
  10317. this._attachedElement = element;
  10318. if (this._onMouseDown === undefined) {
  10319. this._onMouseDown = function (evt) {
  10320. previousPosition = {
  10321. x: evt.clientX,
  10322. y: evt.clientY
  10323. };
  10324. if (!noPreventDefault) {
  10325. evt.preventDefault();
  10326. }
  10327. };
  10328. this._onMouseUp = function (evt) {
  10329. previousPosition = null;
  10330. if (!noPreventDefault) {
  10331. evt.preventDefault();
  10332. }
  10333. };
  10334. this._onMouseOut = function (evt) {
  10335. previousPosition = null;
  10336. _this._keys = [];
  10337. if (!noPreventDefault) {
  10338. evt.preventDefault();
  10339. }
  10340. };
  10341. this._onMouseMove = function (evt) {
  10342. if (!previousPosition && !engine.isPointerLock) {
  10343. return;
  10344. }
  10345. var offsetX;
  10346. var offsetY;
  10347. if (!engine.isPointerLock) {
  10348. offsetX = evt.clientX - previousPosition.x;
  10349. offsetY = evt.clientY - previousPosition.y;
  10350. }
  10351. else {
  10352. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10353. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10354. }
  10355. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10356. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10357. previousPosition = {
  10358. x: evt.clientX,
  10359. y: evt.clientY
  10360. };
  10361. if (!noPreventDefault) {
  10362. evt.preventDefault();
  10363. }
  10364. };
  10365. this._onKeyDown = function (evt) {
  10366. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10367. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10368. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10369. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10370. var index = _this._keys.indexOf(evt.keyCode);
  10371. if (index === -1) {
  10372. _this._keys.push(evt.keyCode);
  10373. }
  10374. if (!noPreventDefault) {
  10375. evt.preventDefault();
  10376. }
  10377. }
  10378. };
  10379. this._onKeyUp = function (evt) {
  10380. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10381. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10382. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10383. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10384. var index = _this._keys.indexOf(evt.keyCode);
  10385. if (index >= 0) {
  10386. _this._keys.splice(index, 1);
  10387. }
  10388. if (!noPreventDefault) {
  10389. evt.preventDefault();
  10390. }
  10391. }
  10392. };
  10393. this._onLostFocus = function () {
  10394. _this._keys = [];
  10395. };
  10396. this._reset = function () {
  10397. _this._keys = [];
  10398. previousPosition = null;
  10399. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10400. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10401. };
  10402. }
  10403. element.addEventListener("mousedown", this._onMouseDown, false);
  10404. element.addEventListener("mouseup", this._onMouseUp, false);
  10405. element.addEventListener("mouseout", this._onMouseOut, false);
  10406. element.addEventListener("mousemove", this._onMouseMove, false);
  10407. BABYLON.Tools.RegisterTopRootEvents([
  10408. { name: "keydown", handler: this._onKeyDown },
  10409. { name: "keyup", handler: this._onKeyUp },
  10410. { name: "blur", handler: this._onLostFocus }
  10411. ]);
  10412. };
  10413. FreeCamera.prototype.detachControl = function (element) {
  10414. if (this._attachedElement != element) {
  10415. return;
  10416. }
  10417. element.removeEventListener("mousedown", this._onMouseDown);
  10418. element.removeEventListener("mouseup", this._onMouseUp);
  10419. element.removeEventListener("mouseout", this._onMouseOut);
  10420. element.removeEventListener("mousemove", this._onMouseMove);
  10421. BABYLON.Tools.UnregisterTopRootEvents([
  10422. { name: "keydown", handler: this._onKeyDown },
  10423. { name: "keyup", handler: this._onKeyUp },
  10424. { name: "blur", handler: this._onLostFocus }
  10425. ]);
  10426. this._attachedElement = null;
  10427. if (this._reset) {
  10428. this._reset();
  10429. }
  10430. };
  10431. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10432. var globalPosition;
  10433. if (this.parent) {
  10434. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10435. }
  10436. else {
  10437. globalPosition = this.position;
  10438. }
  10439. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10440. this._collider.radius = this.ellipsoid;
  10441. //add gravity to the velocity to prevent the dual-collision checking
  10442. if (this.applyGravity) {
  10443. velocity.addInPlace(this.getScene().gravity);
  10444. }
  10445. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10446. };
  10447. FreeCamera.prototype._checkInputs = function () {
  10448. if (!this._localDirection) {
  10449. this._localDirection = BABYLON.Vector3.Zero();
  10450. this._transformedDirection = BABYLON.Vector3.Zero();
  10451. }
  10452. // Keyboard
  10453. for (var index = 0; index < this._keys.length; index++) {
  10454. var keyCode = this._keys[index];
  10455. var speed = this._computeLocalCameraSpeed();
  10456. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10457. this._localDirection.copyFromFloats(-speed, 0, 0);
  10458. }
  10459. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10460. this._localDirection.copyFromFloats(0, 0, speed);
  10461. }
  10462. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10463. this._localDirection.copyFromFloats(speed, 0, 0);
  10464. }
  10465. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10466. this._localDirection.copyFromFloats(0, 0, -speed);
  10467. }
  10468. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10469. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10470. this.cameraDirection.addInPlace(this._transformedDirection);
  10471. }
  10472. _super.prototype._checkInputs.call(this);
  10473. };
  10474. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10475. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10476. };
  10477. FreeCamera.prototype._updatePosition = function () {
  10478. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10479. this._collideWithWorld(this.cameraDirection);
  10480. }
  10481. else {
  10482. this.position.addInPlace(this.cameraDirection);
  10483. }
  10484. };
  10485. return FreeCamera;
  10486. })(BABYLON.TargetCamera);
  10487. BABYLON.FreeCamera = FreeCamera;
  10488. })(BABYLON || (BABYLON = {}));
  10489. //# sourceMappingURL=babylon.freeCamera.js.map
  10490. var BABYLON;
  10491. (function (BABYLON) {
  10492. var FollowCamera = (function (_super) {
  10493. __extends(FollowCamera, _super);
  10494. function FollowCamera(name, position, scene) {
  10495. _super.call(this, name, position, scene);
  10496. this.radius = 12;
  10497. this.rotationOffset = 0;
  10498. this.heightOffset = 4;
  10499. this.cameraAcceleration = 0.05;
  10500. this.maxCameraSpeed = 20;
  10501. }
  10502. FollowCamera.prototype.getRadians = function (degrees) {
  10503. return degrees * Math.PI / 180;
  10504. };
  10505. FollowCamera.prototype.follow = function (cameraTarget) {
  10506. if (!cameraTarget)
  10507. return;
  10508. var yRotation;
  10509. if (cameraTarget.rotationQuaternion) {
  10510. var rotMatrix = new BABYLON.Matrix();
  10511. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10512. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10513. }
  10514. else {
  10515. yRotation = cameraTarget.rotation.y;
  10516. }
  10517. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10518. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10519. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10520. var dx = targetX - this.position.x;
  10521. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10522. var dz = (targetZ) - this.position.z;
  10523. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10524. var vy = dy * this.cameraAcceleration;
  10525. var vz = dz * this.cameraAcceleration * 2;
  10526. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10527. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10528. }
  10529. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10530. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10531. }
  10532. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10533. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10534. }
  10535. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10536. this.setTarget(cameraTarget.position);
  10537. };
  10538. FollowCamera.prototype._checkInputs = function () {
  10539. _super.prototype._checkInputs.call(this);
  10540. this.follow(this.target);
  10541. };
  10542. return FollowCamera;
  10543. })(BABYLON.TargetCamera);
  10544. BABYLON.FollowCamera = FollowCamera;
  10545. })(BABYLON || (BABYLON = {}));
  10546. //# sourceMappingURL=babylon.followCamera.js.map
  10547. var BABYLON;
  10548. (function (BABYLON) {
  10549. // We're mainly based on the logic defined into the FreeCamera code
  10550. var TouchCamera = (function (_super) {
  10551. __extends(TouchCamera, _super);
  10552. function TouchCamera(name, position, scene) {
  10553. _super.call(this, name, position, scene);
  10554. this._offsetX = null;
  10555. this._offsetY = null;
  10556. this._pointerCount = 0;
  10557. this._pointerPressed = [];
  10558. this.angularSensibility = 200000.0;
  10559. this.moveSensibility = 500.0;
  10560. }
  10561. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10562. var _this = this;
  10563. var previousPosition;
  10564. if (this._attachedCanvas) {
  10565. return;
  10566. }
  10567. this._attachedCanvas = canvas;
  10568. if (this._onPointerDown === undefined) {
  10569. this._onPointerDown = function (evt) {
  10570. if (!noPreventDefault) {
  10571. evt.preventDefault();
  10572. }
  10573. _this._pointerPressed.push(evt.pointerId);
  10574. if (_this._pointerPressed.length !== 1) {
  10575. return;
  10576. }
  10577. previousPosition = {
  10578. x: evt.clientX,
  10579. y: evt.clientY
  10580. };
  10581. };
  10582. this._onPointerUp = function (evt) {
  10583. if (!noPreventDefault) {
  10584. evt.preventDefault();
  10585. }
  10586. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10587. if (index === -1) {
  10588. return;
  10589. }
  10590. _this._pointerPressed.splice(index, 1);
  10591. if (index != 0) {
  10592. return;
  10593. }
  10594. previousPosition = null;
  10595. _this._offsetX = null;
  10596. _this._offsetY = null;
  10597. };
  10598. this._onPointerMove = function (evt) {
  10599. if (!noPreventDefault) {
  10600. evt.preventDefault();
  10601. }
  10602. if (!previousPosition) {
  10603. return;
  10604. }
  10605. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10606. if (index != 0) {
  10607. return;
  10608. }
  10609. _this._offsetX = evt.clientX - previousPosition.x;
  10610. _this._offsetY = -(evt.clientY - previousPosition.y);
  10611. };
  10612. this._onLostFocus = function () {
  10613. _this._offsetX = null;
  10614. _this._offsetY = null;
  10615. };
  10616. }
  10617. canvas.addEventListener("pointerdown", this._onPointerDown);
  10618. canvas.addEventListener("pointerup", this._onPointerUp);
  10619. canvas.addEventListener("pointerout", this._onPointerUp);
  10620. canvas.addEventListener("pointermove", this._onPointerMove);
  10621. BABYLON.Tools.RegisterTopRootEvents([
  10622. { name: "blur", handler: this._onLostFocus }
  10623. ]);
  10624. };
  10625. TouchCamera.prototype.detachControl = function (canvas) {
  10626. if (this._attachedCanvas != canvas) {
  10627. return;
  10628. }
  10629. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10630. canvas.removeEventListener("pointerup", this._onPointerUp);
  10631. canvas.removeEventListener("pointerout", this._onPointerUp);
  10632. canvas.removeEventListener("pointermove", this._onPointerMove);
  10633. BABYLON.Tools.UnregisterTopRootEvents([
  10634. { name: "blur", handler: this._onLostFocus }
  10635. ]);
  10636. this._attachedCanvas = null;
  10637. };
  10638. TouchCamera.prototype._checkInputs = function () {
  10639. if (!this._offsetX) {
  10640. return;
  10641. }
  10642. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10643. if (this._pointerPressed.length > 1) {
  10644. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10645. }
  10646. else {
  10647. var speed = this._computeLocalCameraSpeed();
  10648. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10649. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10650. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10651. }
  10652. _super.prototype._checkInputs.call(this);
  10653. };
  10654. return TouchCamera;
  10655. })(BABYLON.FreeCamera);
  10656. BABYLON.TouchCamera = TouchCamera;
  10657. })(BABYLON || (BABYLON = {}));
  10658. //# sourceMappingURL=babylon.touchCamera.js.map
  10659. var BABYLON;
  10660. (function (BABYLON) {
  10661. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10662. var ArcRotateCamera = (function (_super) {
  10663. __extends(ArcRotateCamera, _super);
  10664. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10665. var _this = this;
  10666. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10667. this.alpha = alpha;
  10668. this.beta = beta;
  10669. this.radius = radius;
  10670. this.target = target;
  10671. this.inertialAlphaOffset = 0;
  10672. this.inertialBetaOffset = 0;
  10673. this.inertialRadiusOffset = 0;
  10674. this.lowerAlphaLimit = null;
  10675. this.upperAlphaLimit = null;
  10676. this.lowerBetaLimit = 0.01;
  10677. this.upperBetaLimit = Math.PI;
  10678. this.lowerRadiusLimit = null;
  10679. this.upperRadiusLimit = null;
  10680. this.angularSensibility = 1000.0;
  10681. this.wheelPrecision = 3.0;
  10682. this.pinchPrecision = 2.0;
  10683. this.keysUp = [38];
  10684. this.keysDown = [40];
  10685. this.keysLeft = [37];
  10686. this.keysRight = [39];
  10687. this.zoomOnFactor = 1;
  10688. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10689. this.pinchInwards = true;
  10690. this.allowUpsideDown = true;
  10691. this._keys = [];
  10692. this._viewMatrix = new BABYLON.Matrix();
  10693. this.checkCollisions = false;
  10694. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10695. this._collider = new BABYLON.Collider();
  10696. this._previousPosition = BABYLON.Vector3.Zero();
  10697. this._collisionVelocity = BABYLON.Vector3.Zero();
  10698. this._newPosition = BABYLON.Vector3.Zero();
  10699. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10700. if (collidedMesh === void 0) { collidedMesh = null; }
  10701. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10702. newPosition.multiplyInPlace(_this._collider.radius);
  10703. }
  10704. if (!collidedMesh) {
  10705. _this._previousPosition.copyFrom(_this.position);
  10706. }
  10707. else {
  10708. _this.setPosition(_this.position);
  10709. if (_this.onCollide) {
  10710. _this.onCollide(collidedMesh);
  10711. }
  10712. }
  10713. // Recompute because of constraints
  10714. var cosa = Math.cos(_this.alpha);
  10715. var sina = Math.sin(_this.alpha);
  10716. var cosb = Math.cos(_this.beta);
  10717. var sinb = Math.sin(_this.beta);
  10718. var target = _this._getTargetPosition();
  10719. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10720. _this.position.copyFrom(_this._newPosition);
  10721. var up = _this.upVector;
  10722. if (_this.allowUpsideDown && _this.beta < 0) {
  10723. var up = up.clone();
  10724. up = up.negate();
  10725. }
  10726. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10727. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10728. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10729. _this._collisionTriggered = false;
  10730. };
  10731. if (!this.target) {
  10732. this.target = BABYLON.Vector3.Zero();
  10733. }
  10734. this.getViewMatrix();
  10735. }
  10736. ArcRotateCamera.prototype._getTargetPosition = function () {
  10737. return this.target.position || this.target;
  10738. };
  10739. // Cache
  10740. ArcRotateCamera.prototype._initCache = function () {
  10741. _super.prototype._initCache.call(this);
  10742. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10743. this._cache.alpha = undefined;
  10744. this._cache.beta = undefined;
  10745. this._cache.radius = undefined;
  10746. this._cache.targetScreenOffset = undefined;
  10747. };
  10748. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10749. if (!ignoreParentClass) {
  10750. _super.prototype._updateCache.call(this);
  10751. }
  10752. this._cache.target.copyFrom(this._getTargetPosition());
  10753. this._cache.alpha = this.alpha;
  10754. this._cache.beta = this.beta;
  10755. this._cache.radius = this.radius;
  10756. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10757. };
  10758. // Synchronized
  10759. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10760. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10761. return false;
  10762. return this._cache.target.equals(this._getTargetPosition())
  10763. && this._cache.alpha === this.alpha
  10764. && this._cache.beta === this.beta
  10765. && this._cache.radius === this.radius
  10766. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10767. };
  10768. // Methods
  10769. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10770. var _this = this;
  10771. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10772. var previousPinchDistance = 0;
  10773. var pointers = new BABYLON.SmartCollection();
  10774. if (this._attachedElement) {
  10775. return;
  10776. }
  10777. this._attachedElement = element;
  10778. var engine = this.getEngine();
  10779. if (this._onPointerDown === undefined) {
  10780. this._onPointerDown = function (evt) {
  10781. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10782. cacheSoloPointer = pointers.item(evt.pointerId);
  10783. if (!noPreventDefault) {
  10784. evt.preventDefault();
  10785. }
  10786. };
  10787. this._onPointerUp = function (evt) {
  10788. cacheSoloPointer = null;
  10789. previousPinchDistance = 0;
  10790. pointers.remove(evt.pointerId);
  10791. if (!noPreventDefault) {
  10792. evt.preventDefault();
  10793. }
  10794. };
  10795. this._onPointerMove = function (evt) {
  10796. if (!noPreventDefault) {
  10797. evt.preventDefault();
  10798. }
  10799. switch (pointers.count) {
  10800. case 1:
  10801. var offsetX = evt.clientX - cacheSoloPointer.x;
  10802. var offsetY = evt.clientY - cacheSoloPointer.y;
  10803. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10804. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10805. cacheSoloPointer.x = evt.clientX;
  10806. cacheSoloPointer.y = evt.clientY;
  10807. break;
  10808. case 2:
  10809. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10810. pointers.item(evt.pointerId).x = evt.clientX;
  10811. pointers.item(evt.pointerId).y = evt.clientY;
  10812. var direction = _this.pinchInwards ? 1 : -1;
  10813. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10814. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10815. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10816. if (previousPinchDistance === 0) {
  10817. previousPinchDistance = pinchSquaredDistance;
  10818. return;
  10819. }
  10820. if (pinchSquaredDistance !== previousPinchDistance) {
  10821. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10822. previousPinchDistance = pinchSquaredDistance;
  10823. }
  10824. break;
  10825. default:
  10826. if (pointers.item(evt.pointerId)) {
  10827. pointers.item(evt.pointerId).x = evt.clientX;
  10828. pointers.item(evt.pointerId).y = evt.clientY;
  10829. }
  10830. }
  10831. };
  10832. this._onMouseMove = function (evt) {
  10833. if (!engine.isPointerLock) {
  10834. return;
  10835. }
  10836. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10837. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10838. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10839. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10840. if (!noPreventDefault) {
  10841. evt.preventDefault();
  10842. }
  10843. };
  10844. this._wheel = function (event) {
  10845. var delta = 0;
  10846. if (event.wheelDelta) {
  10847. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10848. }
  10849. else if (event.detail) {
  10850. delta = -event.detail / _this.wheelPrecision;
  10851. }
  10852. if (delta)
  10853. _this.inertialRadiusOffset += delta;
  10854. if (event.preventDefault) {
  10855. if (!noPreventDefault) {
  10856. event.preventDefault();
  10857. }
  10858. }
  10859. };
  10860. this._onKeyDown = function (evt) {
  10861. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10862. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10863. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10864. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10865. var index = _this._keys.indexOf(evt.keyCode);
  10866. if (index === -1) {
  10867. _this._keys.push(evt.keyCode);
  10868. }
  10869. if (evt.preventDefault) {
  10870. if (!noPreventDefault) {
  10871. evt.preventDefault();
  10872. }
  10873. }
  10874. }
  10875. };
  10876. this._onKeyUp = function (evt) {
  10877. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10878. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10879. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10880. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10881. var index = _this._keys.indexOf(evt.keyCode);
  10882. if (index >= 0) {
  10883. _this._keys.splice(index, 1);
  10884. }
  10885. if (evt.preventDefault) {
  10886. if (!noPreventDefault) {
  10887. evt.preventDefault();
  10888. }
  10889. }
  10890. }
  10891. };
  10892. this._onLostFocus = function () {
  10893. _this._keys = [];
  10894. pointers.empty();
  10895. previousPinchDistance = 0;
  10896. cacheSoloPointer = null;
  10897. };
  10898. this._onGestureStart = function (e) {
  10899. if (window.MSGesture === undefined) {
  10900. return;
  10901. }
  10902. if (!_this._MSGestureHandler) {
  10903. _this._MSGestureHandler = new MSGesture();
  10904. _this._MSGestureHandler.target = element;
  10905. }
  10906. _this._MSGestureHandler.addPointer(e.pointerId);
  10907. };
  10908. this._onGesture = function (e) {
  10909. _this.radius *= e.scale;
  10910. if (e.preventDefault) {
  10911. if (!noPreventDefault) {
  10912. e.stopPropagation();
  10913. e.preventDefault();
  10914. }
  10915. }
  10916. };
  10917. this._reset = function () {
  10918. _this._keys = [];
  10919. _this.inertialAlphaOffset = 0;
  10920. _this.inertialBetaOffset = 0;
  10921. _this.inertialRadiusOffset = 0;
  10922. pointers.empty();
  10923. previousPinchDistance = 0;
  10924. cacheSoloPointer = null;
  10925. };
  10926. }
  10927. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10928. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10929. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10930. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10931. element.addEventListener("mousemove", this._onMouseMove, false);
  10932. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10933. element.addEventListener("MSGestureChange", this._onGesture, false);
  10934. element.addEventListener('mousewheel', this._wheel, false);
  10935. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10936. BABYLON.Tools.RegisterTopRootEvents([
  10937. { name: "keydown", handler: this._onKeyDown },
  10938. { name: "keyup", handler: this._onKeyUp },
  10939. { name: "blur", handler: this._onLostFocus }
  10940. ]);
  10941. };
  10942. ArcRotateCamera.prototype.detachControl = function (element) {
  10943. if (this._attachedElement !== element) {
  10944. return;
  10945. }
  10946. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10947. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10948. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10949. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10950. element.removeEventListener("mousemove", this._onMouseMove);
  10951. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10952. element.removeEventListener("MSGestureChange", this._onGesture);
  10953. element.removeEventListener('mousewheel', this._wheel);
  10954. element.removeEventListener('DOMMouseScroll', this._wheel);
  10955. BABYLON.Tools.UnregisterTopRootEvents([
  10956. { name: "keydown", handler: this._onKeyDown },
  10957. { name: "keyup", handler: this._onKeyUp },
  10958. { name: "blur", handler: this._onLostFocus }
  10959. ]);
  10960. this._MSGestureHandler = null;
  10961. this._attachedElement = null;
  10962. if (this._reset) {
  10963. this._reset();
  10964. }
  10965. };
  10966. ArcRotateCamera.prototype._checkInputs = function () {
  10967. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10968. if (this._collisionTriggered) {
  10969. return;
  10970. }
  10971. // Keyboard
  10972. for (var index = 0; index < this._keys.length; index++) {
  10973. var keyCode = this._keys[index];
  10974. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10975. this.inertialAlphaOffset -= 0.01;
  10976. }
  10977. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10978. this.inertialBetaOffset -= 0.01;
  10979. }
  10980. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10981. this.inertialAlphaOffset += 0.01;
  10982. }
  10983. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10984. this.inertialBetaOffset += 0.01;
  10985. }
  10986. }
  10987. // Inertia
  10988. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10989. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  10990. this.beta += this.inertialBetaOffset;
  10991. this.radius -= this.inertialRadiusOffset;
  10992. this.inertialAlphaOffset *= this.inertia;
  10993. this.inertialBetaOffset *= this.inertia;
  10994. this.inertialRadiusOffset *= this.inertia;
  10995. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10996. this.inertialAlphaOffset = 0;
  10997. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10998. this.inertialBetaOffset = 0;
  10999. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11000. this.inertialRadiusOffset = 0;
  11001. }
  11002. // Limits
  11003. this._checkLimits();
  11004. _super.prototype._checkInputs.call(this);
  11005. };
  11006. ArcRotateCamera.prototype._checkLimits = function () {
  11007. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11008. if (this.allowUpsideDown && this.beta > Math.PI) {
  11009. this.beta = this.beta - (2 * Math.PI);
  11010. }
  11011. }
  11012. else {
  11013. if (this.beta < this.lowerBetaLimit) {
  11014. this.beta = this.lowerBetaLimit;
  11015. }
  11016. }
  11017. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11018. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11019. this.beta = this.beta + (2 * Math.PI);
  11020. }
  11021. }
  11022. else {
  11023. if (this.beta > this.upperBetaLimit) {
  11024. this.beta = this.upperBetaLimit;
  11025. }
  11026. }
  11027. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11028. this.alpha = this.lowerAlphaLimit;
  11029. }
  11030. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11031. this.alpha = this.upperAlphaLimit;
  11032. }
  11033. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11034. this.radius = this.lowerRadiusLimit;
  11035. }
  11036. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11037. this.radius = this.upperRadiusLimit;
  11038. }
  11039. };
  11040. ArcRotateCamera.prototype.setPosition = function (position) {
  11041. var radiusv3 = position.subtract(this._getTargetPosition());
  11042. this.radius = radiusv3.length();
  11043. // Alpha
  11044. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11045. if (radiusv3.z < 0) {
  11046. this.alpha = 2 * Math.PI - this.alpha;
  11047. }
  11048. // Beta
  11049. this.beta = Math.acos(radiusv3.y / this.radius);
  11050. this._checkLimits();
  11051. };
  11052. ArcRotateCamera.prototype._getViewMatrix = function () {
  11053. // Compute
  11054. var cosa = Math.cos(this.alpha);
  11055. var sina = Math.sin(this.alpha);
  11056. var cosb = Math.cos(this.beta);
  11057. var sinb = Math.sin(this.beta);
  11058. var target = this._getTargetPosition();
  11059. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11060. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11061. this._collider.radius = this.collisionRadius;
  11062. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11063. this._collisionTriggered = true;
  11064. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11065. }
  11066. else {
  11067. this.position.copyFrom(this._newPosition);
  11068. var up = this.upVector;
  11069. if (this.allowUpsideDown && this.beta < 0) {
  11070. var up = up.clone();
  11071. up = up.negate();
  11072. }
  11073. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11074. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11075. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11076. }
  11077. return this._viewMatrix;
  11078. };
  11079. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11080. meshes = meshes || this.getScene().meshes;
  11081. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11082. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11083. this.radius = distance * this.zoomOnFactor;
  11084. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11085. };
  11086. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11087. var meshesOrMinMaxVector;
  11088. var distance;
  11089. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11090. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11091. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11092. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11093. }
  11094. else {
  11095. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11096. distance = meshesOrMinMaxVectorAndDistance.distance;
  11097. }
  11098. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11099. this.maxZ = distance * 2;
  11100. };
  11101. /**
  11102. * @override
  11103. * needs to be overridden, so sub has required properties to be copied
  11104. */
  11105. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11106. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11107. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11108. };
  11109. /**
  11110. * @override
  11111. * needs to be overridden, adding copy of alpha, beta & radius
  11112. */
  11113. ArcRotateCamera.prototype._updateSubCameras = function () {
  11114. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11115. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11116. camA.alpha = this.alpha - this._subCamHalfSpace;
  11117. camB.alpha = this.alpha + this._subCamHalfSpace;
  11118. camA.beta = camB.beta = this.beta;
  11119. camA.radius = camB.radius = this.radius;
  11120. _super.prototype._updateSubCameras.call(this);
  11121. };
  11122. return ArcRotateCamera;
  11123. })(BABYLON.Camera);
  11124. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11125. })(BABYLON || (BABYLON = {}));
  11126. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11127. var BABYLON;
  11128. (function (BABYLON) {
  11129. // We're mainly based on the logic defined into the FreeCamera code
  11130. var DeviceOrientationCamera = (function (_super) {
  11131. __extends(DeviceOrientationCamera, _super);
  11132. function DeviceOrientationCamera(name, position, scene) {
  11133. var _this = this;
  11134. _super.call(this, name, position, scene);
  11135. this._offsetX = null;
  11136. this._offsetY = null;
  11137. this._orientationGamma = 0;
  11138. this._orientationBeta = 0;
  11139. this._initialOrientationGamma = 0;
  11140. this._initialOrientationBeta = 0;
  11141. this.angularSensibility = 10000.0;
  11142. this.moveSensibility = 50.0;
  11143. window.addEventListener("resize", function () {
  11144. _this._initialOrientationGamma = null;
  11145. }, false);
  11146. }
  11147. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11148. var _this = this;
  11149. if (this._attachedCanvas) {
  11150. return;
  11151. }
  11152. this._attachedCanvas = canvas;
  11153. if (!this._orientationChanged) {
  11154. this._orientationChanged = function (evt) {
  11155. if (!_this._initialOrientationGamma) {
  11156. _this._initialOrientationGamma = evt.gamma;
  11157. _this._initialOrientationBeta = evt.beta;
  11158. }
  11159. _this._orientationGamma = evt.gamma;
  11160. _this._orientationBeta = evt.beta;
  11161. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11162. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11163. };
  11164. }
  11165. window.addEventListener("deviceorientation", this._orientationChanged);
  11166. };
  11167. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11168. if (this._attachedCanvas != canvas) {
  11169. return;
  11170. }
  11171. window.removeEventListener("deviceorientation", this._orientationChanged);
  11172. this._attachedCanvas = null;
  11173. this._orientationGamma = 0;
  11174. this._orientationBeta = 0;
  11175. this._initialOrientationGamma = 0;
  11176. this._initialOrientationBeta = 0;
  11177. };
  11178. DeviceOrientationCamera.prototype._checkInputs = function () {
  11179. if (!this._offsetX) {
  11180. return;
  11181. }
  11182. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11183. var speed = this._computeLocalCameraSpeed();
  11184. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11185. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11186. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11187. _super.prototype._checkInputs.call(this);
  11188. };
  11189. return DeviceOrientationCamera;
  11190. })(BABYLON.FreeCamera);
  11191. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11192. })(BABYLON || (BABYLON = {}));
  11193. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11194. var BABYLON;
  11195. (function (BABYLON) {
  11196. var Gamepads = (function () {
  11197. function Gamepads(ongamedpadconnected) {
  11198. var _this = this;
  11199. this.babylonGamepads = [];
  11200. this.oneGamepadConnected = false;
  11201. this.isMonitoring = false;
  11202. this.gamepadEventSupported = 'GamepadEvent' in window;
  11203. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11204. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11205. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  11206. this._callbackGamepadConnected = ongamedpadconnected;
  11207. if (this.gamepadSupportAvailable) {
  11208. // Checking if the gamepad connected event is supported (like in Firefox)
  11209. if (this.gamepadEventSupported) {
  11210. window.addEventListener('gamepadconnected', function (evt) {
  11211. _this._onGamepadConnected(evt);
  11212. }, false);
  11213. window.addEventListener('gamepaddisconnected', function (evt) {
  11214. _this._onGamepadDisconnected(evt);
  11215. }, false);
  11216. }
  11217. else {
  11218. this._startMonitoringGamepads();
  11219. }
  11220. if (!this.oneGamepadConnected) {
  11221. this._insertGamepadDOMInstructions();
  11222. }
  11223. }
  11224. else {
  11225. this._insertGamepadDOMNotSupported();
  11226. }
  11227. }
  11228. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11229. Gamepads.gamepadDOMInfo = document.createElement("div");
  11230. var buttonAImage = document.createElement("img");
  11231. buttonAImage.src = this.buttonADataURL;
  11232. var spanMessage = document.createElement("span");
  11233. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11234. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11235. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11236. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11237. Gamepads.gamepadDOMInfo.style.width = "100%";
  11238. Gamepads.gamepadDOMInfo.style.height = "48px";
  11239. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11240. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11241. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11242. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11243. buttonAImage.style.position = "relative";
  11244. buttonAImage.style.bottom = "8px";
  11245. spanMessage.style.position = "relative";
  11246. spanMessage.style.fontSize = "32px";
  11247. spanMessage.style.bottom = "32px";
  11248. spanMessage.style.color = "green";
  11249. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11250. };
  11251. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11252. Gamepads.gamepadDOMInfo = document.createElement("div");
  11253. var spanMessage = document.createElement("span");
  11254. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11255. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11256. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11257. Gamepads.gamepadDOMInfo.style.width = "100%";
  11258. Gamepads.gamepadDOMInfo.style.height = "40px";
  11259. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11260. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11261. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11262. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11263. spanMessage.style.position = "relative";
  11264. spanMessage.style.fontSize = "32px";
  11265. spanMessage.style.color = "red";
  11266. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11267. };
  11268. Gamepads.prototype.dispose = function () {
  11269. if (Gamepads.gamepadDOMInfo) {
  11270. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11271. }
  11272. };
  11273. Gamepads.prototype._onGamepadConnected = function (evt) {
  11274. var newGamepad = this._addNewGamepad(evt.gamepad);
  11275. if (this._callbackGamepadConnected)
  11276. this._callbackGamepadConnected(newGamepad);
  11277. this._startMonitoringGamepads();
  11278. };
  11279. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11280. if (!this.oneGamepadConnected) {
  11281. this.oneGamepadConnected = true;
  11282. if (Gamepads.gamepadDOMInfo) {
  11283. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11284. Gamepads.gamepadDOMInfo = null;
  11285. }
  11286. }
  11287. var newGamepad;
  11288. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11289. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11290. }
  11291. else {
  11292. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11293. }
  11294. this.babylonGamepads.push(newGamepad);
  11295. return newGamepad;
  11296. };
  11297. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11298. // Remove the gamepad from the list of gamepads to monitor.
  11299. for (var i in this.babylonGamepads) {
  11300. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11301. this.babylonGamepads.splice(i, 1);
  11302. break;
  11303. }
  11304. }
  11305. // If no gamepads are left, stop the polling loop.
  11306. if (this.babylonGamepads.length == 0) {
  11307. this._stopMonitoringGamepads();
  11308. }
  11309. };
  11310. Gamepads.prototype._startMonitoringGamepads = function () {
  11311. if (!this.isMonitoring) {
  11312. this.isMonitoring = true;
  11313. this._checkGamepadsStatus();
  11314. }
  11315. };
  11316. Gamepads.prototype._stopMonitoringGamepads = function () {
  11317. this.isMonitoring = false;
  11318. };
  11319. Gamepads.prototype._checkGamepadsStatus = function () {
  11320. var _this = this;
  11321. // updating gamepad objects
  11322. this._updateGamepadObjects();
  11323. for (var i in this.babylonGamepads) {
  11324. this.babylonGamepads[i].update();
  11325. }
  11326. if (this.isMonitoring) {
  11327. if (window.requestAnimationFrame) {
  11328. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11329. }
  11330. else if (window.mozRequestAnimationFrame) {
  11331. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11332. }
  11333. else if (window.webkitRequestAnimationFrame) {
  11334. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11335. }
  11336. }
  11337. };
  11338. // This function is called only on Chrome, which does not yet support
  11339. // connection/disconnection events, but requires you to monitor
  11340. // an array for changes.
  11341. Gamepads.prototype._updateGamepadObjects = function () {
  11342. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11343. for (var i = 0; i < gamepads.length; i++) {
  11344. if (gamepads[i]) {
  11345. if (!(gamepads[i].index in this.babylonGamepads)) {
  11346. var newGamepad = this._addNewGamepad(gamepads[i]);
  11347. if (this._callbackGamepadConnected) {
  11348. this._callbackGamepadConnected(newGamepad);
  11349. }
  11350. }
  11351. else {
  11352. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11353. }
  11354. }
  11355. }
  11356. };
  11357. return Gamepads;
  11358. })();
  11359. BABYLON.Gamepads = Gamepads;
  11360. var StickValues = (function () {
  11361. function StickValues(x, y) {
  11362. this.x = x;
  11363. this.y = y;
  11364. }
  11365. return StickValues;
  11366. })();
  11367. BABYLON.StickValues = StickValues;
  11368. var Gamepad = (function () {
  11369. function Gamepad(id, index, browserGamepad) {
  11370. this.id = id;
  11371. this.index = index;
  11372. this.browserGamepad = browserGamepad;
  11373. if (this.browserGamepad.axes.length >= 2) {
  11374. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11375. }
  11376. if (this.browserGamepad.axes.length >= 4) {
  11377. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11378. }
  11379. }
  11380. Gamepad.prototype.onleftstickchanged = function (callback) {
  11381. this._onleftstickchanged = callback;
  11382. };
  11383. Gamepad.prototype.onrightstickchanged = function (callback) {
  11384. this._onrightstickchanged = callback;
  11385. };
  11386. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11387. get: function () {
  11388. return this._leftStick;
  11389. },
  11390. set: function (newValues) {
  11391. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11392. this._onleftstickchanged(newValues);
  11393. }
  11394. this._leftStick = newValues;
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11400. get: function () {
  11401. return this._rightStick;
  11402. },
  11403. set: function (newValues) {
  11404. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11405. this._onrightstickchanged(newValues);
  11406. }
  11407. this._rightStick = newValues;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Gamepad.prototype.update = function () {
  11413. if (this._leftStick) {
  11414. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11415. }
  11416. if (this._rightStick) {
  11417. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11418. }
  11419. };
  11420. return Gamepad;
  11421. })();
  11422. BABYLON.Gamepad = Gamepad;
  11423. var GenericPad = (function (_super) {
  11424. __extends(GenericPad, _super);
  11425. function GenericPad(id, index, gamepad) {
  11426. _super.call(this, id, index, gamepad);
  11427. this.id = id;
  11428. this.index = index;
  11429. this.gamepad = gamepad;
  11430. this._buttons = new Array(gamepad.buttons.length);
  11431. }
  11432. GenericPad.prototype.onbuttondown = function (callback) {
  11433. this._onbuttondown = callback;
  11434. };
  11435. GenericPad.prototype.onbuttonup = function (callback) {
  11436. this._onbuttonup = callback;
  11437. };
  11438. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11439. if (newValue !== currentValue) {
  11440. if (this._onbuttondown && newValue === 1) {
  11441. this._onbuttondown(buttonIndex);
  11442. }
  11443. if (this._onbuttonup && newValue === 0) {
  11444. this._onbuttonup(buttonIndex);
  11445. }
  11446. }
  11447. return newValue;
  11448. };
  11449. GenericPad.prototype.update = function () {
  11450. _super.prototype.update.call(this);
  11451. for (var index = 0; index < this._buttons.length; index++) {
  11452. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11453. }
  11454. };
  11455. return GenericPad;
  11456. })(Gamepad);
  11457. BABYLON.GenericPad = GenericPad;
  11458. (function (Xbox360Button) {
  11459. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11460. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11461. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11462. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11463. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11464. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11465. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11466. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11467. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11468. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11469. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11470. var Xbox360Button = BABYLON.Xbox360Button;
  11471. (function (Xbox360Dpad) {
  11472. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11473. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11474. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11475. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11476. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11477. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11478. var Xbox360Pad = (function (_super) {
  11479. __extends(Xbox360Pad, _super);
  11480. function Xbox360Pad() {
  11481. _super.apply(this, arguments);
  11482. this._leftTrigger = 0;
  11483. this._rightTrigger = 0;
  11484. this._buttonA = 0;
  11485. this._buttonB = 0;
  11486. this._buttonX = 0;
  11487. this._buttonY = 0;
  11488. this._buttonBack = 0;
  11489. this._buttonStart = 0;
  11490. this._buttonLB = 0;
  11491. this._buttonRB = 0;
  11492. this._buttonLeftStick = 0;
  11493. this._buttonRightStick = 0;
  11494. this._dPadUp = 0;
  11495. this._dPadDown = 0;
  11496. this._dPadLeft = 0;
  11497. this._dPadRight = 0;
  11498. }
  11499. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11500. this._onlefttriggerchanged = callback;
  11501. };
  11502. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11503. this._onrighttriggerchanged = callback;
  11504. };
  11505. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11506. get: function () {
  11507. return this._leftTrigger;
  11508. },
  11509. set: function (newValue) {
  11510. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11511. this._onlefttriggerchanged(newValue);
  11512. }
  11513. this._leftTrigger = newValue;
  11514. },
  11515. enumerable: true,
  11516. configurable: true
  11517. });
  11518. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11519. get: function () {
  11520. return this._rightTrigger;
  11521. },
  11522. set: function (newValue) {
  11523. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11524. this._onrighttriggerchanged(newValue);
  11525. }
  11526. this._rightTrigger = newValue;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11532. this._onbuttondown = callback;
  11533. };
  11534. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11535. this._onbuttonup = callback;
  11536. };
  11537. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11538. this._ondpaddown = callback;
  11539. };
  11540. Xbox360Pad.prototype.ondpadup = function (callback) {
  11541. this._ondpadup = callback;
  11542. };
  11543. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11544. if (newValue !== currentValue) {
  11545. if (this._onbuttondown && newValue === 1) {
  11546. this._onbuttondown(buttonType);
  11547. }
  11548. if (this._onbuttonup && newValue === 0) {
  11549. this._onbuttonup(buttonType);
  11550. }
  11551. }
  11552. return newValue;
  11553. };
  11554. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11555. if (newValue !== currentValue) {
  11556. if (this._ondpaddown && newValue === 1) {
  11557. this._ondpaddown(buttonType);
  11558. }
  11559. if (this._ondpadup && newValue === 0) {
  11560. this._ondpadup(buttonType);
  11561. }
  11562. }
  11563. return newValue;
  11564. };
  11565. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11566. get: function () {
  11567. return this._buttonA;
  11568. },
  11569. set: function (value) {
  11570. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11571. },
  11572. enumerable: true,
  11573. configurable: true
  11574. });
  11575. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11576. get: function () {
  11577. return this._buttonB;
  11578. },
  11579. set: function (value) {
  11580. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11581. },
  11582. enumerable: true,
  11583. configurable: true
  11584. });
  11585. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11586. get: function () {
  11587. return this._buttonX;
  11588. },
  11589. set: function (value) {
  11590. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11596. get: function () {
  11597. return this._buttonY;
  11598. },
  11599. set: function (value) {
  11600. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11606. get: function () {
  11607. return this._buttonStart;
  11608. },
  11609. set: function (value) {
  11610. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11616. get: function () {
  11617. return this._buttonBack;
  11618. },
  11619. set: function (value) {
  11620. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11626. get: function () {
  11627. return this._buttonLB;
  11628. },
  11629. set: function (value) {
  11630. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11631. },
  11632. enumerable: true,
  11633. configurable: true
  11634. });
  11635. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11636. get: function () {
  11637. return this._buttonRB;
  11638. },
  11639. set: function (value) {
  11640. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11641. },
  11642. enumerable: true,
  11643. configurable: true
  11644. });
  11645. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11646. get: function () {
  11647. return this._buttonLeftStick;
  11648. },
  11649. set: function (value) {
  11650. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11656. get: function () {
  11657. return this._buttonRightStick;
  11658. },
  11659. set: function (value) {
  11660. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11661. },
  11662. enumerable: true,
  11663. configurable: true
  11664. });
  11665. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11666. get: function () {
  11667. return this._dPadUp;
  11668. },
  11669. set: function (value) {
  11670. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11676. get: function () {
  11677. return this._dPadDown;
  11678. },
  11679. set: function (value) {
  11680. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11686. get: function () {
  11687. return this._dPadLeft;
  11688. },
  11689. set: function (value) {
  11690. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11696. get: function () {
  11697. return this._dPadRight;
  11698. },
  11699. set: function (value) {
  11700. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Xbox360Pad.prototype.update = function () {
  11706. _super.prototype.update.call(this);
  11707. this.buttonA = this.browserGamepad.buttons[0].value;
  11708. this.buttonB = this.browserGamepad.buttons[1].value;
  11709. this.buttonX = this.browserGamepad.buttons[2].value;
  11710. this.buttonY = this.browserGamepad.buttons[3].value;
  11711. this.buttonLB = this.browserGamepad.buttons[4].value;
  11712. this.buttonRB = this.browserGamepad.buttons[5].value;
  11713. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11714. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11715. this.buttonBack = this.browserGamepad.buttons[8].value;
  11716. this.buttonStart = this.browserGamepad.buttons[9].value;
  11717. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11718. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11719. this.dPadUp = this.browserGamepad.buttons[12].value;
  11720. this.dPadDown = this.browserGamepad.buttons[13].value;
  11721. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11722. this.dPadRight = this.browserGamepad.buttons[15].value;
  11723. };
  11724. return Xbox360Pad;
  11725. })(Gamepad);
  11726. BABYLON.Xbox360Pad = Xbox360Pad;
  11727. })(BABYLON || (BABYLON = {}));
  11728. //# sourceMappingURL=babylon.gamepads.js.map
  11729. var BABYLON;
  11730. (function (BABYLON) {
  11731. // We're mainly based on the logic defined into the FreeCamera code
  11732. var GamepadCamera = (function (_super) {
  11733. __extends(GamepadCamera, _super);
  11734. function GamepadCamera(name, position, scene) {
  11735. var _this = this;
  11736. _super.call(this, name, position, scene);
  11737. this.angularSensibility = 200;
  11738. this.moveSensibility = 75;
  11739. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11740. }
  11741. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11742. // Only the first gamepad can control the camera
  11743. if (gamepad.index === 0) {
  11744. this._gamepad = gamepad;
  11745. }
  11746. };
  11747. GamepadCamera.prototype._checkInputs = function () {
  11748. if (this._gamepad) {
  11749. var LSValues = this._gamepad.leftStick;
  11750. var normalizedLX = LSValues.x / this.moveSensibility;
  11751. var normalizedLY = LSValues.y / this.moveSensibility;
  11752. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11753. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11754. var RSValues = this._gamepad.rightStick;
  11755. var normalizedRX = RSValues.x / this.angularSensibility;
  11756. var normalizedRY = RSValues.y / this.angularSensibility;
  11757. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11758. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11759. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11760. var speed = this._computeLocalCameraSpeed() * 50.0;
  11761. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11762. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11763. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11764. }
  11765. _super.prototype._checkInputs.call(this);
  11766. };
  11767. GamepadCamera.prototype.dispose = function () {
  11768. this._gamepads.dispose();
  11769. _super.prototype.dispose.call(this);
  11770. };
  11771. return GamepadCamera;
  11772. })(BABYLON.FreeCamera);
  11773. BABYLON.GamepadCamera = GamepadCamera;
  11774. })(BABYLON || (BABYLON = {}));
  11775. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11776. var BABYLON;
  11777. (function (BABYLON) {
  11778. var RenderingManager = (function () {
  11779. function RenderingManager(scene) {
  11780. this._renderingGroups = new Array();
  11781. this._scene = scene;
  11782. }
  11783. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11784. if (this._scene._activeParticleSystems.length === 0) {
  11785. return;
  11786. }
  11787. // Particles
  11788. var beforeParticlesDate = BABYLON.Tools.Now;
  11789. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11790. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11791. if (particleSystem.renderingGroupId !== index) {
  11792. continue;
  11793. }
  11794. this._clearDepthBuffer();
  11795. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11796. this._scene._activeParticles += particleSystem.render();
  11797. }
  11798. }
  11799. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11800. };
  11801. RenderingManager.prototype._renderSprites = function (index) {
  11802. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11803. return;
  11804. }
  11805. // Sprites
  11806. var beforeSpritessDate = BABYLON.Tools.Now;
  11807. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11808. var spriteManager = this._scene.spriteManagers[id];
  11809. if (spriteManager.renderingGroupId === index) {
  11810. this._clearDepthBuffer();
  11811. spriteManager.render();
  11812. }
  11813. }
  11814. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11815. };
  11816. RenderingManager.prototype._clearDepthBuffer = function () {
  11817. if (this._depthBufferAlreadyCleaned) {
  11818. return;
  11819. }
  11820. this._scene.getEngine().clear(0, false, true);
  11821. this._depthBufferAlreadyCleaned = true;
  11822. };
  11823. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11824. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11825. this._depthBufferAlreadyCleaned = false;
  11826. var renderingGroup = this._renderingGroups[index];
  11827. var needToStepBack = false;
  11828. if (renderingGroup) {
  11829. this._clearDepthBuffer();
  11830. if (!renderingGroup.render(customRenderFunction)) {
  11831. this._renderingGroups.splice(index, 1);
  11832. needToStepBack = true;
  11833. }
  11834. }
  11835. if (renderSprites) {
  11836. this._renderSprites(index);
  11837. }
  11838. if (renderParticles) {
  11839. this._renderParticles(index, activeMeshes);
  11840. }
  11841. if (needToStepBack) {
  11842. index--;
  11843. }
  11844. }
  11845. };
  11846. RenderingManager.prototype.reset = function () {
  11847. for (var index in this._renderingGroups) {
  11848. var renderingGroup = this._renderingGroups[index];
  11849. renderingGroup.prepare();
  11850. }
  11851. };
  11852. RenderingManager.prototype.dispatch = function (subMesh) {
  11853. var mesh = subMesh.getMesh();
  11854. var renderingGroupId = mesh.renderingGroupId || 0;
  11855. if (!this._renderingGroups[renderingGroupId]) {
  11856. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11857. }
  11858. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11859. };
  11860. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11861. return RenderingManager;
  11862. })();
  11863. BABYLON.RenderingManager = RenderingManager;
  11864. })(BABYLON || (BABYLON = {}));
  11865. //# sourceMappingURL=babylon.renderingManager.js.map
  11866. var BABYLON;
  11867. (function (BABYLON) {
  11868. var RenderingGroup = (function () {
  11869. function RenderingGroup(index, scene) {
  11870. this.index = index;
  11871. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11872. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11873. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11874. this._scene = scene;
  11875. }
  11876. RenderingGroup.prototype.render = function (customRenderFunction) {
  11877. if (customRenderFunction) {
  11878. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11879. return true;
  11880. }
  11881. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11882. return false;
  11883. }
  11884. var engine = this._scene.getEngine();
  11885. // Opaque
  11886. var subIndex;
  11887. var submesh;
  11888. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11889. submesh = this._opaqueSubMeshes.data[subIndex];
  11890. submesh.render();
  11891. }
  11892. // Alpha test
  11893. engine.setAlphaTesting(true);
  11894. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11895. submesh = this._alphaTestSubMeshes.data[subIndex];
  11896. submesh.render();
  11897. }
  11898. engine.setAlphaTesting(false);
  11899. // Transparent
  11900. if (this._transparentSubMeshes.length) {
  11901. // Sorting
  11902. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11903. submesh = this._transparentSubMeshes.data[subIndex];
  11904. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11905. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11906. }
  11907. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11908. sortedArray.sort(function (a, b) {
  11909. // Alpha index first
  11910. if (a._alphaIndex > b._alphaIndex) {
  11911. return 1;
  11912. }
  11913. if (a._alphaIndex < b._alphaIndex) {
  11914. return -1;
  11915. }
  11916. // Then distance to camera
  11917. if (a._distanceToCamera < b._distanceToCamera) {
  11918. return 1;
  11919. }
  11920. if (a._distanceToCamera > b._distanceToCamera) {
  11921. return -1;
  11922. }
  11923. return 0;
  11924. });
  11925. // Rendering
  11926. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11927. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11928. submesh = sortedArray[subIndex];
  11929. submesh.render();
  11930. }
  11931. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11932. }
  11933. return true;
  11934. };
  11935. RenderingGroup.prototype.prepare = function () {
  11936. this._opaqueSubMeshes.reset();
  11937. this._transparentSubMeshes.reset();
  11938. this._alphaTestSubMeshes.reset();
  11939. };
  11940. RenderingGroup.prototype.dispatch = function (subMesh) {
  11941. var material = subMesh.getMaterial();
  11942. var mesh = subMesh.getMesh();
  11943. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11944. this._transparentSubMeshes.push(subMesh);
  11945. }
  11946. else if (material.needAlphaTesting()) {
  11947. this._alphaTestSubMeshes.push(subMesh);
  11948. }
  11949. else {
  11950. this._opaqueSubMeshes.push(subMesh); // Opaque
  11951. }
  11952. };
  11953. return RenderingGroup;
  11954. })();
  11955. BABYLON.RenderingGroup = RenderingGroup;
  11956. })(BABYLON || (BABYLON = {}));
  11957. //# sourceMappingURL=babylon.renderingGroup.js.map
  11958. var BABYLON;
  11959. (function (BABYLON) {
  11960. /**
  11961. * Represents a scene to be rendered by the engine.
  11962. * @see http://doc.babylonjs.com/page.php?p=21911
  11963. */
  11964. var Scene = (function () {
  11965. /**
  11966. * @constructor
  11967. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11968. */
  11969. function Scene(engine) {
  11970. // Members
  11971. this.autoClear = true;
  11972. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11973. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11974. this.forceWireframe = false;
  11975. this.forcePointsCloud = false;
  11976. this.forceShowBoundingBoxes = false;
  11977. this.animationsEnabled = true;
  11978. 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
  11979. // Fog
  11980. /**
  11981. * is fog enabled on this scene.
  11982. * @type {boolean}
  11983. */
  11984. this.fogEnabled = true;
  11985. this.fogMode = Scene.FOGMODE_NONE;
  11986. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11987. this.fogDensity = 0.1;
  11988. this.fogStart = 0;
  11989. this.fogEnd = 1000.0;
  11990. // Lights
  11991. /**
  11992. * is shadow enabled on this scene.
  11993. * @type {boolean}
  11994. */
  11995. this.shadowsEnabled = true;
  11996. /**
  11997. * is light enabled on this scene.
  11998. * @type {boolean}
  11999. */
  12000. this.lightsEnabled = true;
  12001. /**
  12002. * All of the lights added to this scene.
  12003. * @see BABYLON.Light
  12004. * @type {BABYLON.Light[]}
  12005. */
  12006. this.lights = new Array();
  12007. // Cameras
  12008. /**
  12009. * All of the cameras added to this scene.
  12010. * @see BABYLON.Camera
  12011. * @type {BABYLON.Camera[]}
  12012. */
  12013. this.cameras = new Array();
  12014. this.activeCameras = new Array();
  12015. // Meshes
  12016. /**
  12017. * All of the (abstract) meshes added to this scene.
  12018. * @see BABYLON.AbstractMesh
  12019. * @type {BABYLON.AbstractMesh[]}
  12020. */
  12021. this.meshes = new Array();
  12022. // Geometries
  12023. this._geometries = new Array();
  12024. this.materials = new Array();
  12025. this.multiMaterials = new Array();
  12026. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12027. // Textures
  12028. this.texturesEnabled = true;
  12029. this.textures = new Array();
  12030. // Particles
  12031. this.particlesEnabled = true;
  12032. this.particleSystems = new Array();
  12033. // Sprites
  12034. this.spritesEnabled = true;
  12035. this.spriteManagers = new Array();
  12036. // Layers
  12037. this.layers = new Array();
  12038. // Skeletons
  12039. this.skeletonsEnabled = true;
  12040. this.skeletons = new Array();
  12041. // Lens flares
  12042. this.lensFlaresEnabled = true;
  12043. this.lensFlareSystems = new Array();
  12044. // Collisions
  12045. this.collisionsEnabled = true;
  12046. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12047. // Postprocesses
  12048. this.postProcessesEnabled = true;
  12049. // Customs render targets
  12050. this.renderTargetsEnabled = true;
  12051. this.dumpNextRenderTargets = false;
  12052. this.customRenderTargets = new Array();
  12053. // Imported meshes
  12054. this.importedMeshesFiles = new Array();
  12055. this._actionManagers = new Array();
  12056. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12057. // Procedural textures
  12058. this.proceduralTexturesEnabled = true;
  12059. this._proceduralTextures = new Array();
  12060. this.soundTracks = new Array();
  12061. this._audioEnabled = true;
  12062. this._headphone = false;
  12063. this._totalVertices = 0;
  12064. this._activeIndices = 0;
  12065. this._activeParticles = 0;
  12066. this._lastFrameDuration = 0;
  12067. this._evaluateActiveMeshesDuration = 0;
  12068. this._renderTargetsDuration = 0;
  12069. this._particlesDuration = 0;
  12070. this._renderDuration = 0;
  12071. this._spritesDuration = 0;
  12072. this._animationRatio = 0;
  12073. this._renderId = 0;
  12074. this._executeWhenReadyTimeoutId = -1;
  12075. this._toBeDisposed = new BABYLON.SmartArray(256);
  12076. this._onReadyCallbacks = new Array();
  12077. this._pendingData = []; //ANY
  12078. this._onBeforeRenderCallbacks = new Array();
  12079. this._onAfterRenderCallbacks = new Array();
  12080. this._activeMeshes = new BABYLON.SmartArray(256);
  12081. this._processedMaterials = new BABYLON.SmartArray(256);
  12082. this._renderTargets = new BABYLON.SmartArray(256);
  12083. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12084. this._activeSkeletons = new BABYLON.SmartArray(32);
  12085. this._activeBones = 0;
  12086. this._activeAnimatables = new Array();
  12087. this._transformMatrix = BABYLON.Matrix.Zero();
  12088. this._uniqueIdCounter = 0;
  12089. this._engine = engine;
  12090. engine.scenes.push(this);
  12091. this._renderingManager = new BABYLON.RenderingManager(this);
  12092. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12093. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12094. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12095. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12096. this.attachControl();
  12097. this._debugLayer = new BABYLON.DebugLayer(this);
  12098. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12099. //simplification queue
  12100. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12101. //collision coordinator initialization. For now legacy per default.
  12102. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12103. }
  12104. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12105. get: function () {
  12106. return Scene._FOGMODE_NONE;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12112. get: function () {
  12113. return Scene._FOGMODE_EXP;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12119. get: function () {
  12120. return Scene._FOGMODE_EXP2;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12126. get: function () {
  12127. return Scene._FOGMODE_LINEAR;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Scene.prototype, "debugLayer", {
  12133. // Properties
  12134. get: function () {
  12135. return this._debugLayer;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12141. get: function () {
  12142. return this._workerCollisions;
  12143. },
  12144. set: function (enabled) {
  12145. enabled = (enabled && !!Worker);
  12146. this._workerCollisions = enabled;
  12147. if (this.collisionCoordinator) {
  12148. this.collisionCoordinator.destroy();
  12149. }
  12150. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12151. this.collisionCoordinator.init(this);
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12157. /**
  12158. * The mesh that is currently under the pointer.
  12159. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12160. */
  12161. get: function () {
  12162. return this._meshUnderPointer;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(Scene.prototype, "pointerX", {
  12168. /**
  12169. * Current on-screen X position of the pointer
  12170. * @return {number} X position of the pointer
  12171. */
  12172. get: function () {
  12173. return this._pointerX;
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(Scene.prototype, "pointerY", {
  12179. /**
  12180. * Current on-screen Y position of the pointer
  12181. * @return {number} Y position of the pointer
  12182. */
  12183. get: function () {
  12184. return this._pointerY;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Scene.prototype.getCachedMaterial = function () {
  12190. return this._cachedMaterial;
  12191. };
  12192. Scene.prototype.getBoundingBoxRenderer = function () {
  12193. return this._boundingBoxRenderer;
  12194. };
  12195. Scene.prototype.getOutlineRenderer = function () {
  12196. return this._outlineRenderer;
  12197. };
  12198. Scene.prototype.getEngine = function () {
  12199. return this._engine;
  12200. };
  12201. Scene.prototype.getTotalVertices = function () {
  12202. return this._totalVertices;
  12203. };
  12204. Scene.prototype.getActiveIndices = function () {
  12205. return this._activeIndices;
  12206. };
  12207. Scene.prototype.getActiveParticles = function () {
  12208. return this._activeParticles;
  12209. };
  12210. Scene.prototype.getActiveBones = function () {
  12211. return this._activeBones;
  12212. };
  12213. // Stats
  12214. Scene.prototype.getLastFrameDuration = function () {
  12215. return this._lastFrameDuration;
  12216. };
  12217. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12218. return this._evaluateActiveMeshesDuration;
  12219. };
  12220. Scene.prototype.getActiveMeshes = function () {
  12221. return this._activeMeshes;
  12222. };
  12223. Scene.prototype.getRenderTargetsDuration = function () {
  12224. return this._renderTargetsDuration;
  12225. };
  12226. Scene.prototype.getRenderDuration = function () {
  12227. return this._renderDuration;
  12228. };
  12229. Scene.prototype.getParticlesDuration = function () {
  12230. return this._particlesDuration;
  12231. };
  12232. Scene.prototype.getSpritesDuration = function () {
  12233. return this._spritesDuration;
  12234. };
  12235. Scene.prototype.getAnimationRatio = function () {
  12236. return this._animationRatio;
  12237. };
  12238. Scene.prototype.getRenderId = function () {
  12239. return this._renderId;
  12240. };
  12241. Scene.prototype.incrementRenderId = function () {
  12242. this._renderId++;
  12243. };
  12244. Scene.prototype._updatePointerPosition = function (evt) {
  12245. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12246. this._pointerX = evt.clientX - canvasRect.left;
  12247. this._pointerY = evt.clientY - canvasRect.top;
  12248. if (this.cameraToUseForPointers) {
  12249. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12250. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12251. }
  12252. };
  12253. // Pointers handling
  12254. Scene.prototype.attachControl = function () {
  12255. var _this = this;
  12256. this._onPointerMove = function (evt) {
  12257. var canvas = _this._engine.getRenderingCanvas();
  12258. _this._updatePointerPosition(evt);
  12259. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  12260. if (pickResult.hit) {
  12261. _this._meshUnderPointer = pickResult.pickedMesh;
  12262. _this.setPointerOverMesh(pickResult.pickedMesh);
  12263. canvas.style.cursor = "pointer";
  12264. }
  12265. else {
  12266. _this.setPointerOverMesh(null);
  12267. canvas.style.cursor = "";
  12268. _this._meshUnderPointer = null;
  12269. }
  12270. };
  12271. this._onPointerDown = function (evt) {
  12272. var predicate = null;
  12273. if (!_this.onPointerDown) {
  12274. predicate = function (mesh) {
  12275. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12276. };
  12277. }
  12278. _this._updatePointerPosition(evt);
  12279. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12280. if (pickResult.hit) {
  12281. if (pickResult.pickedMesh.actionManager) {
  12282. switch (evt.button) {
  12283. case 0:
  12284. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12285. break;
  12286. case 1:
  12287. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12288. break;
  12289. case 2:
  12290. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12291. break;
  12292. }
  12293. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12294. }
  12295. }
  12296. if (_this.onPointerDown) {
  12297. _this.onPointerDown(evt, pickResult);
  12298. }
  12299. };
  12300. this._onPointerUp = function (evt) {
  12301. var predicate = null;
  12302. if (!_this.onPointerUp) {
  12303. predicate = function (mesh) {
  12304. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12305. };
  12306. }
  12307. _this._updatePointerPosition(evt);
  12308. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12309. if (pickResult.hit) {
  12310. if (pickResult.pickedMesh.actionManager) {
  12311. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12312. }
  12313. }
  12314. if (_this.onPointerUp) {
  12315. _this.onPointerUp(evt, pickResult);
  12316. }
  12317. };
  12318. this._onKeyDown = function (evt) {
  12319. if (_this.actionManager) {
  12320. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12321. }
  12322. };
  12323. this._onKeyUp = function (evt) {
  12324. if (_this.actionManager) {
  12325. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12326. }
  12327. };
  12328. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12329. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12330. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12331. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12332. BABYLON.Tools.RegisterTopRootEvents([
  12333. { name: "keydown", handler: this._onKeyDown },
  12334. { name: "keyup", handler: this._onKeyUp }
  12335. ]);
  12336. };
  12337. Scene.prototype.detachControl = function () {
  12338. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12339. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12340. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12341. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12342. BABYLON.Tools.UnregisterTopRootEvents([
  12343. { name: "keydown", handler: this._onKeyDown },
  12344. { name: "keyup", handler: this._onKeyUp }
  12345. ]);
  12346. };
  12347. // Ready
  12348. Scene.prototype.isReady = function () {
  12349. if (this._pendingData.length > 0) {
  12350. return false;
  12351. }
  12352. for (var index = 0; index < this._geometries.length; index++) {
  12353. var geometry = this._geometries[index];
  12354. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12355. return false;
  12356. }
  12357. }
  12358. for (index = 0; index < this.meshes.length; index++) {
  12359. var mesh = this.meshes[index];
  12360. if (!mesh.isReady()) {
  12361. return false;
  12362. }
  12363. var mat = mesh.material;
  12364. if (mat) {
  12365. if (!mat.isReady(mesh)) {
  12366. return false;
  12367. }
  12368. }
  12369. }
  12370. return true;
  12371. };
  12372. Scene.prototype.resetCachedMaterial = function () {
  12373. this._cachedMaterial = null;
  12374. };
  12375. Scene.prototype.registerBeforeRender = function (func) {
  12376. this._onBeforeRenderCallbacks.push(func);
  12377. };
  12378. Scene.prototype.unregisterBeforeRender = function (func) {
  12379. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12380. if (index > -1) {
  12381. this._onBeforeRenderCallbacks.splice(index, 1);
  12382. }
  12383. };
  12384. Scene.prototype.registerAfterRender = function (func) {
  12385. this._onAfterRenderCallbacks.push(func);
  12386. };
  12387. Scene.prototype.unregisterAfterRender = function (func) {
  12388. var index = this._onAfterRenderCallbacks.indexOf(func);
  12389. if (index > -1) {
  12390. this._onAfterRenderCallbacks.splice(index, 1);
  12391. }
  12392. };
  12393. Scene.prototype._addPendingData = function (data) {
  12394. this._pendingData.push(data);
  12395. };
  12396. Scene.prototype._removePendingData = function (data) {
  12397. var index = this._pendingData.indexOf(data);
  12398. if (index !== -1) {
  12399. this._pendingData.splice(index, 1);
  12400. }
  12401. };
  12402. Scene.prototype.getWaitingItemsCount = function () {
  12403. return this._pendingData.length;
  12404. };
  12405. /**
  12406. * Registers a function to be executed when the scene is ready.
  12407. * @param {Function} func - the function to be executed.
  12408. */
  12409. Scene.prototype.executeWhenReady = function (func) {
  12410. var _this = this;
  12411. this._onReadyCallbacks.push(func);
  12412. if (this._executeWhenReadyTimeoutId !== -1) {
  12413. return;
  12414. }
  12415. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12416. _this._checkIsReady();
  12417. }, 150);
  12418. };
  12419. Scene.prototype._checkIsReady = function () {
  12420. var _this = this;
  12421. if (this.isReady()) {
  12422. this._onReadyCallbacks.forEach(function (func) {
  12423. func();
  12424. });
  12425. this._onReadyCallbacks = [];
  12426. this._executeWhenReadyTimeoutId = -1;
  12427. return;
  12428. }
  12429. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12430. _this._checkIsReady();
  12431. }, 150);
  12432. };
  12433. // Animations
  12434. /**
  12435. * Will start the animation sequence of a given target
  12436. * @param target - the target
  12437. * @param {number} from - from which frame should animation start
  12438. * @param {number} to - till which frame should animation run.
  12439. * @param {boolean} [loop] - should the animation loop
  12440. * @param {number} [speedRatio] - the speed in which to run the animation
  12441. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12442. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12443. * @return {BABYLON.Animatable} the animatable object created for this animation
  12444. * @see BABYLON.Animatable
  12445. * @see http://doc.babylonjs.com/page.php?p=22081
  12446. */
  12447. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12448. if (speedRatio === undefined) {
  12449. speedRatio = 1.0;
  12450. }
  12451. this.stopAnimation(target);
  12452. if (!animatable) {
  12453. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12454. }
  12455. // Local animations
  12456. if (target.animations) {
  12457. animatable.appendAnimations(target, target.animations);
  12458. }
  12459. // Children animations
  12460. if (target.getAnimatables) {
  12461. var animatables = target.getAnimatables();
  12462. for (var index = 0; index < animatables.length; index++) {
  12463. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12464. }
  12465. }
  12466. return animatable;
  12467. };
  12468. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12469. if (speedRatio === undefined) {
  12470. speedRatio = 1.0;
  12471. }
  12472. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12473. return animatable;
  12474. };
  12475. Scene.prototype.getAnimatableByTarget = function (target) {
  12476. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12477. if (this._activeAnimatables[index].target === target) {
  12478. return this._activeAnimatables[index];
  12479. }
  12480. }
  12481. return null;
  12482. };
  12483. /**
  12484. * Will stop the animation of the given target
  12485. * @param target - the target
  12486. * @see beginAnimation
  12487. */
  12488. Scene.prototype.stopAnimation = function (target) {
  12489. var animatable = this.getAnimatableByTarget(target);
  12490. if (animatable) {
  12491. animatable.stop();
  12492. }
  12493. };
  12494. Scene.prototype._animate = function () {
  12495. if (!this.animationsEnabled) {
  12496. return;
  12497. }
  12498. if (!this._animationStartDate) {
  12499. this._animationStartDate = BABYLON.Tools.Now;
  12500. }
  12501. // Getting time
  12502. var now = BABYLON.Tools.Now;
  12503. var delay = now - this._animationStartDate;
  12504. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12505. this._activeAnimatables[index]._animate(delay);
  12506. }
  12507. };
  12508. // Matrix
  12509. Scene.prototype.getViewMatrix = function () {
  12510. return this._viewMatrix;
  12511. };
  12512. Scene.prototype.getProjectionMatrix = function () {
  12513. return this._projectionMatrix;
  12514. };
  12515. Scene.prototype.getTransformMatrix = function () {
  12516. return this._transformMatrix;
  12517. };
  12518. Scene.prototype.setTransformMatrix = function (view, projection) {
  12519. this._viewMatrix = view;
  12520. this._projectionMatrix = projection;
  12521. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12522. };
  12523. // Methods
  12524. Scene.prototype.addMesh = function (newMesh) {
  12525. newMesh.uniqueId = this._uniqueIdCounter++;
  12526. var position = this.meshes.push(newMesh);
  12527. //notify the collision coordinator
  12528. this.collisionCoordinator.onMeshAdded(newMesh);
  12529. if (this.onNewMeshAdded) {
  12530. this.onNewMeshAdded(newMesh, position, this);
  12531. }
  12532. };
  12533. Scene.prototype.removeMesh = function (toRemove) {
  12534. var index = this.meshes.indexOf(toRemove);
  12535. if (index !== -1) {
  12536. // Remove from the scene if mesh found
  12537. this.meshes.splice(index, 1);
  12538. }
  12539. //notify the collision coordinator
  12540. this.collisionCoordinator.onMeshRemoved(toRemove);
  12541. if (this.onMeshRemoved) {
  12542. this.onMeshRemoved(toRemove);
  12543. }
  12544. return index;
  12545. };
  12546. Scene.prototype.removeLight = function (toRemove) {
  12547. var index = this.lights.indexOf(toRemove);
  12548. if (index !== -1) {
  12549. // Remove from the scene if mesh found
  12550. this.lights.splice(index, 1);
  12551. }
  12552. if (this.onLightRemoved) {
  12553. this.onLightRemoved(toRemove);
  12554. }
  12555. return index;
  12556. };
  12557. Scene.prototype.removeCamera = function (toRemove) {
  12558. var index = this.cameras.indexOf(toRemove);
  12559. if (index !== -1) {
  12560. // Remove from the scene if mesh found
  12561. this.cameras.splice(index, 1);
  12562. }
  12563. // Remove from activeCameras
  12564. var index2 = this.activeCameras.indexOf(toRemove);
  12565. if (index2 !== -1) {
  12566. // Remove from the scene if mesh found
  12567. this.activeCameras.splice(index2, 1);
  12568. }
  12569. // Reset the activeCamera
  12570. if (this.activeCamera === toRemove) {
  12571. if (this.cameras.length > 0) {
  12572. this.activeCamera = this.cameras[0];
  12573. }
  12574. else {
  12575. this.activeCamera = null;
  12576. }
  12577. }
  12578. if (this.onCameraRemoved) {
  12579. this.onCameraRemoved(toRemove);
  12580. }
  12581. return index;
  12582. };
  12583. Scene.prototype.addLight = function (newLight) {
  12584. newLight.uniqueId = this._uniqueIdCounter++;
  12585. var position = this.lights.push(newLight);
  12586. if (this.onNewLightAdded) {
  12587. this.onNewLightAdded(newLight, position, this);
  12588. }
  12589. };
  12590. Scene.prototype.addCamera = function (newCamera) {
  12591. newCamera.uniqueId = this._uniqueIdCounter++;
  12592. var position = this.cameras.push(newCamera);
  12593. if (this.onNewCameraAdded) {
  12594. this.onNewCameraAdded(newCamera, position, this);
  12595. }
  12596. };
  12597. /**
  12598. * sets the active camera of the scene using its ID
  12599. * @param {string} id - the camera's ID
  12600. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12601. * @see activeCamera
  12602. */
  12603. Scene.prototype.setActiveCameraByID = function (id) {
  12604. var camera = this.getCameraByID(id);
  12605. if (camera) {
  12606. this.activeCamera = camera;
  12607. return camera;
  12608. }
  12609. return null;
  12610. };
  12611. /**
  12612. * sets the active camera of the scene using its name
  12613. * @param {string} name - the camera's name
  12614. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12615. * @see activeCamera
  12616. */
  12617. Scene.prototype.setActiveCameraByName = function (name) {
  12618. var camera = this.getCameraByName(name);
  12619. if (camera) {
  12620. this.activeCamera = camera;
  12621. return camera;
  12622. }
  12623. return null;
  12624. };
  12625. /**
  12626. * get a material using its id
  12627. * @param {string} the material's ID
  12628. * @return {BABYLON.Material|null} the material or null if none found.
  12629. */
  12630. Scene.prototype.getMaterialByID = function (id) {
  12631. for (var index = 0; index < this.materials.length; index++) {
  12632. if (this.materials[index].id === id) {
  12633. return this.materials[index];
  12634. }
  12635. }
  12636. return null;
  12637. };
  12638. /**
  12639. * get a material using its name
  12640. * @param {string} the material's name
  12641. * @return {BABYLON.Material|null} the material or null if none found.
  12642. */
  12643. Scene.prototype.getMaterialByName = function (name) {
  12644. for (var index = 0; index < this.materials.length; index++) {
  12645. if (this.materials[index].name === name) {
  12646. return this.materials[index];
  12647. }
  12648. }
  12649. return null;
  12650. };
  12651. Scene.prototype.getCameraByID = function (id) {
  12652. for (var index = 0; index < this.cameras.length; index++) {
  12653. if (this.cameras[index].id === id) {
  12654. return this.cameras[index];
  12655. }
  12656. }
  12657. return null;
  12658. };
  12659. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12660. for (var index = 0; index < this.cameras.length; index++) {
  12661. if (this.cameras[index].uniqueId === uniqueId) {
  12662. return this.cameras[index];
  12663. }
  12664. }
  12665. return null;
  12666. };
  12667. /**
  12668. * get a camera using its name
  12669. * @param {string} the camera's name
  12670. * @return {BABYLON.Camera|null} the camera or null if none found.
  12671. */
  12672. Scene.prototype.getCameraByName = function (name) {
  12673. for (var index = 0; index < this.cameras.length; index++) {
  12674. if (this.cameras[index].name === name) {
  12675. return this.cameras[index];
  12676. }
  12677. }
  12678. return null;
  12679. };
  12680. /**
  12681. * get a light node using its name
  12682. * @param {string} the light's name
  12683. * @return {BABYLON.Light|null} the light or null if none found.
  12684. */
  12685. Scene.prototype.getLightByName = function (name) {
  12686. for (var index = 0; index < this.lights.length; index++) {
  12687. if (this.lights[index].name === name) {
  12688. return this.lights[index];
  12689. }
  12690. }
  12691. return null;
  12692. };
  12693. /**
  12694. * get a light node using its ID
  12695. * @param {string} the light's id
  12696. * @return {BABYLON.Light|null} the light or null if none found.
  12697. */
  12698. Scene.prototype.getLightByID = function (id) {
  12699. for (var index = 0; index < this.lights.length; index++) {
  12700. if (this.lights[index].id === id) {
  12701. return this.lights[index];
  12702. }
  12703. }
  12704. return null;
  12705. };
  12706. /**
  12707. * get a light node using its scene-generated unique ID
  12708. * @param {number} the light's unique id
  12709. * @return {BABYLON.Light|null} the light or null if none found.
  12710. */
  12711. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12712. for (var index = 0; index < this.lights.length; index++) {
  12713. if (this.lights[index].uniqueId === uniqueId) {
  12714. return this.lights[index];
  12715. }
  12716. }
  12717. return null;
  12718. };
  12719. /**
  12720. * get a geometry using its ID
  12721. * @param {string} the geometry's id
  12722. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12723. */
  12724. Scene.prototype.getGeometryByID = function (id) {
  12725. for (var index = 0; index < this._geometries.length; index++) {
  12726. if (this._geometries[index].id === id) {
  12727. return this._geometries[index];
  12728. }
  12729. }
  12730. return null;
  12731. };
  12732. /**
  12733. * add a new geometry to this scene.
  12734. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12735. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12736. * @return {boolean} was the geometry added or not
  12737. */
  12738. Scene.prototype.pushGeometry = function (geometry, force) {
  12739. if (!force && this.getGeometryByID(geometry.id)) {
  12740. return false;
  12741. }
  12742. this._geometries.push(geometry);
  12743. //notify the collision coordinator
  12744. this.collisionCoordinator.onGeometryAdded(geometry);
  12745. if (this.onGeometryAdded) {
  12746. this.onGeometryAdded(geometry);
  12747. }
  12748. return true;
  12749. };
  12750. /**
  12751. * Removes an existing geometry
  12752. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12753. * @return {boolean} was the geometry removed or not
  12754. */
  12755. Scene.prototype.removeGeometry = function (geometry) {
  12756. var index = this._geometries.indexOf(geometry);
  12757. if (index > -1) {
  12758. this._geometries.splice(index, 1);
  12759. //notify the collision coordinator
  12760. this.collisionCoordinator.onGeometryDeleted(geometry);
  12761. if (this.onGeometryRemoved) {
  12762. this.onGeometryRemoved(geometry);
  12763. }
  12764. return true;
  12765. }
  12766. return false;
  12767. };
  12768. Scene.prototype.getGeometries = function () {
  12769. return this._geometries;
  12770. };
  12771. /**
  12772. * Get the first added mesh found of a given ID
  12773. * @param {string} id - the id to search for
  12774. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12775. */
  12776. Scene.prototype.getMeshByID = function (id) {
  12777. for (var index = 0; index < this.meshes.length; index++) {
  12778. if (this.meshes[index].id === id) {
  12779. return this.meshes[index];
  12780. }
  12781. }
  12782. return null;
  12783. };
  12784. /**
  12785. * Get a mesh with its auto-generated unique id
  12786. * @param {number} uniqueId - the unique id to search for
  12787. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12788. */
  12789. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12790. for (var index = 0; index < this.meshes.length; index++) {
  12791. if (this.meshes[index].uniqueId === uniqueId) {
  12792. return this.meshes[index];
  12793. }
  12794. }
  12795. return null;
  12796. };
  12797. /**
  12798. * Get a the last added mesh found of a given ID
  12799. * @param {string} id - the id to search for
  12800. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12801. */
  12802. Scene.prototype.getLastMeshByID = function (id) {
  12803. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12804. if (this.meshes[index].id === id) {
  12805. return this.meshes[index];
  12806. }
  12807. }
  12808. return null;
  12809. };
  12810. /**
  12811. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12812. * @param {string} id - the id to search for
  12813. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12814. */
  12815. Scene.prototype.getLastEntryByID = function (id) {
  12816. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12817. if (this.meshes[index].id === id) {
  12818. return this.meshes[index];
  12819. }
  12820. }
  12821. for (index = this.cameras.length - 1; index >= 0; index--) {
  12822. if (this.cameras[index].id === id) {
  12823. return this.cameras[index];
  12824. }
  12825. }
  12826. for (index = this.lights.length - 1; index >= 0; index--) {
  12827. if (this.lights[index].id === id) {
  12828. return this.lights[index];
  12829. }
  12830. }
  12831. return null;
  12832. };
  12833. Scene.prototype.getNodeByName = function (name) {
  12834. var mesh = this.getMeshByName(name);
  12835. if (mesh) {
  12836. return mesh;
  12837. }
  12838. var light = this.getLightByName(name);
  12839. if (light) {
  12840. return light;
  12841. }
  12842. return this.getCameraByName(name);
  12843. };
  12844. Scene.prototype.getMeshByName = function (name) {
  12845. for (var index = 0; index < this.meshes.length; index++) {
  12846. if (this.meshes[index].name === name) {
  12847. return this.meshes[index];
  12848. }
  12849. }
  12850. return null;
  12851. };
  12852. Scene.prototype.getSoundByName = function (name) {
  12853. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12854. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12855. return this.mainSoundTrack.soundCollection[index];
  12856. }
  12857. }
  12858. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12859. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12860. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12861. return this.soundTracks[sdIndex].soundCollection[index];
  12862. }
  12863. }
  12864. }
  12865. return null;
  12866. };
  12867. Scene.prototype.getLastSkeletonByID = function (id) {
  12868. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12869. if (this.skeletons[index].id === id) {
  12870. return this.skeletons[index];
  12871. }
  12872. }
  12873. return null;
  12874. };
  12875. Scene.prototype.getSkeletonById = function (id) {
  12876. for (var index = 0; index < this.skeletons.length; index++) {
  12877. if (this.skeletons[index].id === id) {
  12878. return this.skeletons[index];
  12879. }
  12880. }
  12881. return null;
  12882. };
  12883. Scene.prototype.getSkeletonByName = function (name) {
  12884. for (var index = 0; index < this.skeletons.length; index++) {
  12885. if (this.skeletons[index].name === name) {
  12886. return this.skeletons[index];
  12887. }
  12888. }
  12889. return null;
  12890. };
  12891. Scene.prototype.isActiveMesh = function (mesh) {
  12892. return (this._activeMeshes.indexOf(mesh) !== -1);
  12893. };
  12894. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12895. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12896. var material = subMesh.getMaterial();
  12897. if (mesh.showSubMeshesBoundingBox) {
  12898. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12899. }
  12900. if (material) {
  12901. // Render targets
  12902. if (material.getRenderTargetTextures) {
  12903. if (this._processedMaterials.indexOf(material) === -1) {
  12904. this._processedMaterials.push(material);
  12905. this._renderTargets.concat(material.getRenderTargetTextures());
  12906. }
  12907. }
  12908. // Dispatch
  12909. this._activeIndices += subMesh.indexCount;
  12910. this._renderingManager.dispatch(subMesh);
  12911. }
  12912. }
  12913. };
  12914. Scene.prototype._evaluateActiveMeshes = function () {
  12915. this.activeCamera._activeMeshes.reset();
  12916. this._activeMeshes.reset();
  12917. this._renderingManager.reset();
  12918. this._processedMaterials.reset();
  12919. this._activeParticleSystems.reset();
  12920. this._activeSkeletons.reset();
  12921. this._boundingBoxRenderer.reset();
  12922. if (!this._frustumPlanes) {
  12923. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12924. }
  12925. else {
  12926. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12927. }
  12928. // Meshes
  12929. var meshes;
  12930. var len;
  12931. if (this._selectionOctree) {
  12932. var selection = this._selectionOctree.select(this._frustumPlanes);
  12933. meshes = selection.data;
  12934. len = selection.length;
  12935. }
  12936. else {
  12937. len = this.meshes.length;
  12938. meshes = this.meshes;
  12939. }
  12940. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12941. var mesh = meshes[meshIndex];
  12942. if (mesh.isBlocked) {
  12943. continue;
  12944. }
  12945. this._totalVertices += mesh.getTotalVertices();
  12946. if (!mesh.isReady() || !mesh.isEnabled()) {
  12947. continue;
  12948. }
  12949. mesh.computeWorldMatrix();
  12950. // Intersections
  12951. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12952. this._meshesForIntersections.pushNoDuplicate(mesh);
  12953. }
  12954. // Switch to current LOD
  12955. var meshLOD = mesh.getLOD(this.activeCamera);
  12956. if (!meshLOD) {
  12957. continue;
  12958. }
  12959. mesh._preActivate();
  12960. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12961. this._activeMeshes.push(mesh);
  12962. this.activeCamera._activeMeshes.push(mesh);
  12963. mesh._activate(this._renderId);
  12964. this._activeMesh(meshLOD);
  12965. }
  12966. }
  12967. // Particle systems
  12968. var beforeParticlesDate = BABYLON.Tools.Now;
  12969. if (this.particlesEnabled) {
  12970. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12971. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12972. var particleSystem = this.particleSystems[particleIndex];
  12973. if (!particleSystem.isStarted()) {
  12974. continue;
  12975. }
  12976. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12977. this._activeParticleSystems.push(particleSystem);
  12978. particleSystem.animate();
  12979. }
  12980. }
  12981. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12982. }
  12983. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12984. };
  12985. Scene.prototype._activeMesh = function (mesh) {
  12986. if (mesh.skeleton && this.skeletonsEnabled) {
  12987. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12988. }
  12989. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12990. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12991. }
  12992. if (mesh && mesh.subMeshes) {
  12993. // Submeshes Octrees
  12994. var len;
  12995. var subMeshes;
  12996. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12997. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12998. len = intersections.length;
  12999. subMeshes = intersections.data;
  13000. }
  13001. else {
  13002. subMeshes = mesh.subMeshes;
  13003. len = subMeshes.length;
  13004. }
  13005. for (var subIndex = 0; subIndex < len; subIndex++) {
  13006. var subMesh = subMeshes[subIndex];
  13007. this._evaluateSubMesh(subMesh, mesh);
  13008. }
  13009. }
  13010. };
  13011. Scene.prototype.updateTransformMatrix = function (force) {
  13012. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13013. };
  13014. Scene.prototype._renderForCamera = function (camera) {
  13015. var engine = this._engine;
  13016. this.activeCamera = camera;
  13017. if (!this.activeCamera)
  13018. throw new Error("Active camera not set");
  13019. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13020. // Viewport
  13021. engine.setViewport(this.activeCamera.viewport);
  13022. // Camera
  13023. this.resetCachedMaterial();
  13024. this._renderId++;
  13025. this.updateTransformMatrix();
  13026. if (this.beforeCameraRender) {
  13027. this.beforeCameraRender(this.activeCamera);
  13028. }
  13029. // Meshes
  13030. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13031. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13032. this._evaluateActiveMeshes();
  13033. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13034. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13035. // Skeletons
  13036. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13037. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13038. skeleton.prepare();
  13039. }
  13040. // Render targets
  13041. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13042. if (this.renderTargetsEnabled) {
  13043. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13044. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13045. var renderTarget = this._renderTargets.data[renderIndex];
  13046. if (renderTarget._shouldRender()) {
  13047. this._renderId++;
  13048. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13049. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13050. }
  13051. }
  13052. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13053. this._renderId++;
  13054. }
  13055. if (this._renderTargets.length > 0) {
  13056. engine.restoreDefaultFramebuffer();
  13057. }
  13058. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13059. // Prepare Frame
  13060. this.postProcessManager._prepareFrame();
  13061. var beforeRenderDate = BABYLON.Tools.Now;
  13062. // Backgrounds
  13063. if (this.layers.length) {
  13064. engine.setDepthBuffer(false);
  13065. var layerIndex;
  13066. var layer;
  13067. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13068. layer = this.layers[layerIndex];
  13069. if (layer.isBackground) {
  13070. layer.render();
  13071. }
  13072. }
  13073. engine.setDepthBuffer(true);
  13074. }
  13075. // Render
  13076. BABYLON.Tools.StartPerformanceCounter("Main render");
  13077. this._renderingManager.render(null, null, true, true);
  13078. BABYLON.Tools.EndPerformanceCounter("Main render");
  13079. // Bounding boxes
  13080. this._boundingBoxRenderer.render();
  13081. // Lens flares
  13082. if (this.lensFlaresEnabled) {
  13083. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13084. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13085. this.lensFlareSystems[lensFlareSystemIndex].render();
  13086. }
  13087. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13088. }
  13089. // Foregrounds
  13090. if (this.layers.length) {
  13091. engine.setDepthBuffer(false);
  13092. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13093. layer = this.layers[layerIndex];
  13094. if (!layer.isBackground) {
  13095. layer.render();
  13096. }
  13097. }
  13098. engine.setDepthBuffer(true);
  13099. }
  13100. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13101. // Finalize frame
  13102. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13103. // Update camera
  13104. this.activeCamera._updateFromScene();
  13105. // Reset some special arrays
  13106. this._renderTargets.reset();
  13107. if (this.afterCameraRender) {
  13108. this.afterCameraRender(this.activeCamera);
  13109. }
  13110. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13111. };
  13112. Scene.prototype._processSubCameras = function (camera) {
  13113. if (camera.subCameras.length === 0) {
  13114. this._renderForCamera(camera);
  13115. return;
  13116. }
  13117. // Sub-cameras
  13118. for (var index = 0; index < camera.subCameras.length; index++) {
  13119. this._renderForCamera(camera.subCameras[index]);
  13120. }
  13121. this.activeCamera = camera;
  13122. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13123. // Update camera
  13124. this.activeCamera._updateFromScene();
  13125. };
  13126. Scene.prototype._checkIntersections = function () {
  13127. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13128. var sourceMesh = this._meshesForIntersections.data[index];
  13129. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13130. var action = sourceMesh.actionManager.actions[actionIndex];
  13131. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13132. var parameters = action.getTriggerParameter();
  13133. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13134. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13135. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13136. if (areIntersecting && currentIntersectionInProgress === -1) {
  13137. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13138. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13139. sourceMesh._intersectionsInProgress.push(otherMesh);
  13140. }
  13141. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13142. sourceMesh._intersectionsInProgress.push(otherMesh);
  13143. }
  13144. }
  13145. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13146. //They intersected, and now they don't.
  13147. //is this trigger an exit trigger? execute an event.
  13148. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13149. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13150. }
  13151. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13152. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13153. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13154. }
  13155. }
  13156. }
  13157. }
  13158. }
  13159. };
  13160. Scene.prototype.render = function () {
  13161. var startDate = BABYLON.Tools.Now;
  13162. this._particlesDuration = 0;
  13163. this._spritesDuration = 0;
  13164. this._activeParticles = 0;
  13165. this._renderDuration = 0;
  13166. this._renderTargetsDuration = 0;
  13167. this._evaluateActiveMeshesDuration = 0;
  13168. this._totalVertices = 0;
  13169. this._activeIndices = 0;
  13170. this._activeBones = 0;
  13171. this.getEngine().resetDrawCalls();
  13172. this._meshesForIntersections.reset();
  13173. this.resetCachedMaterial();
  13174. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13175. // Actions
  13176. if (this.actionManager) {
  13177. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13178. }
  13179. //Simplification Queue
  13180. if (!this.simplificationQueue.running) {
  13181. this.simplificationQueue.executeNext();
  13182. }
  13183. // Before render
  13184. if (this.beforeRender) {
  13185. this.beforeRender();
  13186. }
  13187. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13188. this._onBeforeRenderCallbacks[callbackIndex]();
  13189. }
  13190. // Animations
  13191. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13192. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13193. this._animate();
  13194. // Physics
  13195. if (this._physicsEngine) {
  13196. BABYLON.Tools.StartPerformanceCounter("Physics");
  13197. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13198. BABYLON.Tools.EndPerformanceCounter("Physics");
  13199. }
  13200. // Customs render targets
  13201. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13202. var engine = this.getEngine();
  13203. var currentActiveCamera = this.activeCamera;
  13204. if (this.renderTargetsEnabled) {
  13205. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13206. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13207. var renderTarget = this.customRenderTargets[customIndex];
  13208. if (renderTarget._shouldRender()) {
  13209. this._renderId++;
  13210. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13211. if (!this.activeCamera)
  13212. throw new Error("Active camera not set");
  13213. // Viewport
  13214. engine.setViewport(this.activeCamera.viewport);
  13215. // Camera
  13216. this.updateTransformMatrix();
  13217. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13218. }
  13219. }
  13220. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13221. this._renderId++;
  13222. }
  13223. if (this.customRenderTargets.length > 0) {
  13224. engine.restoreDefaultFramebuffer();
  13225. }
  13226. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13227. this.activeCamera = currentActiveCamera;
  13228. // Procedural textures
  13229. if (this.proceduralTexturesEnabled) {
  13230. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13231. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13232. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13233. if (proceduralTexture._shouldRender()) {
  13234. proceduralTexture.render();
  13235. }
  13236. }
  13237. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13238. }
  13239. // Clear
  13240. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13241. // Shadows
  13242. if (this.shadowsEnabled) {
  13243. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13244. var light = this.lights[lightIndex];
  13245. var shadowGenerator = light.getShadowGenerator();
  13246. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13247. this._renderTargets.push(shadowGenerator.getShadowMap());
  13248. }
  13249. }
  13250. }
  13251. // Depth renderer
  13252. if (this._depthRenderer) {
  13253. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13254. }
  13255. // RenderPipeline
  13256. this.postProcessRenderPipelineManager.update();
  13257. // Multi-cameras?
  13258. if (this.activeCameras.length > 0) {
  13259. var currentRenderId = this._renderId;
  13260. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13261. this._renderId = currentRenderId;
  13262. this._processSubCameras(this.activeCameras[cameraIndex]);
  13263. }
  13264. }
  13265. else {
  13266. if (!this.activeCamera) {
  13267. throw new Error("No camera defined");
  13268. }
  13269. this._processSubCameras(this.activeCamera);
  13270. }
  13271. // Intersection checks
  13272. this._checkIntersections();
  13273. // Update the audio listener attached to the camera
  13274. this._updateAudioParameters();
  13275. // After render
  13276. if (this.afterRender) {
  13277. this.afterRender();
  13278. }
  13279. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13280. this._onAfterRenderCallbacks[callbackIndex]();
  13281. }
  13282. // Cleaning
  13283. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13284. this._toBeDisposed.data[index].dispose();
  13285. this._toBeDisposed[index] = null;
  13286. }
  13287. this._toBeDisposed.reset();
  13288. if (this.dumpNextRenderTargets) {
  13289. this.dumpNextRenderTargets = false;
  13290. }
  13291. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13292. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13293. };
  13294. Scene.prototype._updateAudioParameters = function () {
  13295. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13296. return;
  13297. }
  13298. var listeningCamera;
  13299. var audioEngine = BABYLON.Engine.audioEngine;
  13300. if (this.activeCameras.length > 0) {
  13301. listeningCamera = this.activeCameras[0];
  13302. }
  13303. else {
  13304. listeningCamera = this.activeCamera;
  13305. }
  13306. if (listeningCamera && audioEngine.canUseWebAudio) {
  13307. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13308. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13309. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13310. cameraDirection.normalize();
  13311. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13312. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13313. var sound = this.mainSoundTrack.soundCollection[i];
  13314. if (sound.useCustomAttenuation) {
  13315. sound.updateDistanceFromListener();
  13316. }
  13317. }
  13318. for (i = 0; i < this.soundTracks.length; i++) {
  13319. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13320. sound = this.soundTracks[i].soundCollection[j];
  13321. if (sound.useCustomAttenuation) {
  13322. sound.updateDistanceFromListener();
  13323. }
  13324. }
  13325. }
  13326. }
  13327. };
  13328. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13329. // Audio
  13330. get: function () {
  13331. return this._audioEnabled;
  13332. },
  13333. set: function (value) {
  13334. this._audioEnabled = value;
  13335. if (this._audioEnabled) {
  13336. this._enableAudio();
  13337. }
  13338. else {
  13339. this._disableAudio();
  13340. }
  13341. },
  13342. enumerable: true,
  13343. configurable: true
  13344. });
  13345. Scene.prototype._disableAudio = function () {
  13346. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13347. this.mainSoundTrack.soundCollection[i].pause();
  13348. }
  13349. for (i = 0; i < this.soundTracks.length; i++) {
  13350. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13351. this.soundTracks[i].soundCollection[j].pause();
  13352. }
  13353. }
  13354. };
  13355. Scene.prototype._enableAudio = function () {
  13356. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13357. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13358. this.mainSoundTrack.soundCollection[i].play();
  13359. }
  13360. }
  13361. for (i = 0; i < this.soundTracks.length; i++) {
  13362. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13363. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13364. this.soundTracks[i].soundCollection[j].play();
  13365. }
  13366. }
  13367. }
  13368. };
  13369. Object.defineProperty(Scene.prototype, "headphone", {
  13370. get: function () {
  13371. return this._headphone;
  13372. },
  13373. set: function (value) {
  13374. this._headphone = value;
  13375. if (this._headphone) {
  13376. this._switchAudioModeForHeadphones();
  13377. }
  13378. else {
  13379. this._switchAudioModeForNormalSpeakers();
  13380. }
  13381. },
  13382. enumerable: true,
  13383. configurable: true
  13384. });
  13385. Scene.prototype._switchAudioModeForHeadphones = function () {
  13386. this.mainSoundTrack.switchPanningModelToHRTF();
  13387. for (var i = 0; i < this.soundTracks.length; i++) {
  13388. this.soundTracks[i].switchPanningModelToHRTF();
  13389. }
  13390. };
  13391. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13392. this.mainSoundTrack.switchPanningModelToEqualPower();
  13393. for (var i = 0; i < this.soundTracks.length; i++) {
  13394. this.soundTracks[i].switchPanningModelToEqualPower();
  13395. }
  13396. };
  13397. Scene.prototype.enableDepthRenderer = function () {
  13398. if (this._depthRenderer) {
  13399. return this._depthRenderer;
  13400. }
  13401. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13402. return this._depthRenderer;
  13403. };
  13404. Scene.prototype.disableDepthRenderer = function () {
  13405. if (!this._depthRenderer) {
  13406. return;
  13407. }
  13408. this._depthRenderer.dispose();
  13409. this._depthRenderer = null;
  13410. };
  13411. Scene.prototype.dispose = function () {
  13412. this.beforeRender = null;
  13413. this.afterRender = null;
  13414. this.skeletons = [];
  13415. this._boundingBoxRenderer.dispose();
  13416. if (this._depthRenderer) {
  13417. this._depthRenderer.dispose();
  13418. }
  13419. // Debug layer
  13420. this.debugLayer.hide();
  13421. // Events
  13422. if (this.onDispose) {
  13423. this.onDispose();
  13424. }
  13425. this._onBeforeRenderCallbacks = [];
  13426. this._onAfterRenderCallbacks = [];
  13427. this.detachControl();
  13428. // Release sounds & sounds tracks
  13429. this.disposeSounds();
  13430. // Detach cameras
  13431. var canvas = this._engine.getRenderingCanvas();
  13432. var index;
  13433. for (index = 0; index < this.cameras.length; index++) {
  13434. this.cameras[index].detachControl(canvas);
  13435. }
  13436. // Release lights
  13437. while (this.lights.length) {
  13438. this.lights[0].dispose();
  13439. }
  13440. // Release meshes
  13441. while (this.meshes.length) {
  13442. this.meshes[0].dispose(true);
  13443. }
  13444. // Release cameras
  13445. while (this.cameras.length) {
  13446. this.cameras[0].dispose();
  13447. }
  13448. // Release materials
  13449. while (this.materials.length) {
  13450. this.materials[0].dispose();
  13451. }
  13452. // Release particles
  13453. while (this.particleSystems.length) {
  13454. this.particleSystems[0].dispose();
  13455. }
  13456. // Release sprites
  13457. while (this.spriteManagers.length) {
  13458. this.spriteManagers[0].dispose();
  13459. }
  13460. // Release layers
  13461. while (this.layers.length) {
  13462. this.layers[0].dispose();
  13463. }
  13464. // Release textures
  13465. while (this.textures.length) {
  13466. this.textures[0].dispose();
  13467. }
  13468. // Post-processes
  13469. this.postProcessManager.dispose();
  13470. // Physics
  13471. if (this._physicsEngine) {
  13472. this.disablePhysicsEngine();
  13473. }
  13474. // Remove from engine
  13475. index = this._engine.scenes.indexOf(this);
  13476. if (index > -1) {
  13477. this._engine.scenes.splice(index, 1);
  13478. }
  13479. this._engine.wipeCaches();
  13480. };
  13481. // Release sounds & sounds tracks
  13482. Scene.prototype.disposeSounds = function () {
  13483. this.mainSoundTrack.dispose();
  13484. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13485. this.soundTracks[scIndex].dispose();
  13486. }
  13487. };
  13488. // Octrees
  13489. Scene.prototype.getWorldExtends = function () {
  13490. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13491. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13492. for (var index = 0; index < this.meshes.length; index++) {
  13493. var mesh = this.meshes[index];
  13494. mesh.computeWorldMatrix(true);
  13495. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13496. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13497. BABYLON.Tools.CheckExtends(minBox, min, max);
  13498. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13499. }
  13500. return {
  13501. min: min,
  13502. max: max
  13503. };
  13504. };
  13505. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13506. if (maxCapacity === void 0) { maxCapacity = 64; }
  13507. if (maxDepth === void 0) { maxDepth = 2; }
  13508. if (!this._selectionOctree) {
  13509. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13510. }
  13511. var worldExtends = this.getWorldExtends();
  13512. // Update octree
  13513. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13514. return this._selectionOctree;
  13515. };
  13516. // Picking
  13517. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13518. var engine = this._engine;
  13519. if (!camera) {
  13520. if (!this.activeCamera)
  13521. throw new Error("Active camera not set");
  13522. camera = this.activeCamera;
  13523. }
  13524. var cameraViewport = camera.viewport;
  13525. var viewport = cameraViewport.toGlobal(engine);
  13526. // Moving coordinates to local viewport world
  13527. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13528. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13529. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13530. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13531. };
  13532. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13533. var pickingInfo = null;
  13534. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13535. var mesh = this.meshes[meshIndex];
  13536. if (predicate) {
  13537. if (!predicate(mesh)) {
  13538. continue;
  13539. }
  13540. }
  13541. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13542. continue;
  13543. }
  13544. var world = mesh.getWorldMatrix();
  13545. var ray = rayFunction(world);
  13546. var result = mesh.intersects(ray, fastCheck);
  13547. if (!result || !result.hit)
  13548. continue;
  13549. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13550. continue;
  13551. pickingInfo = result;
  13552. if (fastCheck) {
  13553. break;
  13554. }
  13555. }
  13556. return pickingInfo || new BABYLON.PickingInfo();
  13557. };
  13558. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13559. var _this = this;
  13560. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13561. /// <param name="x">X position on screen</param>
  13562. /// <param name="y">Y position on screen</param>
  13563. /// <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>
  13564. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13565. /// <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>
  13566. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13567. };
  13568. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13569. var _this = this;
  13570. return this._internalPick(function (world) {
  13571. if (!_this._pickWithRayInverseMatrix) {
  13572. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13573. }
  13574. world.invertToRef(_this._pickWithRayInverseMatrix);
  13575. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13576. }, predicate, fastCheck);
  13577. };
  13578. Scene.prototype.setPointerOverMesh = function (mesh) {
  13579. if (this._pointerOverMesh === mesh) {
  13580. return;
  13581. }
  13582. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13583. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13584. }
  13585. this._pointerOverMesh = mesh;
  13586. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13587. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13588. }
  13589. };
  13590. Scene.prototype.getPointerOverMesh = function () {
  13591. return this._pointerOverMesh;
  13592. };
  13593. // Physics
  13594. Scene.prototype.getPhysicsEngine = function () {
  13595. return this._physicsEngine;
  13596. };
  13597. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13598. if (this._physicsEngine) {
  13599. return true;
  13600. }
  13601. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13602. if (!this._physicsEngine.isSupported()) {
  13603. this._physicsEngine = null;
  13604. return false;
  13605. }
  13606. this._physicsEngine._initialize(gravity);
  13607. return true;
  13608. };
  13609. Scene.prototype.disablePhysicsEngine = function () {
  13610. if (!this._physicsEngine) {
  13611. return;
  13612. }
  13613. this._physicsEngine.dispose();
  13614. this._physicsEngine = undefined;
  13615. };
  13616. Scene.prototype.isPhysicsEnabled = function () {
  13617. return this._physicsEngine !== undefined;
  13618. };
  13619. Scene.prototype.setGravity = function (gravity) {
  13620. if (!this._physicsEngine) {
  13621. return;
  13622. }
  13623. this._physicsEngine._setGravity(gravity);
  13624. };
  13625. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13626. if (parts.parts) {
  13627. options = parts;
  13628. parts = parts.parts;
  13629. }
  13630. if (!this._physicsEngine) {
  13631. return null;
  13632. }
  13633. for (var index = 0; index < parts.length; index++) {
  13634. var mesh = parts[index].mesh;
  13635. mesh._physicImpostor = parts[index].impostor;
  13636. mesh._physicsMass = options.mass / parts.length;
  13637. mesh._physicsFriction = options.friction;
  13638. mesh._physicRestitution = options.restitution;
  13639. }
  13640. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13641. };
  13642. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13643. for (var index = 0; index < compound.parts.length; index++) {
  13644. var mesh = compound.parts[index].mesh;
  13645. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13646. this._physicsEngine._unregisterMesh(mesh);
  13647. }
  13648. };
  13649. // Misc.
  13650. Scene.prototype.createDefaultCameraOrLight = function () {
  13651. // Light
  13652. if (this.lights.length === 0) {
  13653. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13654. }
  13655. // Camera
  13656. if (!this.activeCamera) {
  13657. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13658. // Compute position
  13659. var worldExtends = this.getWorldExtends();
  13660. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13661. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13662. camera.setTarget(worldCenter);
  13663. this.activeCamera = camera;
  13664. }
  13665. };
  13666. // Tags
  13667. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13668. if (tagsQuery === undefined) {
  13669. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13670. return list;
  13671. }
  13672. var listByTags = [];
  13673. forEach = forEach || (function (item) { return; });
  13674. for (var i in list) {
  13675. var item = list[i];
  13676. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13677. listByTags.push(item);
  13678. forEach(item);
  13679. }
  13680. }
  13681. return listByTags;
  13682. };
  13683. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13684. return this._getByTags(this.meshes, tagsQuery, forEach);
  13685. };
  13686. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13687. return this._getByTags(this.cameras, tagsQuery, forEach);
  13688. };
  13689. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13690. return this._getByTags(this.lights, tagsQuery, forEach);
  13691. };
  13692. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13693. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13694. };
  13695. // Statics
  13696. Scene._FOGMODE_NONE = 0;
  13697. Scene._FOGMODE_EXP = 1;
  13698. Scene._FOGMODE_EXP2 = 2;
  13699. Scene._FOGMODE_LINEAR = 3;
  13700. Scene.MinDeltaTime = 1.0;
  13701. Scene.MaxDeltaTime = 1000.0;
  13702. return Scene;
  13703. })();
  13704. BABYLON.Scene = Scene;
  13705. })(BABYLON || (BABYLON = {}));
  13706. //# sourceMappingURL=babylon.scene.js.map
  13707. var BABYLON;
  13708. (function (BABYLON) {
  13709. var VertexBuffer = (function () {
  13710. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13711. if (engine instanceof BABYLON.Mesh) {
  13712. this._engine = engine.getScene().getEngine();
  13713. }
  13714. else {
  13715. this._engine = engine;
  13716. }
  13717. this._updatable = updatable;
  13718. this._data = data;
  13719. if (!postponeInternalCreation) {
  13720. this.create();
  13721. }
  13722. this._kind = kind;
  13723. if (stride) {
  13724. this._strideSize = stride;
  13725. return;
  13726. }
  13727. // Deduce stride from kind
  13728. switch (kind) {
  13729. case VertexBuffer.PositionKind:
  13730. this._strideSize = 3;
  13731. break;
  13732. case VertexBuffer.NormalKind:
  13733. this._strideSize = 3;
  13734. break;
  13735. case VertexBuffer.UVKind:
  13736. this._strideSize = 2;
  13737. break;
  13738. case VertexBuffer.UV2Kind:
  13739. this._strideSize = 2;
  13740. break;
  13741. case VertexBuffer.ColorKind:
  13742. this._strideSize = 4;
  13743. break;
  13744. case VertexBuffer.MatricesIndicesKind:
  13745. this._strideSize = 4;
  13746. break;
  13747. case VertexBuffer.MatricesWeightsKind:
  13748. this._strideSize = 4;
  13749. break;
  13750. }
  13751. }
  13752. // Properties
  13753. VertexBuffer.prototype.isUpdatable = function () {
  13754. return this._updatable;
  13755. };
  13756. VertexBuffer.prototype.getData = function () {
  13757. return this._data;
  13758. };
  13759. VertexBuffer.prototype.getBuffer = function () {
  13760. return this._buffer;
  13761. };
  13762. VertexBuffer.prototype.getStrideSize = function () {
  13763. return this._strideSize;
  13764. };
  13765. // Methods
  13766. VertexBuffer.prototype.create = function (data) {
  13767. if (!data && this._buffer) {
  13768. return; // nothing to do
  13769. }
  13770. data = data || this._data;
  13771. if (!this._buffer) {
  13772. if (this._updatable) {
  13773. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13774. }
  13775. else {
  13776. this._buffer = this._engine.createVertexBuffer(data);
  13777. }
  13778. }
  13779. if (this._updatable) {
  13780. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13781. this._data = data;
  13782. }
  13783. };
  13784. VertexBuffer.prototype.update = function (data) {
  13785. this.create(data);
  13786. };
  13787. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13788. if (!this._buffer) {
  13789. return;
  13790. }
  13791. if (this._updatable) {
  13792. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13793. this._data = null;
  13794. }
  13795. };
  13796. VertexBuffer.prototype.dispose = function () {
  13797. if (!this._buffer) {
  13798. return;
  13799. }
  13800. if (this._engine._releaseBuffer(this._buffer)) {
  13801. this._buffer = null;
  13802. }
  13803. };
  13804. Object.defineProperty(VertexBuffer, "PositionKind", {
  13805. get: function () {
  13806. return VertexBuffer._PositionKind;
  13807. },
  13808. enumerable: true,
  13809. configurable: true
  13810. });
  13811. Object.defineProperty(VertexBuffer, "NormalKind", {
  13812. get: function () {
  13813. return VertexBuffer._NormalKind;
  13814. },
  13815. enumerable: true,
  13816. configurable: true
  13817. });
  13818. Object.defineProperty(VertexBuffer, "UVKind", {
  13819. get: function () {
  13820. return VertexBuffer._UVKind;
  13821. },
  13822. enumerable: true,
  13823. configurable: true
  13824. });
  13825. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13826. get: function () {
  13827. return VertexBuffer._UV2Kind;
  13828. },
  13829. enumerable: true,
  13830. configurable: true
  13831. });
  13832. Object.defineProperty(VertexBuffer, "ColorKind", {
  13833. get: function () {
  13834. return VertexBuffer._ColorKind;
  13835. },
  13836. enumerable: true,
  13837. configurable: true
  13838. });
  13839. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13840. get: function () {
  13841. return VertexBuffer._MatricesIndicesKind;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13847. get: function () {
  13848. return VertexBuffer._MatricesWeightsKind;
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. // Enums
  13854. VertexBuffer._PositionKind = "position";
  13855. VertexBuffer._NormalKind = "normal";
  13856. VertexBuffer._UVKind = "uv";
  13857. VertexBuffer._UV2Kind = "uv2";
  13858. VertexBuffer._ColorKind = "color";
  13859. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13860. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13861. return VertexBuffer;
  13862. })();
  13863. BABYLON.VertexBuffer = VertexBuffer;
  13864. })(BABYLON || (BABYLON = {}));
  13865. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13866. var BABYLON;
  13867. (function (BABYLON) {
  13868. /**
  13869. * Creates an instance based on a source mesh.
  13870. */
  13871. var InstancedMesh = (function (_super) {
  13872. __extends(InstancedMesh, _super);
  13873. function InstancedMesh(name, source) {
  13874. _super.call(this, name, source.getScene());
  13875. source.instances.push(this);
  13876. this._sourceMesh = source;
  13877. this.position.copyFrom(source.position);
  13878. this.rotation.copyFrom(source.rotation);
  13879. this.scaling.copyFrom(source.scaling);
  13880. if (source.rotationQuaternion) {
  13881. this.rotationQuaternion = source.rotationQuaternion.clone();
  13882. }
  13883. this.infiniteDistance = source.infiniteDistance;
  13884. this.setPivotMatrix(source.getPivotMatrix());
  13885. this.refreshBoundingInfo();
  13886. this._syncSubMeshes();
  13887. }
  13888. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13889. // Methods
  13890. get: function () {
  13891. return this._sourceMesh.receiveShadows;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(InstancedMesh.prototype, "material", {
  13897. get: function () {
  13898. return this._sourceMesh.material;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13904. get: function () {
  13905. return this._sourceMesh.visibility;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13911. get: function () {
  13912. return this._sourceMesh.skeleton;
  13913. },
  13914. enumerable: true,
  13915. configurable: true
  13916. });
  13917. InstancedMesh.prototype.getTotalVertices = function () {
  13918. return this._sourceMesh.getTotalVertices();
  13919. };
  13920. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13921. get: function () {
  13922. return this._sourceMesh;
  13923. },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. InstancedMesh.prototype.getVerticesData = function (kind) {
  13928. return this._sourceMesh.getVerticesData(kind);
  13929. };
  13930. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13931. return this._sourceMesh.isVerticesDataPresent(kind);
  13932. };
  13933. InstancedMesh.prototype.getIndices = function () {
  13934. return this._sourceMesh.getIndices();
  13935. };
  13936. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13937. get: function () {
  13938. return this._sourceMesh._positions;
  13939. },
  13940. enumerable: true,
  13941. configurable: true
  13942. });
  13943. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13944. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13945. if (data) {
  13946. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13947. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13948. }
  13949. this._updateBoundingInfo();
  13950. };
  13951. InstancedMesh.prototype._preActivate = function () {
  13952. if (this._currentLOD) {
  13953. this._currentLOD._preActivate();
  13954. }
  13955. };
  13956. InstancedMesh.prototype._activate = function (renderId) {
  13957. if (this._currentLOD) {
  13958. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13959. }
  13960. };
  13961. InstancedMesh.prototype.getLOD = function (camera) {
  13962. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13963. if (this._currentLOD === this.sourceMesh) {
  13964. return this;
  13965. }
  13966. return this._currentLOD;
  13967. };
  13968. InstancedMesh.prototype._syncSubMeshes = function () {
  13969. this.releaseSubMeshes();
  13970. if (this._sourceMesh.subMeshes) {
  13971. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13972. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13973. }
  13974. }
  13975. };
  13976. InstancedMesh.prototype._generatePointsArray = function () {
  13977. return this._sourceMesh._generatePointsArray();
  13978. };
  13979. // Clone
  13980. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13981. var result = this._sourceMesh.createInstance(name);
  13982. // Deep copy
  13983. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13984. // Bounding info
  13985. this.refreshBoundingInfo();
  13986. // Parent
  13987. if (newParent) {
  13988. result.parent = newParent;
  13989. }
  13990. if (!doNotCloneChildren) {
  13991. // Children
  13992. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13993. var mesh = this.getScene().meshes[index];
  13994. if (mesh.parent === this) {
  13995. mesh.clone(mesh.name, result);
  13996. }
  13997. }
  13998. }
  13999. result.computeWorldMatrix(true);
  14000. return result;
  14001. };
  14002. // Dispoe
  14003. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14004. // Remove from mesh
  14005. var index = this._sourceMesh.instances.indexOf(this);
  14006. this._sourceMesh.instances.splice(index, 1);
  14007. _super.prototype.dispose.call(this, doNotRecurse);
  14008. };
  14009. return InstancedMesh;
  14010. })(BABYLON.AbstractMesh);
  14011. BABYLON.InstancedMesh = InstancedMesh;
  14012. })(BABYLON || (BABYLON = {}));
  14013. //# sourceMappingURL=babylon.instancedMesh.js.map
  14014. var BABYLON;
  14015. (function (BABYLON) {
  14016. var _InstancesBatch = (function () {
  14017. function _InstancesBatch() {
  14018. this.mustReturn = false;
  14019. this.visibleInstances = new Array();
  14020. this.renderSelf = new Array();
  14021. }
  14022. return _InstancesBatch;
  14023. })();
  14024. BABYLON._InstancesBatch = _InstancesBatch;
  14025. var Mesh = (function (_super) {
  14026. __extends(Mesh, _super);
  14027. /**
  14028. * @constructor
  14029. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14030. * @param {Scene} scene - The scene to add this mesh to.
  14031. * @param {Node} parent - The parent of this mesh, if it has one
  14032. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14033. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14034. * When false, achieved by calling a clone(), also passing False.
  14035. * This will make creation of children, recursive.
  14036. */
  14037. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14038. if (parent === void 0) { parent = null; }
  14039. _super.call(this, name, scene);
  14040. // Members
  14041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14042. this.instances = new Array();
  14043. this._LODLevels = new Array();
  14044. this._onBeforeRenderCallbacks = new Array();
  14045. this._onAfterRenderCallbacks = new Array();
  14046. this._visibleInstances = {};
  14047. this._renderIdForInstances = new Array();
  14048. this._batchCache = new _InstancesBatch();
  14049. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14050. this._sideOrientation = Mesh._DEFAULTSIDE;
  14051. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14052. if (source) {
  14053. // Geometry
  14054. if (source._geometry) {
  14055. source._geometry.applyToMesh(this);
  14056. }
  14057. // Deep copy
  14058. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14059. // Material
  14060. this.material = source.material;
  14061. if (!doNotCloneChildren) {
  14062. // Children
  14063. for (var index = 0; index < scene.meshes.length; index++) {
  14064. var mesh = scene.meshes[index];
  14065. if (mesh.parent === source) {
  14066. // doNotCloneChildren is always going to be False
  14067. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14068. }
  14069. }
  14070. }
  14071. // Particles
  14072. for (index = 0; index < scene.particleSystems.length; index++) {
  14073. var system = scene.particleSystems[index];
  14074. if (system.emitter === source) {
  14075. system.clone(system.name, this);
  14076. }
  14077. }
  14078. this.computeWorldMatrix(true);
  14079. }
  14080. // Parent
  14081. if (parent !== null) {
  14082. this.parent = parent;
  14083. }
  14084. }
  14085. Object.defineProperty(Mesh, "FRONTSIDE", {
  14086. get: function () {
  14087. return Mesh._FRONTSIDE;
  14088. },
  14089. enumerable: true,
  14090. configurable: true
  14091. });
  14092. Object.defineProperty(Mesh, "BACKSIDE", {
  14093. get: function () {
  14094. return Mesh._BACKSIDE;
  14095. },
  14096. enumerable: true,
  14097. configurable: true
  14098. });
  14099. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14100. get: function () {
  14101. return Mesh._DOUBLESIDE;
  14102. },
  14103. enumerable: true,
  14104. configurable: true
  14105. });
  14106. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14107. get: function () {
  14108. return Mesh._DEFAULTSIDE;
  14109. },
  14110. enumerable: true,
  14111. configurable: true
  14112. });
  14113. Object.defineProperty(Mesh, "NO_CAP", {
  14114. get: function () {
  14115. return Mesh._NO_CAP;
  14116. },
  14117. enumerable: true,
  14118. configurable: true
  14119. });
  14120. Object.defineProperty(Mesh, "CAP_START", {
  14121. get: function () {
  14122. return Mesh._CAP_START;
  14123. },
  14124. enumerable: true,
  14125. configurable: true
  14126. });
  14127. Object.defineProperty(Mesh, "CAP_END", {
  14128. get: function () {
  14129. return Mesh._CAP_END;
  14130. },
  14131. enumerable: true,
  14132. configurable: true
  14133. });
  14134. Object.defineProperty(Mesh, "CAP_ALL", {
  14135. get: function () {
  14136. return Mesh._CAP_ALL;
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14142. // Methods
  14143. get: function () {
  14144. return this._LODLevels.length > 0;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. Mesh.prototype._sortLODLevels = function () {
  14150. this._LODLevels.sort(function (a, b) {
  14151. if (a.distance < b.distance) {
  14152. return 1;
  14153. }
  14154. if (a.distance > b.distance) {
  14155. return -1;
  14156. }
  14157. return 0;
  14158. });
  14159. };
  14160. /**
  14161. * Add a mesh as LOD level triggered at the given distance.
  14162. * @param {number} distance - the distance from the center of the object to show this level
  14163. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14164. * @return {BABYLON.Mesh} this mesh (for chaining)
  14165. */
  14166. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14167. if (mesh && mesh._masterMesh) {
  14168. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14169. return this;
  14170. }
  14171. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14172. this._LODLevels.push(level);
  14173. if (mesh) {
  14174. mesh._masterMesh = this;
  14175. }
  14176. this._sortLODLevels();
  14177. return this;
  14178. };
  14179. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14180. for (var index = 0; index < this._LODLevels.length; index++) {
  14181. var level = this._LODLevels[index];
  14182. if (level.distance === distance) {
  14183. return level.mesh;
  14184. }
  14185. }
  14186. return null;
  14187. };
  14188. /**
  14189. * Remove a mesh from the LOD array
  14190. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14191. * @return {BABYLON.Mesh} this mesh (for chaining)
  14192. */
  14193. Mesh.prototype.removeLODLevel = function (mesh) {
  14194. for (var index = 0; index < this._LODLevels.length; index++) {
  14195. if (this._LODLevels[index].mesh === mesh) {
  14196. this._LODLevels.splice(index, 1);
  14197. if (mesh) {
  14198. mesh._masterMesh = null;
  14199. }
  14200. }
  14201. }
  14202. this._sortLODLevels();
  14203. return this;
  14204. };
  14205. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14206. if (!this._LODLevels || this._LODLevels.length === 0) {
  14207. return this;
  14208. }
  14209. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14210. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14211. if (this.onLODLevelSelection) {
  14212. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14213. }
  14214. return this;
  14215. }
  14216. for (var index = 0; index < this._LODLevels.length; index++) {
  14217. var level = this._LODLevels[index];
  14218. if (level.distance < distanceToCamera) {
  14219. if (level.mesh) {
  14220. level.mesh._preActivate();
  14221. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14222. }
  14223. if (this.onLODLevelSelection) {
  14224. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14225. }
  14226. return level.mesh;
  14227. }
  14228. }
  14229. if (this.onLODLevelSelection) {
  14230. this.onLODLevelSelection(distanceToCamera, this, this);
  14231. }
  14232. return this;
  14233. };
  14234. Object.defineProperty(Mesh.prototype, "geometry", {
  14235. get: function () {
  14236. return this._geometry;
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. Mesh.prototype.getTotalVertices = function () {
  14242. if (!this._geometry) {
  14243. return 0;
  14244. }
  14245. return this._geometry.getTotalVertices();
  14246. };
  14247. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14248. if (!this._geometry) {
  14249. return null;
  14250. }
  14251. return this._geometry.getVerticesData(kind, copyWhenShared);
  14252. };
  14253. Mesh.prototype.getVertexBuffer = function (kind) {
  14254. if (!this._geometry) {
  14255. return undefined;
  14256. }
  14257. return this._geometry.getVertexBuffer(kind);
  14258. };
  14259. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14260. if (!this._geometry) {
  14261. if (this._delayInfo) {
  14262. return this._delayInfo.indexOf(kind) !== -1;
  14263. }
  14264. return false;
  14265. }
  14266. return this._geometry.isVerticesDataPresent(kind);
  14267. };
  14268. Mesh.prototype.getVerticesDataKinds = function () {
  14269. if (!this._geometry) {
  14270. var result = [];
  14271. if (this._delayInfo) {
  14272. for (var kind in this._delayInfo) {
  14273. result.push(kind);
  14274. }
  14275. }
  14276. return result;
  14277. }
  14278. return this._geometry.getVerticesDataKinds();
  14279. };
  14280. Mesh.prototype.getTotalIndices = function () {
  14281. if (!this._geometry) {
  14282. return 0;
  14283. }
  14284. return this._geometry.getTotalIndices();
  14285. };
  14286. Mesh.prototype.getIndices = function (copyWhenShared) {
  14287. if (!this._geometry) {
  14288. return [];
  14289. }
  14290. return this._geometry.getIndices(copyWhenShared);
  14291. };
  14292. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14293. get: function () {
  14294. return this._masterMesh !== null && this._masterMesh !== undefined;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Mesh.prototype.isReady = function () {
  14300. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14301. return false;
  14302. }
  14303. return _super.prototype.isReady.call(this);
  14304. };
  14305. Mesh.prototype.isDisposed = function () {
  14306. return this._isDisposed;
  14307. };
  14308. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14309. get: function () {
  14310. return this._sideOrientation;
  14311. },
  14312. set: function (sideO) {
  14313. this._sideOrientation = sideO;
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14319. get: function () {
  14320. return this._areNormalsFrozen;
  14321. },
  14322. enumerable: true,
  14323. configurable: true
  14324. });
  14325. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14326. Mesh.prototype.freezeNormals = function () {
  14327. this._areNormalsFrozen = true;
  14328. };
  14329. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14330. Mesh.prototype.unfreezeNormals = function () {
  14331. this._areNormalsFrozen = false;
  14332. };
  14333. // Methods
  14334. Mesh.prototype._preActivate = function () {
  14335. var sceneRenderId = this.getScene().getRenderId();
  14336. if (this._preActivateId === sceneRenderId) {
  14337. return;
  14338. }
  14339. this._preActivateId = sceneRenderId;
  14340. this._visibleInstances = null;
  14341. };
  14342. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14343. if (!this._visibleInstances) {
  14344. this._visibleInstances = {};
  14345. this._visibleInstances.defaultRenderId = renderId;
  14346. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14347. }
  14348. if (!this._visibleInstances[renderId]) {
  14349. this._visibleInstances[renderId] = new Array();
  14350. }
  14351. this._visibleInstances[renderId].push(instance);
  14352. };
  14353. Mesh.prototype.refreshBoundingInfo = function () {
  14354. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14355. if (data) {
  14356. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14357. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14358. }
  14359. if (this.subMeshes) {
  14360. for (var index = 0; index < this.subMeshes.length; index++) {
  14361. this.subMeshes[index].refreshBoundingInfo();
  14362. }
  14363. }
  14364. this._updateBoundingInfo();
  14365. };
  14366. Mesh.prototype._createGlobalSubMesh = function () {
  14367. var totalVertices = this.getTotalVertices();
  14368. if (!totalVertices || !this.getIndices()) {
  14369. return null;
  14370. }
  14371. this.releaseSubMeshes();
  14372. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14373. };
  14374. Mesh.prototype.subdivide = function (count) {
  14375. if (count < 1) {
  14376. return;
  14377. }
  14378. var totalIndices = this.getTotalIndices();
  14379. var subdivisionSize = (totalIndices / count) | 0;
  14380. var offset = 0;
  14381. // Ensure that subdivisionSize is a multiple of 3
  14382. while (subdivisionSize % 3 !== 0) {
  14383. subdivisionSize++;
  14384. }
  14385. this.releaseSubMeshes();
  14386. for (var index = 0; index < count; index++) {
  14387. if (offset >= totalIndices) {
  14388. break;
  14389. }
  14390. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14391. offset += subdivisionSize;
  14392. }
  14393. this.synchronizeInstances();
  14394. };
  14395. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14396. if (kind instanceof Array) {
  14397. var temp = data;
  14398. data = kind;
  14399. kind = temp;
  14400. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14401. }
  14402. if (!this._geometry) {
  14403. var vertexData = new BABYLON.VertexData();
  14404. vertexData.set(data, kind);
  14405. var scene = this.getScene();
  14406. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14407. }
  14408. else {
  14409. this._geometry.setVerticesData(kind, data, updatable, stride);
  14410. }
  14411. };
  14412. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14413. if (!this._geometry) {
  14414. return;
  14415. }
  14416. if (!makeItUnique) {
  14417. this._geometry.updateVerticesData(kind, data, updateExtends);
  14418. }
  14419. else {
  14420. this.makeGeometryUnique();
  14421. this.updateVerticesData(kind, data, updateExtends, false);
  14422. }
  14423. };
  14424. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14425. if (!this._geometry) {
  14426. return;
  14427. }
  14428. if (!makeItUnique) {
  14429. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14430. }
  14431. else {
  14432. this.makeGeometryUnique();
  14433. this.updateVerticesDataDirectly(kind, data, offset, false);
  14434. }
  14435. };
  14436. // Mesh positions update function :
  14437. // updates the mesh positions according to the positionFunction returned values.
  14438. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14439. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14440. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14441. if (computeNormals === void 0) { computeNormals = true; }
  14442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14443. positionFunction(positions);
  14444. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14445. if (computeNormals) {
  14446. var indices = this.getIndices();
  14447. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14448. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14449. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14450. }
  14451. };
  14452. Mesh.prototype.makeGeometryUnique = function () {
  14453. if (!this._geometry) {
  14454. return;
  14455. }
  14456. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14457. geometry.applyToMesh(this);
  14458. };
  14459. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14460. if (!this._geometry) {
  14461. var vertexData = new BABYLON.VertexData();
  14462. vertexData.indices = indices;
  14463. var scene = this.getScene();
  14464. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14465. }
  14466. else {
  14467. this._geometry.setIndices(indices, totalVertices);
  14468. }
  14469. };
  14470. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14471. var engine = this.getScene().getEngine();
  14472. // Wireframe
  14473. var indexToBind;
  14474. switch (fillMode) {
  14475. case BABYLON.Material.PointFillMode:
  14476. indexToBind = null;
  14477. break;
  14478. case BABYLON.Material.WireFrameFillMode:
  14479. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14480. break;
  14481. default:
  14482. case BABYLON.Material.TriangleFillMode:
  14483. indexToBind = this._geometry.getIndexBuffer();
  14484. break;
  14485. }
  14486. // VBOs
  14487. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14488. };
  14489. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14490. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14491. return;
  14492. }
  14493. var engine = this.getScene().getEngine();
  14494. // Draw order
  14495. switch (fillMode) {
  14496. case BABYLON.Material.PointFillMode:
  14497. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14498. break;
  14499. case BABYLON.Material.WireFrameFillMode:
  14500. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14501. break;
  14502. default:
  14503. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14504. }
  14505. };
  14506. Mesh.prototype.registerBeforeRender = function (func) {
  14507. this._onBeforeRenderCallbacks.push(func);
  14508. };
  14509. Mesh.prototype.unregisterBeforeRender = function (func) {
  14510. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14511. if (index > -1) {
  14512. this._onBeforeRenderCallbacks.splice(index, 1);
  14513. }
  14514. };
  14515. Mesh.prototype.registerAfterRender = function (func) {
  14516. this._onAfterRenderCallbacks.push(func);
  14517. };
  14518. Mesh.prototype.unregisterAfterRender = function (func) {
  14519. var index = this._onAfterRenderCallbacks.indexOf(func);
  14520. if (index > -1) {
  14521. this._onAfterRenderCallbacks.splice(index, 1);
  14522. }
  14523. };
  14524. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14525. var scene = this.getScene();
  14526. this._batchCache.mustReturn = false;
  14527. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14528. this._batchCache.visibleInstances[subMeshId] = null;
  14529. if (this._visibleInstances) {
  14530. var currentRenderId = scene.getRenderId();
  14531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14532. var selfRenderId = this._renderId;
  14533. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14534. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14535. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14536. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14537. }
  14538. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14539. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14540. this._batchCache.mustReturn = true;
  14541. return this._batchCache;
  14542. }
  14543. if (currentRenderId !== selfRenderId) {
  14544. this._batchCache.renderSelf[subMeshId] = false;
  14545. }
  14546. }
  14547. this._renderIdForInstances[subMeshId] = currentRenderId;
  14548. }
  14549. return this._batchCache;
  14550. };
  14551. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14552. var visibleInstances = batch.visibleInstances[subMesh._id];
  14553. var matricesCount = visibleInstances.length + 1;
  14554. var bufferSize = matricesCount * 16 * 4;
  14555. while (this._instancesBufferSize < bufferSize) {
  14556. this._instancesBufferSize *= 2;
  14557. }
  14558. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14559. if (this._worldMatricesInstancesBuffer) {
  14560. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14561. }
  14562. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14563. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14564. }
  14565. var offset = 0;
  14566. var instancesCount = 0;
  14567. var world = this.getWorldMatrix();
  14568. if (batch.renderSelf[subMesh._id]) {
  14569. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14570. offset += 16;
  14571. instancesCount++;
  14572. }
  14573. if (visibleInstances) {
  14574. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14575. var instance = visibleInstances[instanceIndex];
  14576. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14577. offset += 16;
  14578. instancesCount++;
  14579. }
  14580. }
  14581. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14582. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14583. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14584. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14585. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14586. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14587. this._draw(subMesh, fillMode, instancesCount);
  14588. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14589. };
  14590. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14591. var scene = this.getScene();
  14592. var engine = scene.getEngine();
  14593. if (hardwareInstancedRendering) {
  14594. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14595. }
  14596. else {
  14597. if (batch.renderSelf[subMesh._id]) {
  14598. // Draw
  14599. if (onBeforeDraw) {
  14600. onBeforeDraw(false, this.getWorldMatrix());
  14601. }
  14602. this._draw(subMesh, fillMode);
  14603. }
  14604. if (batch.visibleInstances[subMesh._id]) {
  14605. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14606. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14607. // World
  14608. var world = instance.getWorldMatrix();
  14609. if (onBeforeDraw) {
  14610. onBeforeDraw(true, world);
  14611. }
  14612. // Draw
  14613. this._draw(subMesh, fillMode);
  14614. }
  14615. }
  14616. }
  14617. };
  14618. Mesh.prototype.render = function (subMesh) {
  14619. var scene = this.getScene();
  14620. // Managing instances
  14621. var batch = this._getInstancesRenderList(subMesh._id);
  14622. if (batch.mustReturn) {
  14623. return;
  14624. }
  14625. // Checking geometry state
  14626. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14627. return;
  14628. }
  14629. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14630. this._onBeforeRenderCallbacks[callbackIndex](this);
  14631. }
  14632. var engine = scene.getEngine();
  14633. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14634. // Material
  14635. var effectiveMaterial = subMesh.getMaterial();
  14636. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14637. return;
  14638. }
  14639. // Outline - step 1
  14640. var savedDepthWrite = engine.getDepthWrite();
  14641. if (this.renderOutline) {
  14642. engine.setDepthWrite(false);
  14643. scene.getOutlineRenderer().render(subMesh, batch);
  14644. engine.setDepthWrite(savedDepthWrite);
  14645. }
  14646. effectiveMaterial._preBind();
  14647. var effect = effectiveMaterial.getEffect();
  14648. // Bind
  14649. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14650. this._bind(subMesh, effect, fillMode);
  14651. var world = this.getWorldMatrix();
  14652. effectiveMaterial.bind(world, this);
  14653. // Draw
  14654. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14655. if (isInstance) {
  14656. effectiveMaterial.bindOnlyWorldMatrix(world);
  14657. }
  14658. });
  14659. // Unbind
  14660. effectiveMaterial.unbind();
  14661. // Outline - step 2
  14662. if (this.renderOutline && savedDepthWrite) {
  14663. engine.setDepthWrite(true);
  14664. engine.setColorWrite(false);
  14665. scene.getOutlineRenderer().render(subMesh, batch);
  14666. engine.setColorWrite(true);
  14667. }
  14668. // Overlay
  14669. if (this.renderOverlay) {
  14670. var currentMode = engine.getAlphaMode();
  14671. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14672. scene.getOutlineRenderer().render(subMesh, batch, true);
  14673. engine.setAlphaMode(currentMode);
  14674. }
  14675. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14676. this._onAfterRenderCallbacks[callbackIndex](this);
  14677. }
  14678. };
  14679. Mesh.prototype.getEmittedParticleSystems = function () {
  14680. var results = new Array();
  14681. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14682. var particleSystem = this.getScene().particleSystems[index];
  14683. if (particleSystem.emitter === this) {
  14684. results.push(particleSystem);
  14685. }
  14686. }
  14687. return results;
  14688. };
  14689. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14690. var results = new Array();
  14691. var descendants = this.getDescendants();
  14692. descendants.push(this);
  14693. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14694. var particleSystem = this.getScene().particleSystems[index];
  14695. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14696. results.push(particleSystem);
  14697. }
  14698. }
  14699. return results;
  14700. };
  14701. Mesh.prototype.getChildren = function () {
  14702. var results = [];
  14703. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14704. var mesh = this.getScene().meshes[index];
  14705. if (mesh.parent === this) {
  14706. results.push(mesh);
  14707. }
  14708. }
  14709. return results;
  14710. };
  14711. Mesh.prototype._checkDelayState = function () {
  14712. var _this = this;
  14713. var that = this;
  14714. var scene = this.getScene();
  14715. if (this._geometry) {
  14716. this._geometry.load(scene);
  14717. }
  14718. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14719. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14720. scene._addPendingData(that);
  14721. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14722. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14723. if (data instanceof ArrayBuffer) {
  14724. _this._delayLoadingFunction(data, _this);
  14725. }
  14726. else {
  14727. _this._delayLoadingFunction(JSON.parse(data), _this);
  14728. }
  14729. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14730. scene._removePendingData(_this);
  14731. }, function () { }, scene.database, getBinaryData);
  14732. }
  14733. };
  14734. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14735. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14736. return false;
  14737. }
  14738. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14739. return false;
  14740. }
  14741. this._checkDelayState();
  14742. return true;
  14743. };
  14744. Mesh.prototype.setMaterialByID = function (id) {
  14745. var materials = this.getScene().materials;
  14746. for (var index = 0; index < materials.length; index++) {
  14747. if (materials[index].id === id) {
  14748. this.material = materials[index];
  14749. return;
  14750. }
  14751. }
  14752. // Multi
  14753. var multiMaterials = this.getScene().multiMaterials;
  14754. for (index = 0; index < multiMaterials.length; index++) {
  14755. if (multiMaterials[index].id === id) {
  14756. this.material = multiMaterials[index];
  14757. return;
  14758. }
  14759. }
  14760. };
  14761. Mesh.prototype.getAnimatables = function () {
  14762. var results = [];
  14763. if (this.material) {
  14764. results.push(this.material);
  14765. }
  14766. if (this.skeleton) {
  14767. results.push(this.skeleton);
  14768. }
  14769. return results;
  14770. };
  14771. // Geometry
  14772. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14773. // Position
  14774. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14775. return;
  14776. }
  14777. this._resetPointsArrayCache();
  14778. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14779. var temp = [];
  14780. for (var index = 0; index < data.length; index += 3) {
  14781. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14782. }
  14783. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14784. // Normals
  14785. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14786. return;
  14787. }
  14788. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14789. temp = [];
  14790. for (index = 0; index < data.length; index += 3) {
  14791. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14792. }
  14793. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14794. };
  14795. // Cache
  14796. Mesh.prototype._resetPointsArrayCache = function () {
  14797. this._positions = null;
  14798. };
  14799. Mesh.prototype._generatePointsArray = function () {
  14800. if (this._positions)
  14801. return true;
  14802. this._positions = [];
  14803. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14804. if (!data) {
  14805. return false;
  14806. }
  14807. for (var index = 0; index < data.length; index += 3) {
  14808. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14809. }
  14810. return true;
  14811. };
  14812. // Clone
  14813. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14814. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14815. };
  14816. // Dispose
  14817. Mesh.prototype.dispose = function (doNotRecurse) {
  14818. if (this._geometry) {
  14819. this._geometry.releaseForMesh(this, true);
  14820. }
  14821. // Instances
  14822. if (this._worldMatricesInstancesBuffer) {
  14823. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14824. this._worldMatricesInstancesBuffer = null;
  14825. }
  14826. while (this.instances.length) {
  14827. this.instances[0].dispose();
  14828. }
  14829. _super.prototype.dispose.call(this, doNotRecurse);
  14830. };
  14831. // Geometric tools
  14832. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14833. var _this = this;
  14834. var scene = this.getScene();
  14835. var onload = function (img) {
  14836. // Getting height map data
  14837. var canvas = document.createElement("canvas");
  14838. var context = canvas.getContext("2d");
  14839. var heightMapWidth = img.width;
  14840. var heightMapHeight = img.height;
  14841. canvas.width = heightMapWidth;
  14842. canvas.height = heightMapHeight;
  14843. context.drawImage(img, 0, 0);
  14844. // Create VertexData from map data
  14845. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14846. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14847. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14848. //execute success callback, if set
  14849. if (onSuccess) {
  14850. onSuccess(_this);
  14851. }
  14852. };
  14853. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14854. };
  14855. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14856. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14857. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14858. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14859. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14860. return;
  14861. }
  14862. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14863. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14864. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14865. var position = BABYLON.Vector3.Zero();
  14866. var normal = BABYLON.Vector3.Zero();
  14867. var uv = BABYLON.Vector2.Zero();
  14868. for (var index = 0; index < positions.length; index += 3) {
  14869. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14870. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14871. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14872. // Compute height
  14873. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14874. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14875. var pos = (u + v * heightMapWidth) * 4;
  14876. var r = buffer[pos] / 255.0;
  14877. var g = buffer[pos + 1] / 255.0;
  14878. var b = buffer[pos + 2] / 255.0;
  14879. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14880. normal.normalize();
  14881. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14882. position = position.add(normal);
  14883. position.toArray(positions, index);
  14884. }
  14885. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14886. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14887. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14888. };
  14889. Mesh.prototype.convertToFlatShadedMesh = function () {
  14890. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14891. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14892. var kinds = this.getVerticesDataKinds();
  14893. var vbs = [];
  14894. var data = [];
  14895. var newdata = [];
  14896. var updatableNormals = false;
  14897. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14898. var kind = kinds[kindIndex];
  14899. var vertexBuffer = this.getVertexBuffer(kind);
  14900. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14901. updatableNormals = vertexBuffer.isUpdatable();
  14902. kinds.splice(kindIndex, 1);
  14903. kindIndex--;
  14904. continue;
  14905. }
  14906. vbs[kind] = vertexBuffer;
  14907. data[kind] = vbs[kind].getData();
  14908. newdata[kind] = [];
  14909. }
  14910. // Save previous submeshes
  14911. var previousSubmeshes = this.subMeshes.slice(0);
  14912. var indices = this.getIndices();
  14913. var totalIndices = this.getTotalIndices();
  14914. // Generating unique vertices per face
  14915. for (var index = 0; index < totalIndices; index++) {
  14916. var vertexIndex = indices[index];
  14917. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14918. kind = kinds[kindIndex];
  14919. var stride = vbs[kind].getStrideSize();
  14920. for (var offset = 0; offset < stride; offset++) {
  14921. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14922. }
  14923. }
  14924. }
  14925. // Updating faces & normal
  14926. var normals = [];
  14927. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14928. for (index = 0; index < totalIndices; index += 3) {
  14929. indices[index] = index;
  14930. indices[index + 1] = index + 1;
  14931. indices[index + 2] = index + 2;
  14932. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14933. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14934. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14935. var p1p2 = p1.subtract(p2);
  14936. var p3p2 = p3.subtract(p2);
  14937. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14938. // Store same normals for every vertex
  14939. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14940. normals.push(normal.x);
  14941. normals.push(normal.y);
  14942. normals.push(normal.z);
  14943. }
  14944. }
  14945. this.setIndices(indices);
  14946. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14947. // Updating vertex buffers
  14948. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14949. kind = kinds[kindIndex];
  14950. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14951. }
  14952. // Updating submeshes
  14953. this.releaseSubMeshes();
  14954. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14955. var previousOne = previousSubmeshes[submeshIndex];
  14956. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14957. }
  14958. this.synchronizeInstances();
  14959. };
  14960. // Instances
  14961. Mesh.prototype.createInstance = function (name) {
  14962. return new BABYLON.InstancedMesh(name, this);
  14963. };
  14964. Mesh.prototype.synchronizeInstances = function () {
  14965. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14966. var instance = this.instances[instanceIndex];
  14967. instance._syncSubMeshes();
  14968. }
  14969. };
  14970. /**
  14971. * Simplify the mesh according to the given array of settings.
  14972. * Function will return immediately and will simplify async.
  14973. * @param settings a collection of simplification settings.
  14974. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14975. * @param type the type of simplification to run.
  14976. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14977. */
  14978. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14979. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14980. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14981. this.getScene().simplificationQueue.addTask({
  14982. settings: settings,
  14983. parallelProcessing: parallelProcessing,
  14984. mesh: this,
  14985. simplificationType: simplificationType,
  14986. successCallback: successCallback
  14987. });
  14988. };
  14989. /**
  14990. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14991. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14992. * This should be used together with the simplification to avoid disappearing triangles.
  14993. * @param successCallback an optional success callback to be called after the optimization finished.
  14994. */
  14995. Mesh.prototype.optimizeIndices = function (successCallback) {
  14996. var _this = this;
  14997. var indices = this.getIndices();
  14998. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14999. var vectorPositions = [];
  15000. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15001. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15002. }
  15003. var dupes = [];
  15004. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15005. var realPos = vectorPositions.length - 1 - iteration;
  15006. var testedPosition = vectorPositions[realPos];
  15007. for (var j = 0; j < realPos; ++j) {
  15008. var againstPosition = vectorPositions[j];
  15009. if (testedPosition.equals(againstPosition)) {
  15010. dupes[realPos] = j;
  15011. break;
  15012. }
  15013. }
  15014. }, function () {
  15015. for (var i = 0; i < indices.length; ++i) {
  15016. indices[i] = dupes[indices[i]] || indices[i];
  15017. }
  15018. //indices are now reordered
  15019. var originalSubMeshes = _this.subMeshes.slice(0);
  15020. _this.setIndices(indices);
  15021. _this.subMeshes = originalSubMeshes;
  15022. if (successCallback) {
  15023. successCallback(_this);
  15024. }
  15025. });
  15026. };
  15027. // Statics
  15028. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15029. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15030. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15031. if (ribbonInstance) {
  15032. // positionFunction : ribbon case
  15033. // only pathArray and sideOrientation parameters are taken into account for positions update
  15034. var positionFunction = function (positions) {
  15035. var minlg = pathArray[0].length;
  15036. var i = 0;
  15037. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15038. for (var si = 1; si <= ns; si++) {
  15039. for (var p = 0; p < pathArray.length; p++) {
  15040. var path = pathArray[p];
  15041. var l = path.length;
  15042. minlg = (minlg < l) ? minlg : l;
  15043. var j = 0;
  15044. while (j < minlg) {
  15045. positions[i] = path[j].x;
  15046. positions[i + 1] = path[j].y;
  15047. positions[i + 2] = path[j].z;
  15048. j++;
  15049. i += 3;
  15050. }
  15051. }
  15052. }
  15053. };
  15054. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15055. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15056. return ribbonInstance;
  15057. }
  15058. else {
  15059. var ribbon = new Mesh(name, scene);
  15060. ribbon.sideOrientation = sideOrientation;
  15061. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15062. vertexData.applyToMesh(ribbon, updatable);
  15063. return ribbon;
  15064. }
  15065. };
  15066. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15067. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15068. var disc = new Mesh(name, scene);
  15069. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15070. vertexData.applyToMesh(disc, updatable);
  15071. return disc;
  15072. };
  15073. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15074. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15075. var box = new Mesh(name, scene);
  15076. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15077. vertexData.applyToMesh(box, updatable);
  15078. return box;
  15079. };
  15080. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15081. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15082. var sphere = new Mesh(name, scene);
  15083. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15084. vertexData.applyToMesh(sphere, updatable);
  15085. return sphere;
  15086. };
  15087. // Cylinder and cone (Code inspired by SharpDX.org)
  15088. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15089. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15090. // subdivisions is a new parameter, we need to support old signature
  15091. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15092. if (scene !== undefined) {
  15093. updatable = scene;
  15094. }
  15095. scene = subdivisions;
  15096. subdivisions = 1;
  15097. }
  15098. var cylinder = new Mesh(name, scene);
  15099. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15100. vertexData.applyToMesh(cylinder, updatable);
  15101. return cylinder;
  15102. };
  15103. // Torus (Code from SharpDX.org)
  15104. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15105. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15106. var torus = new Mesh(name, scene);
  15107. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15108. vertexData.applyToMesh(torus, updatable);
  15109. return torus;
  15110. };
  15111. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15112. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15113. var torusKnot = new Mesh(name, scene);
  15114. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15115. vertexData.applyToMesh(torusKnot, updatable);
  15116. return torusKnot;
  15117. };
  15118. // Lines
  15119. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15120. if (linesInstance === void 0) { linesInstance = null; }
  15121. if (linesInstance) {
  15122. var positionFunction = function (positions) {
  15123. var i = 0;
  15124. for (var p = 0; p < points.length; p++) {
  15125. positions[i] = points[p].x;
  15126. positions[i + 1] = points[p].y;
  15127. positions[i + 2] = points[p].z;
  15128. i += 3;
  15129. }
  15130. };
  15131. linesInstance.updateMeshPositions(positionFunction, false);
  15132. return linesInstance;
  15133. }
  15134. // lines creation
  15135. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15136. var vertexData = BABYLON.VertexData.CreateLines(points);
  15137. vertexData.applyToMesh(lines, updatable);
  15138. return lines;
  15139. };
  15140. // Dashed Lines
  15141. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15142. if (linesInstance === void 0) { linesInstance = null; }
  15143. if (linesInstance) {
  15144. var positionFunction = function (positions) {
  15145. var curvect = BABYLON.Vector3.Zero();
  15146. var nbSeg = positions.length / 6;
  15147. var lg = 0;
  15148. var nb = 0;
  15149. var shft = 0;
  15150. var dashshft = 0;
  15151. var curshft = 0;
  15152. var p = 0;
  15153. var i = 0;
  15154. var j = 0;
  15155. for (i = 0; i < points.length - 1; i++) {
  15156. points[i + 1].subtractToRef(points[i], curvect);
  15157. lg += curvect.length();
  15158. }
  15159. shft = lg / nbSeg;
  15160. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15161. for (i = 0; i < points.length - 1; i++) {
  15162. points[i + 1].subtractToRef(points[i], curvect);
  15163. nb = Math.floor(curvect.length() / shft);
  15164. curvect.normalize();
  15165. j = 0;
  15166. while (j < nb && p < positions.length) {
  15167. curshft = shft * j;
  15168. positions[p] = points[i].x + curshft * curvect.x;
  15169. positions[p + 1] = points[i].y + curshft * curvect.y;
  15170. positions[p + 2] = points[i].z + curshft * curvect.z;
  15171. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15172. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15173. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15174. p += 6;
  15175. j++;
  15176. }
  15177. }
  15178. while (p < positions.length) {
  15179. positions[p] = points[i].x;
  15180. positions[p + 1] = points[i].y;
  15181. positions[p + 2] = points[i].z;
  15182. p += 3;
  15183. }
  15184. };
  15185. linesInstance.updateMeshPositions(positionFunction, false);
  15186. return linesInstance;
  15187. }
  15188. // dashed lines creation
  15189. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15190. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15191. vertexData.applyToMesh(dashedLines, updatable);
  15192. dashedLines.dashSize = dashSize;
  15193. dashedLines.gapSize = gapSize;
  15194. return dashedLines;
  15195. };
  15196. // Extrusion
  15197. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15198. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15199. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15200. scale = scale || 1;
  15201. rotation = rotation || 0;
  15202. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15203. return extruded;
  15204. };
  15205. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15206. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15207. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15208. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15209. return extrudedCustom;
  15210. };
  15211. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15212. // extrusion geometry
  15213. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15214. var tangents = path3D.getTangents();
  15215. var normals = path3D.getNormals();
  15216. var binormals = path3D.getBinormals();
  15217. var distances = path3D.getDistances();
  15218. var angle = 0;
  15219. var returnScale = function (i, distance) { return scale; };
  15220. var returnRotation = function (i, distance) { return rotation; };
  15221. var rotate = custom ? rotateFunction : returnRotation;
  15222. var scl = custom ? scaleFunction : returnScale;
  15223. var index = 0;
  15224. for (var i = 0; i < curve.length; i++) {
  15225. var shapePath = new Array();
  15226. var angleStep = rotate(i, distances[i]);
  15227. var scaleRatio = scl(i, distances[i]);
  15228. for (var p = 0; p < shape.length; p++) {
  15229. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15230. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15231. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15232. shapePath.push(rotated);
  15233. }
  15234. shapePaths[index] = shapePath;
  15235. angle += angleStep;
  15236. index++;
  15237. }
  15238. // cap
  15239. var capPath = function (shapePath) {
  15240. var pointCap = Array();
  15241. var barycenter = BABYLON.Vector3.Zero();
  15242. var i;
  15243. for (i = 0; i < shapePath.length; i++) {
  15244. barycenter.addInPlace(shapePath[i]);
  15245. }
  15246. barycenter.scaleInPlace(1 / shapePath.length);
  15247. for (i = 0; i < shapePath.length; i++) {
  15248. pointCap.push(barycenter);
  15249. }
  15250. return pointCap;
  15251. };
  15252. switch (cap) {
  15253. case BABYLON.Mesh.NO_CAP:
  15254. break;
  15255. case BABYLON.Mesh.CAP_START:
  15256. shapePaths.unshift(capPath(shapePaths[0]));
  15257. break;
  15258. case BABYLON.Mesh.CAP_END:
  15259. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15260. break;
  15261. case BABYLON.Mesh.CAP_ALL:
  15262. shapePaths.unshift(capPath(shapePaths[0]));
  15263. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15264. break;
  15265. default:
  15266. break;
  15267. }
  15268. return shapePaths;
  15269. };
  15270. if (instance) {
  15271. var path3D = (instance.path3D).update(curve);
  15272. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15273. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15274. return instance;
  15275. }
  15276. // extruded shape creation
  15277. var path3D = new BABYLON.Path3D(curve);
  15278. var newShapePaths = new Array();
  15279. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15280. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15281. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15282. extrudedGeneric.pathArray = pathArray;
  15283. extrudedGeneric.path3D = path3D;
  15284. extrudedGeneric.cap = cap;
  15285. return extrudedGeneric;
  15286. };
  15287. // Lathe
  15288. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15289. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15290. radius = radius || 1;
  15291. tessellation = tessellation || radius * 60;
  15292. var pi2 = Math.PI * 2;
  15293. var Y = BABYLON.Axis.Y;
  15294. var shapeLathe = new Array();
  15295. // first rotatable point
  15296. var i = 0;
  15297. while (shape[i].x === 0) {
  15298. i++;
  15299. }
  15300. var pt = shape[i];
  15301. for (i = 0; i < shape.length; i++) {
  15302. shapeLathe.push(shape[i].subtract(pt));
  15303. }
  15304. // circle path
  15305. var step = pi2 / tessellation;
  15306. var rotated;
  15307. var path = new Array();
  15308. ;
  15309. for (i = 0; i < tessellation; i++) {
  15310. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15311. path.push(rotated);
  15312. }
  15313. path.push(path[0]);
  15314. // extrusion
  15315. var scaleFunction = function () { return 1; };
  15316. var rotateFunction = function () { return 0; };
  15317. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15318. return lathe;
  15319. };
  15320. // Plane & ground
  15321. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15322. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15323. var plane = new Mesh(name, scene);
  15324. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15325. vertexData.applyToMesh(plane, updatable);
  15326. return plane;
  15327. };
  15328. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15329. var ground = new BABYLON.GroundMesh(name, scene);
  15330. ground._setReady(false);
  15331. ground._subdivisions = subdivisions;
  15332. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15333. vertexData.applyToMesh(ground, updatable);
  15334. ground._setReady(true);
  15335. return ground;
  15336. };
  15337. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15338. var tiledGround = new Mesh(name, scene);
  15339. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15340. vertexData.applyToMesh(tiledGround, updatable);
  15341. return tiledGround;
  15342. };
  15343. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15344. var ground = new BABYLON.GroundMesh(name, scene);
  15345. ground._subdivisions = subdivisions;
  15346. ground._setReady(false);
  15347. var onload = function (img) {
  15348. // Getting height map data
  15349. var canvas = document.createElement("canvas");
  15350. var context = canvas.getContext("2d");
  15351. var heightMapWidth = img.width;
  15352. var heightMapHeight = img.height;
  15353. canvas.width = heightMapWidth;
  15354. canvas.height = heightMapHeight;
  15355. context.drawImage(img, 0, 0);
  15356. // Create VertexData from map data
  15357. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15358. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15359. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15360. vertexData.applyToMesh(ground, updatable);
  15361. ground._setReady(true);
  15362. //execute ready callback, if set
  15363. if (onReady) {
  15364. onReady(ground);
  15365. }
  15366. };
  15367. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15368. return ground;
  15369. };
  15370. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15371. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15372. if (tubeInstance === void 0) { tubeInstance = null; }
  15373. // tube geometry
  15374. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15375. var tangents = path3D.getTangents();
  15376. var normals = path3D.getNormals();
  15377. var distances = path3D.getDistances();
  15378. var pi2 = Math.PI * 2;
  15379. var step = pi2 / tessellation;
  15380. var returnRadius = function (i, distance) { return radius; };
  15381. var radiusFunctionFinal = radiusFunction || returnRadius;
  15382. var circlePath;
  15383. var rad;
  15384. var normal;
  15385. var rotated;
  15386. var rotationMatrix;
  15387. var index = 0;
  15388. for (var i = 0; i < path.length; i++) {
  15389. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15390. circlePath = Array(); // current circle array
  15391. normal = normals[i]; // current normal
  15392. for (var t = 0; t < tessellation; t++) {
  15393. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15394. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15395. circlePath.push(rotated);
  15396. }
  15397. circlePath.push(circlePath[0]);
  15398. circlePaths[index] = circlePath;
  15399. index++;
  15400. }
  15401. // cap
  15402. var capPath = function (nbPoints, pathIndex) {
  15403. var pointCap = Array();
  15404. for (var i = 0; i < nbPoints; i++) {
  15405. pointCap.push(path[pathIndex]);
  15406. }
  15407. return pointCap;
  15408. };
  15409. switch (cap) {
  15410. case BABYLON.Mesh.NO_CAP:
  15411. break;
  15412. case BABYLON.Mesh.CAP_START:
  15413. circlePaths.unshift(capPath(tessellation + 1, 0));
  15414. break;
  15415. case BABYLON.Mesh.CAP_END:
  15416. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15417. break;
  15418. case BABYLON.Mesh.CAP_ALL:
  15419. circlePaths.unshift(capPath(tessellation + 1, 0));
  15420. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15421. break;
  15422. default:
  15423. break;
  15424. }
  15425. return circlePaths;
  15426. };
  15427. if (tubeInstance) {
  15428. var path3D = (tubeInstance.path3D).update(path);
  15429. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15430. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15431. return tubeInstance;
  15432. }
  15433. // tube creation
  15434. var path3D = new BABYLON.Path3D(path);
  15435. var newPathArray = new Array();
  15436. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15437. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15438. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15439. tube.pathArray = pathArray;
  15440. tube.path3D = path3D;
  15441. tube.tessellation = tessellation;
  15442. tube.cap = cap;
  15443. return tube;
  15444. };
  15445. // Decals
  15446. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15447. if (angle === void 0) { angle = 0; }
  15448. var indices = sourceMesh.getIndices();
  15449. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15450. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15451. // Getting correct rotation
  15452. if (!normal) {
  15453. var target = new BABYLON.Vector3(0, 0, 1);
  15454. var camera = sourceMesh.getScene().activeCamera;
  15455. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15456. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15457. }
  15458. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15459. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15460. var pitch = Math.atan2(normal.y, len);
  15461. // Matrix
  15462. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15463. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15464. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15465. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15466. var vertexData = new BABYLON.VertexData();
  15467. vertexData.indices = [];
  15468. vertexData.positions = [];
  15469. vertexData.normals = [];
  15470. vertexData.uvs = [];
  15471. var currentVertexDataIndex = 0;
  15472. var extractDecalVector3 = function (indexId) {
  15473. var vertexId = indices[indexId];
  15474. var result = new BABYLON.PositionNormalVertex();
  15475. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15476. // Send vector to decal local world
  15477. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15478. // Get normal
  15479. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15480. return result;
  15481. };
  15482. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15483. var clip = function (vertices, axis) {
  15484. if (vertices.length === 0) {
  15485. return vertices;
  15486. }
  15487. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15488. var clipVertices = function (v0, v1) {
  15489. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15490. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15491. };
  15492. var result = new Array();
  15493. for (var index = 0; index < vertices.length; index += 3) {
  15494. var v1Out;
  15495. var v2Out;
  15496. var v3Out;
  15497. var total = 0;
  15498. var nV1, nV2, nV3, nV4;
  15499. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15500. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15501. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15502. v1Out = d1 > 0;
  15503. v2Out = d2 > 0;
  15504. v3Out = d3 > 0;
  15505. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15506. switch (total) {
  15507. case 0:
  15508. result.push(vertices[index]);
  15509. result.push(vertices[index + 1]);
  15510. result.push(vertices[index + 2]);
  15511. break;
  15512. case 1:
  15513. if (v1Out) {
  15514. nV1 = vertices[index + 1];
  15515. nV2 = vertices[index + 2];
  15516. nV3 = clipVertices(vertices[index], nV1);
  15517. nV4 = clipVertices(vertices[index], nV2);
  15518. }
  15519. if (v2Out) {
  15520. nV1 = vertices[index];
  15521. nV2 = vertices[index + 2];
  15522. nV3 = clipVertices(vertices[index + 1], nV1);
  15523. nV4 = clipVertices(vertices[index + 1], nV2);
  15524. result.push(nV3);
  15525. result.push(nV2.clone());
  15526. result.push(nV1.clone());
  15527. result.push(nV2.clone());
  15528. result.push(nV3.clone());
  15529. result.push(nV4);
  15530. break;
  15531. }
  15532. if (v3Out) {
  15533. nV1 = vertices[index];
  15534. nV2 = vertices[index + 1];
  15535. nV3 = clipVertices(vertices[index + 2], nV1);
  15536. nV4 = clipVertices(vertices[index + 2], nV2);
  15537. }
  15538. result.push(nV1.clone());
  15539. result.push(nV2.clone());
  15540. result.push(nV3);
  15541. result.push(nV4);
  15542. result.push(nV3.clone());
  15543. result.push(nV2.clone());
  15544. break;
  15545. case 2:
  15546. if (!v1Out) {
  15547. nV1 = vertices[index].clone();
  15548. nV2 = clipVertices(nV1, vertices[index + 1]);
  15549. nV3 = clipVertices(nV1, vertices[index + 2]);
  15550. result.push(nV1);
  15551. result.push(nV2);
  15552. result.push(nV3);
  15553. }
  15554. if (!v2Out) {
  15555. nV1 = vertices[index + 1].clone();
  15556. nV2 = clipVertices(nV1, vertices[index + 2]);
  15557. nV3 = clipVertices(nV1, vertices[index]);
  15558. result.push(nV1);
  15559. result.push(nV2);
  15560. result.push(nV3);
  15561. }
  15562. if (!v3Out) {
  15563. nV1 = vertices[index + 2].clone();
  15564. nV2 = clipVertices(nV1, vertices[index]);
  15565. nV3 = clipVertices(nV1, vertices[index + 1]);
  15566. result.push(nV1);
  15567. result.push(nV2);
  15568. result.push(nV3);
  15569. }
  15570. break;
  15571. case 3:
  15572. break;
  15573. }
  15574. }
  15575. return result;
  15576. };
  15577. for (var index = 0; index < indices.length; index += 3) {
  15578. var faceVertices = new Array();
  15579. faceVertices.push(extractDecalVector3(index));
  15580. faceVertices.push(extractDecalVector3(index + 1));
  15581. faceVertices.push(extractDecalVector3(index + 2));
  15582. // Clip
  15583. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15584. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15585. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15586. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15587. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15588. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15589. if (faceVertices.length === 0) {
  15590. continue;
  15591. }
  15592. // Add UVs and get back to world
  15593. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15594. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15595. var vertex = faceVertices[vIndex];
  15596. vertexData.indices.push(currentVertexDataIndex);
  15597. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15598. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15599. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15600. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15601. currentVertexDataIndex++;
  15602. }
  15603. }
  15604. // Return mesh
  15605. var decal = new Mesh(name, sourceMesh.getScene());
  15606. vertexData.applyToMesh(decal);
  15607. decal.position = position.clone();
  15608. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15609. return decal;
  15610. };
  15611. // Tools
  15612. Mesh.MinMax = function (meshes) {
  15613. var minVector = null;
  15614. var maxVector = null;
  15615. for (var i in meshes) {
  15616. var mesh = meshes[i];
  15617. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15618. if (!minVector) {
  15619. minVector = boundingBox.minimumWorld;
  15620. maxVector = boundingBox.maximumWorld;
  15621. continue;
  15622. }
  15623. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15624. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15625. }
  15626. return {
  15627. min: minVector,
  15628. max: maxVector
  15629. };
  15630. };
  15631. Mesh.Center = function (meshesOrMinMaxVector) {
  15632. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15633. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15634. };
  15635. /**
  15636. * Merge the array of meshes into a single mesh for performance reasons.
  15637. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15638. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15639. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15640. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15641. */
  15642. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15643. if (disposeSource === void 0) { disposeSource = true; }
  15644. if (!allow32BitsIndices) {
  15645. var totalVertices = 0;
  15646. // Counting vertices
  15647. for (var index = 0; index < meshes.length; index++) {
  15648. if (meshes[index]) {
  15649. totalVertices += meshes[index].getTotalVertices();
  15650. if (totalVertices > 65536) {
  15651. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15652. return null;
  15653. }
  15654. }
  15655. }
  15656. }
  15657. // Merge
  15658. var vertexData;
  15659. var otherVertexData;
  15660. var source;
  15661. for (index = 0; index < meshes.length; index++) {
  15662. if (meshes[index]) {
  15663. meshes[index].computeWorldMatrix(true);
  15664. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15665. otherVertexData.transform(meshes[index].getWorldMatrix());
  15666. if (vertexData) {
  15667. vertexData.merge(otherVertexData);
  15668. }
  15669. else {
  15670. vertexData = otherVertexData;
  15671. source = meshes[index];
  15672. }
  15673. }
  15674. }
  15675. if (!meshSubclass) {
  15676. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15677. }
  15678. vertexData.applyToMesh(meshSubclass);
  15679. // Setting properties
  15680. meshSubclass.material = source.material;
  15681. meshSubclass.checkCollisions = source.checkCollisions;
  15682. // Cleaning
  15683. if (disposeSource) {
  15684. for (index = 0; index < meshes.length; index++) {
  15685. if (meshes[index]) {
  15686. meshes[index].dispose();
  15687. }
  15688. }
  15689. }
  15690. return meshSubclass;
  15691. };
  15692. // Consts
  15693. Mesh._FRONTSIDE = 0;
  15694. Mesh._BACKSIDE = 1;
  15695. Mesh._DOUBLESIDE = 2;
  15696. Mesh._DEFAULTSIDE = 0;
  15697. Mesh._NO_CAP = 0;
  15698. Mesh._CAP_START = 1;
  15699. Mesh._CAP_END = 2;
  15700. Mesh._CAP_ALL = 3;
  15701. return Mesh;
  15702. })(BABYLON.AbstractMesh);
  15703. BABYLON.Mesh = Mesh;
  15704. })(BABYLON || (BABYLON = {}));
  15705. //# sourceMappingURL=babylon.mesh.js.map
  15706. var BABYLON;
  15707. (function (BABYLON) {
  15708. var SubMesh = (function () {
  15709. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15710. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15711. this.materialIndex = materialIndex;
  15712. this.verticesStart = verticesStart;
  15713. this.verticesCount = verticesCount;
  15714. this.indexStart = indexStart;
  15715. this.indexCount = indexCount;
  15716. this._renderId = 0;
  15717. this._mesh = mesh;
  15718. this._renderingMesh = renderingMesh || mesh;
  15719. mesh.subMeshes.push(this);
  15720. this._trianglePlanes = [];
  15721. this._id = mesh.subMeshes.length - 1;
  15722. if (createBoundingBox) {
  15723. this.refreshBoundingInfo();
  15724. mesh.computeWorldMatrix(true);
  15725. }
  15726. }
  15727. SubMesh.prototype.getBoundingInfo = function () {
  15728. return this._boundingInfo;
  15729. };
  15730. SubMesh.prototype.getMesh = function () {
  15731. return this._mesh;
  15732. };
  15733. SubMesh.prototype.getRenderingMesh = function () {
  15734. return this._renderingMesh;
  15735. };
  15736. SubMesh.prototype.getMaterial = function () {
  15737. var rootMaterial = this._renderingMesh.material;
  15738. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15739. var multiMaterial = rootMaterial;
  15740. return multiMaterial.getSubMaterial(this.materialIndex);
  15741. }
  15742. if (!rootMaterial) {
  15743. return this._mesh.getScene().defaultMaterial;
  15744. }
  15745. return rootMaterial;
  15746. };
  15747. // Methods
  15748. SubMesh.prototype.refreshBoundingInfo = function () {
  15749. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15750. if (!data) {
  15751. this._boundingInfo = this._mesh._boundingInfo;
  15752. return;
  15753. }
  15754. var indices = this._renderingMesh.getIndices();
  15755. var extend;
  15756. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15757. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15758. }
  15759. else {
  15760. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15761. }
  15762. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15763. };
  15764. SubMesh.prototype._checkCollision = function (collider) {
  15765. return this._boundingInfo._checkCollision(collider);
  15766. };
  15767. SubMesh.prototype.updateBoundingInfo = function (world) {
  15768. if (!this._boundingInfo) {
  15769. this.refreshBoundingInfo();
  15770. }
  15771. this._boundingInfo._update(world);
  15772. };
  15773. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15774. return this._boundingInfo.isInFrustum(frustumPlanes);
  15775. };
  15776. SubMesh.prototype.render = function () {
  15777. this._renderingMesh.render(this);
  15778. };
  15779. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15780. if (!this._linesIndexBuffer) {
  15781. var linesIndices = [];
  15782. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15783. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15784. }
  15785. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15786. this.linesIndexCount = linesIndices.length;
  15787. }
  15788. return this._linesIndexBuffer;
  15789. };
  15790. SubMesh.prototype.canIntersects = function (ray) {
  15791. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15792. };
  15793. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15794. var intersectInfo = null;
  15795. // Triangles test
  15796. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15797. var p0 = positions[indices[index]];
  15798. var p1 = positions[indices[index + 1]];
  15799. var p2 = positions[indices[index + 2]];
  15800. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15801. if (currentIntersectInfo) {
  15802. if (currentIntersectInfo.distance < 0) {
  15803. continue;
  15804. }
  15805. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15806. intersectInfo = currentIntersectInfo;
  15807. intersectInfo.faceId = index / 3;
  15808. if (fastCheck) {
  15809. break;
  15810. }
  15811. }
  15812. }
  15813. }
  15814. return intersectInfo;
  15815. };
  15816. // Clone
  15817. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15818. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15819. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15820. return result;
  15821. };
  15822. // Dispose
  15823. SubMesh.prototype.dispose = function () {
  15824. if (this._linesIndexBuffer) {
  15825. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15826. this._linesIndexBuffer = null;
  15827. }
  15828. // Remove from mesh
  15829. var index = this._mesh.subMeshes.indexOf(this);
  15830. this._mesh.subMeshes.splice(index, 1);
  15831. };
  15832. // Statics
  15833. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15834. var minVertexIndex = Number.MAX_VALUE;
  15835. var maxVertexIndex = -Number.MAX_VALUE;
  15836. renderingMesh = renderingMesh || mesh;
  15837. var indices = renderingMesh.getIndices();
  15838. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15839. var vertexIndex = indices[index];
  15840. if (vertexIndex < minVertexIndex)
  15841. minVertexIndex = vertexIndex;
  15842. if (vertexIndex > maxVertexIndex)
  15843. maxVertexIndex = vertexIndex;
  15844. }
  15845. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15846. };
  15847. return SubMesh;
  15848. })();
  15849. BABYLON.SubMesh = SubMesh;
  15850. })(BABYLON || (BABYLON = {}));
  15851. //# sourceMappingURL=babylon.subMesh.js.map
  15852. var BABYLON;
  15853. (function (BABYLON) {
  15854. var BaseTexture = (function () {
  15855. function BaseTexture(scene) {
  15856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15857. this.hasAlpha = false;
  15858. this.getAlphaFromRGB = false;
  15859. this.level = 1;
  15860. this.isCube = false;
  15861. this.isRenderTarget = false;
  15862. this.animations = new Array();
  15863. this.coordinatesIndex = 0;
  15864. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15865. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15866. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15867. this.anisotropicFilteringLevel = 4;
  15868. this._scene = scene;
  15869. this._scene.textures.push(this);
  15870. }
  15871. BaseTexture.prototype.getScene = function () {
  15872. return this._scene;
  15873. };
  15874. BaseTexture.prototype.getTextureMatrix = function () {
  15875. return null;
  15876. };
  15877. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15878. return null;
  15879. };
  15880. BaseTexture.prototype.getInternalTexture = function () {
  15881. return this._texture;
  15882. };
  15883. BaseTexture.prototype.isReady = function () {
  15884. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15885. return true;
  15886. }
  15887. if (this._texture) {
  15888. return this._texture.isReady;
  15889. }
  15890. return false;
  15891. };
  15892. BaseTexture.prototype.getSize = function () {
  15893. if (this._texture._width) {
  15894. return { width: this._texture._width, height: this._texture._height };
  15895. }
  15896. if (this._texture._size) {
  15897. return { width: this._texture._size, height: this._texture._size };
  15898. }
  15899. return { width: 0, height: 0 };
  15900. };
  15901. BaseTexture.prototype.getBaseSize = function () {
  15902. if (!this.isReady())
  15903. return { width: 0, height: 0 };
  15904. if (this._texture._size) {
  15905. return { width: this._texture._size, height: this._texture._size };
  15906. }
  15907. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15908. };
  15909. BaseTexture.prototype.scale = function (ratio) {
  15910. };
  15911. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15912. get: function () {
  15913. return false;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15919. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15920. for (var index = 0; index < texturesCache.length; index++) {
  15921. var texturesCacheEntry = texturesCache[index];
  15922. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15923. texturesCache.splice(index, 1);
  15924. return;
  15925. }
  15926. }
  15927. };
  15928. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15929. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15930. for (var index = 0; index < texturesCache.length; index++) {
  15931. var texturesCacheEntry = texturesCache[index];
  15932. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15933. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15934. texturesCacheEntry.references++;
  15935. return texturesCacheEntry;
  15936. }
  15937. }
  15938. }
  15939. return null;
  15940. };
  15941. BaseTexture.prototype.delayLoad = function () {
  15942. };
  15943. BaseTexture.prototype.releaseInternalTexture = function () {
  15944. if (!this._texture) {
  15945. return;
  15946. }
  15947. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15948. this._texture.references--;
  15949. // Final reference ?
  15950. if (this._texture.references === 0) {
  15951. var index = texturesCache.indexOf(this._texture);
  15952. texturesCache.splice(index, 1);
  15953. this._scene.getEngine()._releaseTexture(this._texture);
  15954. delete this._texture;
  15955. }
  15956. };
  15957. BaseTexture.prototype.clone = function () {
  15958. return null;
  15959. };
  15960. BaseTexture.prototype.dispose = function () {
  15961. // Remove from scene
  15962. var index = this._scene.textures.indexOf(this);
  15963. if (index >= 0) {
  15964. this._scene.textures.splice(index, 1);
  15965. }
  15966. if (this._texture === undefined) {
  15967. return;
  15968. }
  15969. this.releaseInternalTexture();
  15970. // Callback
  15971. if (this.onDispose) {
  15972. this.onDispose();
  15973. }
  15974. };
  15975. return BaseTexture;
  15976. })();
  15977. BABYLON.BaseTexture = BaseTexture;
  15978. })(BABYLON || (BABYLON = {}));
  15979. //# sourceMappingURL=babylon.baseTexture.js.map
  15980. var BABYLON;
  15981. (function (BABYLON) {
  15982. var Texture = (function (_super) {
  15983. __extends(Texture, _super);
  15984. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  15985. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15986. if (onLoad === void 0) { onLoad = null; }
  15987. if (onError === void 0) { onError = null; }
  15988. if (buffer === void 0) { buffer = null; }
  15989. if (deleteBuffer === void 0) { deleteBuffer = false; }
  15990. _super.call(this, scene);
  15991. this.uOffset = 0;
  15992. this.vOffset = 0;
  15993. this.uScale = 1.0;
  15994. this.vScale = 1.0;
  15995. this.uAng = 0;
  15996. this.vAng = 0;
  15997. this.wAng = 0;
  15998. this.name = url;
  15999. this.url = url;
  16000. this._noMipmap = noMipmap;
  16001. this._invertY = invertY;
  16002. this._samplingMode = samplingMode;
  16003. this._buffer = buffer;
  16004. this._deleteBuffer = deleteBuffer;
  16005. if (!url) {
  16006. return;
  16007. }
  16008. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16009. if (!this._texture) {
  16010. if (!scene.useDelayedTextureLoading) {
  16011. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16012. if (deleteBuffer) {
  16013. delete this._buffer;
  16014. }
  16015. }
  16016. else {
  16017. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16018. }
  16019. }
  16020. else {
  16021. BABYLON.Tools.SetImmediate(function () {
  16022. if (onLoad) {
  16023. onLoad();
  16024. }
  16025. });
  16026. }
  16027. }
  16028. Texture.prototype.delayLoad = function () {
  16029. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16030. return;
  16031. }
  16032. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16033. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16034. if (!this._texture) {
  16035. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16036. if (this._deleteBuffer) {
  16037. delete this._buffer;
  16038. }
  16039. }
  16040. };
  16041. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16042. if (!this._texture) {
  16043. return;
  16044. }
  16045. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16046. };
  16047. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16048. x -= this.uOffset + 0.5;
  16049. y -= this.vOffset + 0.5;
  16050. z -= 0.5;
  16051. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16052. t.x *= this.uScale;
  16053. t.y *= this.vScale;
  16054. t.x += 0.5;
  16055. t.y += 0.5;
  16056. t.z += 0.5;
  16057. };
  16058. Texture.prototype.getTextureMatrix = function () {
  16059. if (this.uOffset === this._cachedUOffset &&
  16060. this.vOffset === this._cachedVOffset &&
  16061. this.uScale === this._cachedUScale &&
  16062. this.vScale === this._cachedVScale &&
  16063. this.uAng === this._cachedUAng &&
  16064. this.vAng === this._cachedVAng &&
  16065. this.wAng === this._cachedWAng) {
  16066. return this._cachedTextureMatrix;
  16067. }
  16068. this._cachedUOffset = this.uOffset;
  16069. this._cachedVOffset = this.vOffset;
  16070. this._cachedUScale = this.uScale;
  16071. this._cachedVScale = this.vScale;
  16072. this._cachedUAng = this.uAng;
  16073. this._cachedVAng = this.vAng;
  16074. this._cachedWAng = this.wAng;
  16075. if (!this._cachedTextureMatrix) {
  16076. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16077. this._rowGenerationMatrix = new BABYLON.Matrix();
  16078. this._t0 = BABYLON.Vector3.Zero();
  16079. this._t1 = BABYLON.Vector3.Zero();
  16080. this._t2 = BABYLON.Vector3.Zero();
  16081. }
  16082. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16083. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16084. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16085. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16086. this._t1.subtractInPlace(this._t0);
  16087. this._t2.subtractInPlace(this._t0);
  16088. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16089. this._cachedTextureMatrix.m[0] = this._t1.x;
  16090. this._cachedTextureMatrix.m[1] = this._t1.y;
  16091. this._cachedTextureMatrix.m[2] = this._t1.z;
  16092. this._cachedTextureMatrix.m[4] = this._t2.x;
  16093. this._cachedTextureMatrix.m[5] = this._t2.y;
  16094. this._cachedTextureMatrix.m[6] = this._t2.z;
  16095. this._cachedTextureMatrix.m[8] = this._t0.x;
  16096. this._cachedTextureMatrix.m[9] = this._t0.y;
  16097. this._cachedTextureMatrix.m[10] = this._t0.z;
  16098. return this._cachedTextureMatrix;
  16099. };
  16100. Texture.prototype.getReflectionTextureMatrix = function () {
  16101. if (this.uOffset === this._cachedUOffset &&
  16102. this.vOffset === this._cachedVOffset &&
  16103. this.uScale === this._cachedUScale &&
  16104. this.vScale === this._cachedVScale &&
  16105. this.coordinatesMode === this._cachedCoordinatesMode) {
  16106. return this._cachedTextureMatrix;
  16107. }
  16108. if (!this._cachedTextureMatrix) {
  16109. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16110. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16111. }
  16112. this._cachedCoordinatesMode = this.coordinatesMode;
  16113. switch (this.coordinatesMode) {
  16114. case Texture.SPHERICAL_MODE:
  16115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16116. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16117. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16118. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16119. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16120. break;
  16121. case Texture.PLANAR_MODE:
  16122. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16123. this._cachedTextureMatrix[0] = this.uScale;
  16124. this._cachedTextureMatrix[5] = this.vScale;
  16125. this._cachedTextureMatrix[12] = this.uOffset;
  16126. this._cachedTextureMatrix[13] = this.vOffset;
  16127. break;
  16128. case Texture.PROJECTION_MODE:
  16129. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16130. this._projectionModeMatrix.m[0] = 0.5;
  16131. this._projectionModeMatrix.m[5] = -0.5;
  16132. this._projectionModeMatrix.m[10] = 0.0;
  16133. this._projectionModeMatrix.m[12] = 0.5;
  16134. this._projectionModeMatrix.m[13] = 0.5;
  16135. this._projectionModeMatrix.m[14] = 1.0;
  16136. this._projectionModeMatrix.m[15] = 1.0;
  16137. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16138. break;
  16139. default:
  16140. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16141. break;
  16142. }
  16143. return this._cachedTextureMatrix;
  16144. };
  16145. Texture.prototype.clone = function () {
  16146. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16147. // Base texture
  16148. newTexture.hasAlpha = this.hasAlpha;
  16149. newTexture.level = this.level;
  16150. newTexture.wrapU = this.wrapU;
  16151. newTexture.wrapV = this.wrapV;
  16152. newTexture.coordinatesIndex = this.coordinatesIndex;
  16153. newTexture.coordinatesMode = this.coordinatesMode;
  16154. // Texture
  16155. newTexture.uOffset = this.uOffset;
  16156. newTexture.vOffset = this.vOffset;
  16157. newTexture.uScale = this.uScale;
  16158. newTexture.vScale = this.vScale;
  16159. newTexture.uAng = this.uAng;
  16160. newTexture.vAng = this.vAng;
  16161. newTexture.wAng = this.wAng;
  16162. return newTexture;
  16163. };
  16164. // Statics
  16165. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16166. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16167. if (onLoad === void 0) { onLoad = null; }
  16168. if (onError === void 0) { onError = null; }
  16169. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16170. };
  16171. // Constants
  16172. Texture.NEAREST_SAMPLINGMODE = 1;
  16173. Texture.BILINEAR_SAMPLINGMODE = 2;
  16174. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16175. Texture.EXPLICIT_MODE = 0;
  16176. Texture.SPHERICAL_MODE = 1;
  16177. Texture.PLANAR_MODE = 2;
  16178. Texture.CUBIC_MODE = 3;
  16179. Texture.PROJECTION_MODE = 4;
  16180. Texture.SKYBOX_MODE = 5;
  16181. Texture.CLAMP_ADDRESSMODE = 0;
  16182. Texture.WRAP_ADDRESSMODE = 1;
  16183. Texture.MIRROR_ADDRESSMODE = 2;
  16184. return Texture;
  16185. })(BABYLON.BaseTexture);
  16186. BABYLON.Texture = Texture;
  16187. })(BABYLON || (BABYLON = {}));
  16188. //# sourceMappingURL=babylon.texture.js.map
  16189. var BABYLON;
  16190. (function (BABYLON) {
  16191. var CubeTexture = (function (_super) {
  16192. __extends(CubeTexture, _super);
  16193. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16194. _super.call(this, scene);
  16195. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16196. this.name = rootUrl;
  16197. this.url = rootUrl;
  16198. this._noMipmap = noMipmap;
  16199. this.hasAlpha = false;
  16200. this._texture = this._getFromCache(rootUrl, noMipmap);
  16201. if (!extensions) {
  16202. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16203. }
  16204. this._extensions = extensions;
  16205. if (!this._texture) {
  16206. if (!scene.useDelayedTextureLoading) {
  16207. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16208. }
  16209. else {
  16210. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16211. }
  16212. }
  16213. this.isCube = true;
  16214. this._textureMatrix = BABYLON.Matrix.Identity();
  16215. }
  16216. CubeTexture.prototype.clone = function () {
  16217. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16218. // Base texture
  16219. newTexture.level = this.level;
  16220. newTexture.wrapU = this.wrapU;
  16221. newTexture.wrapV = this.wrapV;
  16222. newTexture.coordinatesIndex = this.coordinatesIndex;
  16223. newTexture.coordinatesMode = this.coordinatesMode;
  16224. return newTexture;
  16225. };
  16226. // Methods
  16227. CubeTexture.prototype.delayLoad = function () {
  16228. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16229. return;
  16230. }
  16231. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16232. this._texture = this._getFromCache(this.url, this._noMipmap);
  16233. if (!this._texture) {
  16234. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16235. }
  16236. };
  16237. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16238. return this._textureMatrix;
  16239. };
  16240. return CubeTexture;
  16241. })(BABYLON.BaseTexture);
  16242. BABYLON.CubeTexture = CubeTexture;
  16243. })(BABYLON || (BABYLON = {}));
  16244. //# sourceMappingURL=babylon.cubeTexture.js.map
  16245. var BABYLON;
  16246. (function (BABYLON) {
  16247. var RenderTargetTexture = (function (_super) {
  16248. __extends(RenderTargetTexture, _super);
  16249. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16250. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16251. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16252. _super.call(this, null, scene, !generateMipMaps);
  16253. this.renderList = new Array();
  16254. this.renderParticles = true;
  16255. this.renderSprites = false;
  16256. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16257. this._currentRefreshId = -1;
  16258. this._refreshRate = 1;
  16259. this.name = name;
  16260. this.isRenderTarget = true;
  16261. this._size = size;
  16262. this._generateMipMaps = generateMipMaps;
  16263. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16264. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16265. // Rendering groups
  16266. this._renderingManager = new BABYLON.RenderingManager(scene);
  16267. }
  16268. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16269. this._currentRefreshId = -1;
  16270. };
  16271. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16272. get: function () {
  16273. return this._refreshRate;
  16274. },
  16275. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16276. set: function (value) {
  16277. this._refreshRate = value;
  16278. this.resetRefreshCounter();
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. RenderTargetTexture.prototype._shouldRender = function () {
  16284. if (this._currentRefreshId === -1) {
  16285. this._currentRefreshId = 1;
  16286. return true;
  16287. }
  16288. if (this.refreshRate === this._currentRefreshId) {
  16289. this._currentRefreshId = 1;
  16290. return true;
  16291. }
  16292. this._currentRefreshId++;
  16293. return false;
  16294. };
  16295. RenderTargetTexture.prototype.isReady = function () {
  16296. if (!this.getScene().renderTargetsEnabled) {
  16297. return false;
  16298. }
  16299. return _super.prototype.isReady.call(this);
  16300. };
  16301. RenderTargetTexture.prototype.getRenderSize = function () {
  16302. return this._size;
  16303. };
  16304. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16305. get: function () {
  16306. return true;
  16307. },
  16308. enumerable: true,
  16309. configurable: true
  16310. });
  16311. RenderTargetTexture.prototype.scale = function (ratio) {
  16312. var newSize = this._size * ratio;
  16313. this.resize(newSize, this._generateMipMaps);
  16314. };
  16315. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16316. this.releaseInternalTexture();
  16317. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16318. };
  16319. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16320. var scene = this.getScene();
  16321. var engine = scene.getEngine();
  16322. if (this._waitingRenderList) {
  16323. this.renderList = [];
  16324. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16325. var id = this._waitingRenderList[index];
  16326. this.renderList.push(scene.getMeshByID(id));
  16327. }
  16328. delete this._waitingRenderList;
  16329. }
  16330. if (this.renderList && this.renderList.length === 0) {
  16331. return;
  16332. }
  16333. // Bind
  16334. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16335. engine.bindFramebuffer(this._texture);
  16336. }
  16337. this._renderingManager.reset();
  16338. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16339. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16340. var mesh = currentRenderList[meshIndex];
  16341. if (mesh) {
  16342. if (!mesh.isReady()) {
  16343. // Reset _currentRefreshId
  16344. this.resetRefreshCounter();
  16345. continue;
  16346. }
  16347. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16348. mesh._activate(scene.getRenderId());
  16349. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16350. var subMesh = mesh.subMeshes[subIndex];
  16351. scene._activeIndices += subMesh.indexCount;
  16352. this._renderingManager.dispatch(subMesh);
  16353. }
  16354. }
  16355. }
  16356. }
  16357. if (this.onBeforeRender) {
  16358. this.onBeforeRender();
  16359. }
  16360. // Clear
  16361. if (this.onClear) {
  16362. this.onClear(engine);
  16363. }
  16364. else {
  16365. engine.clear(scene.clearColor, true, true);
  16366. }
  16367. if (!this._doNotChangeAspectRatio) {
  16368. scene.updateTransformMatrix(true);
  16369. }
  16370. // Render
  16371. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16372. if (useCameraPostProcess) {
  16373. scene.postProcessManager._finalizeFrame(false, this._texture);
  16374. }
  16375. if (!this._doNotChangeAspectRatio) {
  16376. scene.updateTransformMatrix(true);
  16377. }
  16378. if (this.onAfterRender) {
  16379. this.onAfterRender();
  16380. }
  16381. // Dump ?
  16382. if (dumpForDebug) {
  16383. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16384. }
  16385. // Unbind
  16386. engine.unBindFramebuffer(this._texture);
  16387. if (this.onAfterUnbind) {
  16388. this.onAfterUnbind();
  16389. }
  16390. };
  16391. RenderTargetTexture.prototype.clone = function () {
  16392. var textureSize = this.getSize();
  16393. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16394. // Base texture
  16395. newTexture.hasAlpha = this.hasAlpha;
  16396. newTexture.level = this.level;
  16397. // RenderTarget Texture
  16398. newTexture.coordinatesMode = this.coordinatesMode;
  16399. newTexture.renderList = this.renderList.slice(0);
  16400. return newTexture;
  16401. };
  16402. return RenderTargetTexture;
  16403. })(BABYLON.Texture);
  16404. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16405. })(BABYLON || (BABYLON = {}));
  16406. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16407. var BABYLON;
  16408. (function (BABYLON) {
  16409. var ProceduralTexture = (function (_super) {
  16410. __extends(ProceduralTexture, _super);
  16411. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16412. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16413. _super.call(this, null, scene, !generateMipMaps);
  16414. this._currentRefreshId = -1;
  16415. this._refreshRate = 1;
  16416. this._vertexDeclaration = [2];
  16417. this._vertexStrideSize = 2 * 4;
  16418. this._uniforms = new Array();
  16419. this._samplers = new Array();
  16420. this._textures = new Array();
  16421. this._floats = new Array();
  16422. this._floatsArrays = {};
  16423. this._colors3 = new Array();
  16424. this._colors4 = new Array();
  16425. this._vectors2 = new Array();
  16426. this._vectors3 = new Array();
  16427. this._matrices = new Array();
  16428. this._fallbackTextureUsed = false;
  16429. scene._proceduralTextures.push(this);
  16430. this.name = name;
  16431. this.isRenderTarget = true;
  16432. this._size = size;
  16433. this._generateMipMaps = generateMipMaps;
  16434. this.setFragment(fragment);
  16435. this._fallbackTexture = fallbackTexture;
  16436. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16437. // VBO
  16438. var vertices = [];
  16439. vertices.push(1, 1);
  16440. vertices.push(-1, 1);
  16441. vertices.push(-1, -1);
  16442. vertices.push(1, -1);
  16443. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16444. // Indices
  16445. var indices = [];
  16446. indices.push(0);
  16447. indices.push(1);
  16448. indices.push(2);
  16449. indices.push(0);
  16450. indices.push(2);
  16451. indices.push(3);
  16452. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16453. }
  16454. ProceduralTexture.prototype.reset = function () {
  16455. if (this._effect === undefined) {
  16456. return;
  16457. }
  16458. var engine = this.getScene().getEngine();
  16459. engine._releaseEffect(this._effect);
  16460. };
  16461. ProceduralTexture.prototype.isReady = function () {
  16462. var _this = this;
  16463. var engine = this.getScene().getEngine();
  16464. var shaders;
  16465. if (!this._fragment) {
  16466. return false;
  16467. }
  16468. if (this._fallbackTextureUsed) {
  16469. return true;
  16470. }
  16471. if (this._fragment.fragmentElement !== undefined) {
  16472. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16473. }
  16474. else {
  16475. shaders = { vertex: "procedural", fragment: this._fragment };
  16476. }
  16477. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16478. _this.releaseInternalTexture();
  16479. if (_this._fallbackTexture) {
  16480. _this._texture = _this._fallbackTexture._texture;
  16481. _this._texture.references++;
  16482. }
  16483. _this._fallbackTextureUsed = true;
  16484. });
  16485. return this._effect.isReady();
  16486. };
  16487. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16488. this._currentRefreshId = -1;
  16489. };
  16490. ProceduralTexture.prototype.setFragment = function (fragment) {
  16491. this._fragment = fragment;
  16492. };
  16493. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16494. get: function () {
  16495. return this._refreshRate;
  16496. },
  16497. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16498. set: function (value) {
  16499. this._refreshRate = value;
  16500. this.resetRefreshCounter();
  16501. },
  16502. enumerable: true,
  16503. configurable: true
  16504. });
  16505. ProceduralTexture.prototype._shouldRender = function () {
  16506. if (!this.isReady() || !this._texture) {
  16507. return false;
  16508. }
  16509. if (this._fallbackTextureUsed) {
  16510. return false;
  16511. }
  16512. if (this._currentRefreshId === -1) {
  16513. this._currentRefreshId = 1;
  16514. return true;
  16515. }
  16516. if (this.refreshRate === this._currentRefreshId) {
  16517. this._currentRefreshId = 1;
  16518. return true;
  16519. }
  16520. this._currentRefreshId++;
  16521. return false;
  16522. };
  16523. ProceduralTexture.prototype.getRenderSize = function () {
  16524. return this._size;
  16525. };
  16526. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16527. if (this._fallbackTextureUsed) {
  16528. return;
  16529. }
  16530. this.releaseInternalTexture();
  16531. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16532. };
  16533. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16534. if (this._uniforms.indexOf(uniformName) === -1) {
  16535. this._uniforms.push(uniformName);
  16536. }
  16537. };
  16538. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16539. if (this._samplers.indexOf(name) === -1) {
  16540. this._samplers.push(name);
  16541. }
  16542. this._textures[name] = texture;
  16543. return this;
  16544. };
  16545. ProceduralTexture.prototype.setFloat = function (name, value) {
  16546. this._checkUniform(name);
  16547. this._floats[name] = value;
  16548. return this;
  16549. };
  16550. ProceduralTexture.prototype.setFloats = function (name, value) {
  16551. this._checkUniform(name);
  16552. this._floatsArrays[name] = value;
  16553. return this;
  16554. };
  16555. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16556. this._checkUniform(name);
  16557. this._colors3[name] = value;
  16558. return this;
  16559. };
  16560. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16561. this._checkUniform(name);
  16562. this._colors4[name] = value;
  16563. return this;
  16564. };
  16565. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16566. this._checkUniform(name);
  16567. this._vectors2[name] = value;
  16568. return this;
  16569. };
  16570. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16571. this._checkUniform(name);
  16572. this._vectors3[name] = value;
  16573. return this;
  16574. };
  16575. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16576. this._checkUniform(name);
  16577. this._matrices[name] = value;
  16578. return this;
  16579. };
  16580. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16581. var scene = this.getScene();
  16582. var engine = scene.getEngine();
  16583. engine.bindFramebuffer(this._texture);
  16584. // Clear
  16585. engine.clear(scene.clearColor, true, true);
  16586. // Render
  16587. engine.enableEffect(this._effect);
  16588. engine.setState(false);
  16589. // Texture
  16590. for (var name in this._textures) {
  16591. this._effect.setTexture(name, this._textures[name]);
  16592. }
  16593. // Float
  16594. for (name in this._floats) {
  16595. this._effect.setFloat(name, this._floats[name]);
  16596. }
  16597. // Floats
  16598. for (name in this._floatsArrays) {
  16599. this._effect.setArray(name, this._floatsArrays[name]);
  16600. }
  16601. // Color3
  16602. for (name in this._colors3) {
  16603. this._effect.setColor3(name, this._colors3[name]);
  16604. }
  16605. // Color4
  16606. for (name in this._colors4) {
  16607. var color = this._colors4[name];
  16608. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16609. }
  16610. // Vector2
  16611. for (name in this._vectors2) {
  16612. this._effect.setVector2(name, this._vectors2[name]);
  16613. }
  16614. // Vector3
  16615. for (name in this._vectors3) {
  16616. this._effect.setVector3(name, this._vectors3[name]);
  16617. }
  16618. // Matrix
  16619. for (name in this._matrices) {
  16620. this._effect.setMatrix(name, this._matrices[name]);
  16621. }
  16622. // VBOs
  16623. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16624. // Draw order
  16625. engine.draw(true, 0, 6);
  16626. // Unbind
  16627. engine.unBindFramebuffer(this._texture);
  16628. };
  16629. ProceduralTexture.prototype.clone = function () {
  16630. var textureSize = this.getSize();
  16631. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16632. // Base texture
  16633. newTexture.hasAlpha = this.hasAlpha;
  16634. newTexture.level = this.level;
  16635. // RenderTarget Texture
  16636. newTexture.coordinatesMode = this.coordinatesMode;
  16637. return newTexture;
  16638. };
  16639. ProceduralTexture.prototype.dispose = function () {
  16640. var index = this.getScene()._proceduralTextures.indexOf(this);
  16641. if (index >= 0) {
  16642. this.getScene()._proceduralTextures.splice(index, 1);
  16643. }
  16644. _super.prototype.dispose.call(this);
  16645. };
  16646. return ProceduralTexture;
  16647. })(BABYLON.Texture);
  16648. BABYLON.ProceduralTexture = ProceduralTexture;
  16649. })(BABYLON || (BABYLON = {}));
  16650. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16651. var BABYLON;
  16652. (function (BABYLON) {
  16653. var MirrorTexture = (function (_super) {
  16654. __extends(MirrorTexture, _super);
  16655. function MirrorTexture(name, size, scene, generateMipMaps) {
  16656. var _this = this;
  16657. _super.call(this, name, size, scene, generateMipMaps, true);
  16658. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16659. this._transformMatrix = BABYLON.Matrix.Zero();
  16660. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16661. this.onBeforeRender = function () {
  16662. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16663. _this._savedViewMatrix = scene.getViewMatrix();
  16664. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16665. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16666. scene.clipPlane = _this.mirrorPlane;
  16667. scene.getEngine().cullBackFaces = false;
  16668. };
  16669. this.onAfterRender = function () {
  16670. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16671. scene.getEngine().cullBackFaces = true;
  16672. delete scene.clipPlane;
  16673. };
  16674. }
  16675. MirrorTexture.prototype.clone = function () {
  16676. var textureSize = this.getSize();
  16677. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16678. // Base texture
  16679. newTexture.hasAlpha = this.hasAlpha;
  16680. newTexture.level = this.level;
  16681. // Mirror Texture
  16682. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16683. newTexture.renderList = this.renderList.slice(0);
  16684. return newTexture;
  16685. };
  16686. return MirrorTexture;
  16687. })(BABYLON.RenderTargetTexture);
  16688. BABYLON.MirrorTexture = MirrorTexture;
  16689. })(BABYLON || (BABYLON = {}));
  16690. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16691. var BABYLON;
  16692. (function (BABYLON) {
  16693. var DynamicTexture = (function (_super) {
  16694. __extends(DynamicTexture, _super);
  16695. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16697. _super.call(this, null, scene, !generateMipMaps);
  16698. this.name = name;
  16699. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16700. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16701. this._generateMipMaps = generateMipMaps;
  16702. if (options.getContext) {
  16703. this._canvas = options;
  16704. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16705. }
  16706. else {
  16707. this._canvas = document.createElement("canvas");
  16708. if (options.width) {
  16709. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16710. }
  16711. else {
  16712. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16713. }
  16714. }
  16715. var textureSize = this.getSize();
  16716. this._canvas.width = textureSize.width;
  16717. this._canvas.height = textureSize.height;
  16718. this._context = this._canvas.getContext("2d");
  16719. }
  16720. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16721. get: function () {
  16722. return true;
  16723. },
  16724. enumerable: true,
  16725. configurable: true
  16726. });
  16727. DynamicTexture.prototype.scale = function (ratio) {
  16728. var textureSize = this.getSize();
  16729. textureSize.width *= ratio;
  16730. textureSize.height *= ratio;
  16731. this._canvas.width = textureSize.width;
  16732. this._canvas.height = textureSize.height;
  16733. this.releaseInternalTexture();
  16734. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16735. };
  16736. DynamicTexture.prototype.getContext = function () {
  16737. return this._context;
  16738. };
  16739. DynamicTexture.prototype.clear = function () {
  16740. var size = this.getSize();
  16741. this._context.fillRect(0, 0, size.width, size.height);
  16742. };
  16743. DynamicTexture.prototype.update = function (invertY) {
  16744. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16745. };
  16746. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16747. if (update === void 0) { update = true; }
  16748. var size = this.getSize();
  16749. if (clearColor) {
  16750. this._context.fillStyle = clearColor;
  16751. this._context.fillRect(0, 0, size.width, size.height);
  16752. }
  16753. this._context.font = font;
  16754. if (x === null) {
  16755. var textSize = this._context.measureText(text);
  16756. x = (size.width - textSize.width) / 2;
  16757. }
  16758. this._context.fillStyle = color;
  16759. this._context.fillText(text, x, y);
  16760. if (update) {
  16761. this.update(invertY);
  16762. }
  16763. };
  16764. DynamicTexture.prototype.clone = function () {
  16765. var textureSize = this.getSize();
  16766. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16767. // Base texture
  16768. newTexture.hasAlpha = this.hasAlpha;
  16769. newTexture.level = this.level;
  16770. // Dynamic Texture
  16771. newTexture.wrapU = this.wrapU;
  16772. newTexture.wrapV = this.wrapV;
  16773. return newTexture;
  16774. };
  16775. return DynamicTexture;
  16776. })(BABYLON.Texture);
  16777. BABYLON.DynamicTexture = DynamicTexture;
  16778. })(BABYLON || (BABYLON = {}));
  16779. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16780. var BABYLON;
  16781. (function (BABYLON) {
  16782. var VideoTexture = (function (_super) {
  16783. __extends(VideoTexture, _super);
  16784. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16785. var _this = this;
  16786. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16787. if (invertY === void 0) { invertY = false; }
  16788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16789. _super.call(this, null, scene, !generateMipMaps, invertY);
  16790. this._autoLaunch = true;
  16791. this.name = name;
  16792. this.video = document.createElement("video");
  16793. this.video.autoplay = false;
  16794. this.video.loop = true;
  16795. this.video.addEventListener("canplaythrough", function () {
  16796. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16797. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16798. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16799. }
  16800. else {
  16801. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16802. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16803. generateMipMaps = false;
  16804. }
  16805. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16806. _this._texture.isReady = true;
  16807. });
  16808. urls.forEach(function (url) {
  16809. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16810. var source = document.createElement("source");
  16811. source.src = url;
  16812. _this.video.appendChild(source);
  16813. });
  16814. this._lastUpdate = BABYLON.Tools.Now;
  16815. }
  16816. VideoTexture.prototype.update = function () {
  16817. if (this._autoLaunch) {
  16818. this._autoLaunch = false;
  16819. this.video.play();
  16820. }
  16821. var now = BABYLON.Tools.Now;
  16822. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16823. return false;
  16824. }
  16825. this._lastUpdate = now;
  16826. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16827. return true;
  16828. };
  16829. return VideoTexture;
  16830. })(BABYLON.Texture);
  16831. BABYLON.VideoTexture = VideoTexture;
  16832. })(BABYLON || (BABYLON = {}));
  16833. //# sourceMappingURL=babylon.videoTexture.js.map
  16834. var BABYLON;
  16835. (function (BABYLON) {
  16836. var CustomProceduralTexture = (function (_super) {
  16837. __extends(CustomProceduralTexture, _super);
  16838. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16839. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16840. this._animate = true;
  16841. this._time = 0;
  16842. this._texturePath = texturePath;
  16843. //Try to load json
  16844. this.loadJson(texturePath);
  16845. this.refreshRate = 1;
  16846. }
  16847. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16848. var _this = this;
  16849. var that = this;
  16850. function noConfigFile() {
  16851. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16852. try {
  16853. that.setFragment(that._texturePath);
  16854. }
  16855. catch (ex) {
  16856. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16857. }
  16858. }
  16859. var configFileUrl = jsonUrl + "/config.json";
  16860. var xhr = new XMLHttpRequest();
  16861. xhr.open("GET", configFileUrl, true);
  16862. xhr.addEventListener("load", function () {
  16863. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16864. try {
  16865. _this._config = JSON.parse(xhr.response);
  16866. _this.updateShaderUniforms();
  16867. _this.updateTextures();
  16868. _this.setFragment(_this._texturePath + "/custom");
  16869. _this._animate = _this._config.animate;
  16870. _this.refreshRate = _this._config.refreshrate;
  16871. }
  16872. catch (ex) {
  16873. noConfigFile();
  16874. }
  16875. }
  16876. else {
  16877. noConfigFile();
  16878. }
  16879. }, false);
  16880. xhr.addEventListener("error", function () {
  16881. noConfigFile();
  16882. }, false);
  16883. try {
  16884. xhr.send();
  16885. }
  16886. catch (ex) {
  16887. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16888. }
  16889. };
  16890. CustomProceduralTexture.prototype.isReady = function () {
  16891. if (!_super.prototype.isReady.call(this)) {
  16892. return false;
  16893. }
  16894. for (var name in this._textures) {
  16895. var texture = this._textures[name];
  16896. if (!texture.isReady()) {
  16897. return false;
  16898. }
  16899. }
  16900. return true;
  16901. };
  16902. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16903. if (this._animate) {
  16904. this._time += this.getScene().getAnimationRatio() * 0.03;
  16905. this.updateShaderUniforms();
  16906. }
  16907. _super.prototype.render.call(this, useCameraPostProcess);
  16908. };
  16909. CustomProceduralTexture.prototype.updateTextures = function () {
  16910. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16911. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16912. }
  16913. };
  16914. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16915. if (this._config) {
  16916. for (var j = 0; j < this._config.uniforms.length; j++) {
  16917. var uniform = this._config.uniforms[j];
  16918. switch (uniform.type) {
  16919. case "float":
  16920. this.setFloat(uniform.name, uniform.value);
  16921. break;
  16922. case "color3":
  16923. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16924. break;
  16925. case "color4":
  16926. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  16927. break;
  16928. case "vector2":
  16929. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  16930. break;
  16931. case "vector3":
  16932. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  16933. break;
  16934. }
  16935. }
  16936. }
  16937. this.setFloat("time", this._time);
  16938. };
  16939. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  16940. get: function () {
  16941. return this._animate;
  16942. },
  16943. set: function (value) {
  16944. this._animate = value;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. return CustomProceduralTexture;
  16950. })(BABYLON.ProceduralTexture);
  16951. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  16952. })(BABYLON || (BABYLON = {}));
  16953. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  16954. var BABYLON;
  16955. (function (BABYLON) {
  16956. var WoodProceduralTexture = (function (_super) {
  16957. __extends(WoodProceduralTexture, _super);
  16958. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16959. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  16960. this._ampScale = 100.0;
  16961. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  16962. this.updateShaderUniforms();
  16963. this.refreshRate = 0;
  16964. }
  16965. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  16966. this.setFloat("ampScale", this._ampScale);
  16967. this.setColor3("woodColor", this._woodColor);
  16968. };
  16969. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  16970. get: function () {
  16971. return this._ampScale;
  16972. },
  16973. set: function (value) {
  16974. this._ampScale = value;
  16975. this.updateShaderUniforms();
  16976. },
  16977. enumerable: true,
  16978. configurable: true
  16979. });
  16980. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  16981. get: function () {
  16982. return this._woodColor;
  16983. },
  16984. set: function (value) {
  16985. this._woodColor = value;
  16986. this.updateShaderUniforms();
  16987. },
  16988. enumerable: true,
  16989. configurable: true
  16990. });
  16991. return WoodProceduralTexture;
  16992. })(BABYLON.ProceduralTexture);
  16993. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  16994. var FireProceduralTexture = (function (_super) {
  16995. __extends(FireProceduralTexture, _super);
  16996. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16997. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  16998. this._time = 0.0;
  16999. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17000. this._autoGenerateTime = true;
  17001. this._alphaThreshold = 0.5;
  17002. this._fireColors = FireProceduralTexture.RedFireColors;
  17003. this.updateShaderUniforms();
  17004. this.refreshRate = 1;
  17005. }
  17006. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17007. this.setFloat("time", this._time);
  17008. this.setVector2("speed", this._speed);
  17009. this.setColor3("c1", this._fireColors[0]);
  17010. this.setColor3("c2", this._fireColors[1]);
  17011. this.setColor3("c3", this._fireColors[2]);
  17012. this.setColor3("c4", this._fireColors[3]);
  17013. this.setColor3("c5", this._fireColors[4]);
  17014. this.setColor3("c6", this._fireColors[5]);
  17015. this.setFloat("alphaThreshold", this._alphaThreshold);
  17016. };
  17017. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17018. if (this._autoGenerateTime) {
  17019. this._time += this.getScene().getAnimationRatio() * 0.03;
  17020. this.updateShaderUniforms();
  17021. }
  17022. _super.prototype.render.call(this, useCameraPostProcess);
  17023. };
  17024. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17025. get: function () {
  17026. return [
  17027. new BABYLON.Color3(0.5, 0.0, 1.0),
  17028. new BABYLON.Color3(0.9, 0.0, 1.0),
  17029. new BABYLON.Color3(0.2, 0.0, 1.0),
  17030. new BABYLON.Color3(1.0, 0.9, 1.0),
  17031. new BABYLON.Color3(0.1, 0.1, 1.0),
  17032. new BABYLON.Color3(0.9, 0.9, 1.0)
  17033. ];
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17039. get: function () {
  17040. return [
  17041. new BABYLON.Color3(0.5, 1.0, 0.0),
  17042. new BABYLON.Color3(0.5, 1.0, 0.0),
  17043. new BABYLON.Color3(0.3, 0.4, 0.0),
  17044. new BABYLON.Color3(0.5, 1.0, 0.0),
  17045. new BABYLON.Color3(0.2, 0.0, 0.0),
  17046. new BABYLON.Color3(0.5, 1.0, 0.0)
  17047. ];
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17053. get: function () {
  17054. return [
  17055. new BABYLON.Color3(0.5, 0.0, 0.1),
  17056. new BABYLON.Color3(0.9, 0.0, 0.0),
  17057. new BABYLON.Color3(0.2, 0.0, 0.0),
  17058. new BABYLON.Color3(1.0, 0.9, 0.0),
  17059. new BABYLON.Color3(0.1, 0.1, 0.1),
  17060. new BABYLON.Color3(0.9, 0.9, 0.9)
  17061. ];
  17062. },
  17063. enumerable: true,
  17064. configurable: true
  17065. });
  17066. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17067. get: function () {
  17068. return [
  17069. new BABYLON.Color3(0.1, 0.0, 0.5),
  17070. new BABYLON.Color3(0.0, 0.0, 0.5),
  17071. new BABYLON.Color3(0.1, 0.0, 0.2),
  17072. new BABYLON.Color3(0.0, 0.0, 1.0),
  17073. new BABYLON.Color3(0.1, 0.2, 0.3),
  17074. new BABYLON.Color3(0.0, 0.2, 0.9)
  17075. ];
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17081. get: function () {
  17082. return this._fireColors;
  17083. },
  17084. set: function (value) {
  17085. this._fireColors = value;
  17086. this.updateShaderUniforms();
  17087. },
  17088. enumerable: true,
  17089. configurable: true
  17090. });
  17091. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17092. get: function () {
  17093. return this._time;
  17094. },
  17095. set: function (value) {
  17096. this._time = value;
  17097. this.updateShaderUniforms();
  17098. },
  17099. enumerable: true,
  17100. configurable: true
  17101. });
  17102. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17103. get: function () {
  17104. return this._speed;
  17105. },
  17106. set: function (value) {
  17107. this._speed = value;
  17108. this.updateShaderUniforms();
  17109. },
  17110. enumerable: true,
  17111. configurable: true
  17112. });
  17113. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17114. get: function () {
  17115. return this._alphaThreshold;
  17116. },
  17117. set: function (value) {
  17118. this._alphaThreshold = value;
  17119. this.updateShaderUniforms();
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. return FireProceduralTexture;
  17125. })(BABYLON.ProceduralTexture);
  17126. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17127. var CloudProceduralTexture = (function (_super) {
  17128. __extends(CloudProceduralTexture, _super);
  17129. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17130. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17131. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17132. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17133. this.updateShaderUniforms();
  17134. this.refreshRate = 0;
  17135. }
  17136. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17137. this.setColor3("skyColor", this._skyColor);
  17138. this.setColor3("cloudColor", this._cloudColor);
  17139. };
  17140. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17141. get: function () {
  17142. return this._skyColor;
  17143. },
  17144. set: function (value) {
  17145. this._skyColor = value;
  17146. this.updateShaderUniforms();
  17147. },
  17148. enumerable: true,
  17149. configurable: true
  17150. });
  17151. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17152. get: function () {
  17153. return this._cloudColor;
  17154. },
  17155. set: function (value) {
  17156. this._cloudColor = value;
  17157. this.updateShaderUniforms();
  17158. },
  17159. enumerable: true,
  17160. configurable: true
  17161. });
  17162. return CloudProceduralTexture;
  17163. })(BABYLON.ProceduralTexture);
  17164. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17165. var GrassProceduralTexture = (function (_super) {
  17166. __extends(GrassProceduralTexture, _super);
  17167. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17168. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17169. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17170. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17171. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17172. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17173. this._grassColors = [
  17174. new BABYLON.Color3(0.29, 0.38, 0.02),
  17175. new BABYLON.Color3(0.36, 0.49, 0.09),
  17176. new BABYLON.Color3(0.51, 0.6, 0.28)
  17177. ];
  17178. this.updateShaderUniforms();
  17179. this.refreshRate = 0;
  17180. }
  17181. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17182. this.setColor3("herb1Color", this._grassColors[0]);
  17183. this.setColor3("herb2Color", this._grassColors[1]);
  17184. this.setColor3("herb3Color", this._grassColors[2]);
  17185. this.setColor3("groundColor", this._groundColor);
  17186. };
  17187. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17188. get: function () {
  17189. return this._grassColors;
  17190. },
  17191. set: function (value) {
  17192. this._grassColors = value;
  17193. this.updateShaderUniforms();
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17199. get: function () {
  17200. return this._groundColor;
  17201. },
  17202. set: function (value) {
  17203. this.groundColor = value;
  17204. this.updateShaderUniforms();
  17205. },
  17206. enumerable: true,
  17207. configurable: true
  17208. });
  17209. return GrassProceduralTexture;
  17210. })(BABYLON.ProceduralTexture);
  17211. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17212. var RoadProceduralTexture = (function (_super) {
  17213. __extends(RoadProceduralTexture, _super);
  17214. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17215. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17216. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17217. this.updateShaderUniforms();
  17218. this.refreshRate = 0;
  17219. }
  17220. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17221. this.setColor3("roadColor", this._roadColor);
  17222. };
  17223. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17224. get: function () {
  17225. return this._roadColor;
  17226. },
  17227. set: function (value) {
  17228. this._roadColor = value;
  17229. this.updateShaderUniforms();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. return RoadProceduralTexture;
  17235. })(BABYLON.ProceduralTexture);
  17236. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17237. var BrickProceduralTexture = (function (_super) {
  17238. __extends(BrickProceduralTexture, _super);
  17239. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17240. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17241. this._numberOfBricksHeight = 15;
  17242. this._numberOfBricksWidth = 5;
  17243. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17244. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17245. this.updateShaderUniforms();
  17246. this.refreshRate = 0;
  17247. }
  17248. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17249. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17250. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17251. this.setColor3("brickColor", this._brickColor);
  17252. this.setColor3("jointColor", this._jointColor);
  17253. };
  17254. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17255. get: function () {
  17256. return this._numberOfBricksHeight;
  17257. },
  17258. set: function (value) {
  17259. this._numberOfBricksHeight = value;
  17260. this.updateShaderUniforms();
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17266. get: function () {
  17267. return this._numberOfBricksWidth;
  17268. },
  17269. set: function (value) {
  17270. this._numberOfBricksHeight = value;
  17271. this.updateShaderUniforms();
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17277. get: function () {
  17278. return this._jointColor;
  17279. },
  17280. set: function (value) {
  17281. this._jointColor = value;
  17282. this.updateShaderUniforms();
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17288. get: function () {
  17289. return this._brickColor;
  17290. },
  17291. set: function (value) {
  17292. this._brickColor = value;
  17293. this.updateShaderUniforms();
  17294. },
  17295. enumerable: true,
  17296. configurable: true
  17297. });
  17298. return BrickProceduralTexture;
  17299. })(BABYLON.ProceduralTexture);
  17300. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17301. var MarbleProceduralTexture = (function (_super) {
  17302. __extends(MarbleProceduralTexture, _super);
  17303. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17304. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17305. this._numberOfTilesHeight = 3;
  17306. this._numberOfTilesWidth = 3;
  17307. this._amplitude = 9.0;
  17308. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17309. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17310. this.updateShaderUniforms();
  17311. this.refreshRate = 0;
  17312. }
  17313. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17314. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17315. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17316. this.setFloat("amplitude", this._amplitude);
  17317. this.setColor3("marbleColor", this._marbleColor);
  17318. this.setColor3("jointColor", this._jointColor);
  17319. };
  17320. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17321. get: function () {
  17322. return this._numberOfTilesHeight;
  17323. },
  17324. set: function (value) {
  17325. this._numberOfTilesHeight = value;
  17326. this.updateShaderUniforms();
  17327. },
  17328. enumerable: true,
  17329. configurable: true
  17330. });
  17331. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17332. get: function () {
  17333. return this._numberOfTilesWidth;
  17334. },
  17335. set: function (value) {
  17336. this._numberOfTilesWidth = value;
  17337. this.updateShaderUniforms();
  17338. },
  17339. enumerable: true,
  17340. configurable: true
  17341. });
  17342. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17343. get: function () {
  17344. return this._jointColor;
  17345. },
  17346. set: function (value) {
  17347. this._jointColor = value;
  17348. this.updateShaderUniforms();
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17354. get: function () {
  17355. return this._marbleColor;
  17356. },
  17357. set: function (value) {
  17358. this._marbleColor = value;
  17359. this.updateShaderUniforms();
  17360. },
  17361. enumerable: true,
  17362. configurable: true
  17363. });
  17364. return MarbleProceduralTexture;
  17365. })(BABYLON.ProceduralTexture);
  17366. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17367. })(BABYLON || (BABYLON = {}));
  17368. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17369. var BABYLON;
  17370. (function (BABYLON) {
  17371. var EffectFallbacks = (function () {
  17372. function EffectFallbacks() {
  17373. this._defines = {};
  17374. this._currentRank = 32;
  17375. this._maxRank = -1;
  17376. }
  17377. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17378. if (!this._defines[rank]) {
  17379. if (rank < this._currentRank) {
  17380. this._currentRank = rank;
  17381. }
  17382. if (rank > this._maxRank) {
  17383. this._maxRank = rank;
  17384. }
  17385. this._defines[rank] = new Array();
  17386. }
  17387. this._defines[rank].push(define);
  17388. };
  17389. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17390. get: function () {
  17391. return this._currentRank <= this._maxRank;
  17392. },
  17393. enumerable: true,
  17394. configurable: true
  17395. });
  17396. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17397. var currentFallbacks = this._defines[this._currentRank];
  17398. for (var index = 0; index < currentFallbacks.length; index++) {
  17399. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17400. }
  17401. this._currentRank++;
  17402. return currentDefines;
  17403. };
  17404. return EffectFallbacks;
  17405. })();
  17406. BABYLON.EffectFallbacks = EffectFallbacks;
  17407. var Effect = (function () {
  17408. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17409. var _this = this;
  17410. this._isReady = false;
  17411. this._compilationError = "";
  17412. this._valueCache = [];
  17413. this._engine = engine;
  17414. this.name = baseName;
  17415. this.defines = defines;
  17416. this._uniformsNames = uniformsNames.concat(samplers);
  17417. this._samplers = samplers;
  17418. this._attributesNames = attributesNames;
  17419. this.onError = onError;
  17420. this.onCompiled = onCompiled;
  17421. var vertexSource;
  17422. var fragmentSource;
  17423. if (baseName.vertexElement) {
  17424. vertexSource = document.getElementById(baseName.vertexElement);
  17425. if (!vertexSource) {
  17426. vertexSource = baseName.vertexElement;
  17427. }
  17428. }
  17429. else {
  17430. vertexSource = baseName.vertex || baseName;
  17431. }
  17432. if (baseName.fragmentElement) {
  17433. fragmentSource = document.getElementById(baseName.fragmentElement);
  17434. if (!fragmentSource) {
  17435. fragmentSource = baseName.fragmentElement;
  17436. }
  17437. }
  17438. else {
  17439. fragmentSource = baseName.fragment || baseName;
  17440. }
  17441. this._loadVertexShader(vertexSource, function (vertexCode) {
  17442. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17443. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17444. });
  17445. });
  17446. }
  17447. // Properties
  17448. Effect.prototype.isReady = function () {
  17449. return this._isReady;
  17450. };
  17451. Effect.prototype.getProgram = function () {
  17452. return this._program;
  17453. };
  17454. Effect.prototype.getAttributesNames = function () {
  17455. return this._attributesNames;
  17456. };
  17457. Effect.prototype.getAttributeLocation = function (index) {
  17458. return this._attributes[index];
  17459. };
  17460. Effect.prototype.getAttributeLocationByName = function (name) {
  17461. var index = this._attributesNames.indexOf(name);
  17462. return this._attributes[index];
  17463. };
  17464. Effect.prototype.getAttributesCount = function () {
  17465. return this._attributes.length;
  17466. };
  17467. Effect.prototype.getUniformIndex = function (uniformName) {
  17468. return this._uniformsNames.indexOf(uniformName);
  17469. };
  17470. Effect.prototype.getUniform = function (uniformName) {
  17471. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17472. };
  17473. Effect.prototype.getSamplers = function () {
  17474. return this._samplers;
  17475. };
  17476. Effect.prototype.getCompilationError = function () {
  17477. return this._compilationError;
  17478. };
  17479. // Methods
  17480. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17481. // DOM element ?
  17482. if (vertex instanceof HTMLElement) {
  17483. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17484. callback(vertexCode);
  17485. return;
  17486. }
  17487. // Is in local store ?
  17488. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17489. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17490. return;
  17491. }
  17492. var vertexShaderUrl;
  17493. if (vertex[0] === ".") {
  17494. vertexShaderUrl = vertex;
  17495. }
  17496. else {
  17497. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17498. }
  17499. // Vertex shader
  17500. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17501. };
  17502. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17503. // DOM element ?
  17504. if (fragment instanceof HTMLElement) {
  17505. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17506. callback(fragmentCode);
  17507. return;
  17508. }
  17509. // Is in local store ?
  17510. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17511. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17512. return;
  17513. }
  17514. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17515. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17516. return;
  17517. }
  17518. var fragmentShaderUrl;
  17519. if (fragment[0] === ".") {
  17520. fragmentShaderUrl = fragment;
  17521. }
  17522. else {
  17523. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17524. }
  17525. // Fragment shader
  17526. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17527. };
  17528. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17529. try {
  17530. var engine = this._engine;
  17531. if (!engine.getCaps().highPrecisionShaderSupported) {
  17532. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17533. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17534. }
  17535. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17536. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17537. this._attributes = engine.getAttributes(this._program, attributesNames);
  17538. for (var index = 0; index < this._samplers.length; index++) {
  17539. var sampler = this.getUniform(this._samplers[index]);
  17540. if (sampler == null) {
  17541. this._samplers.splice(index, 1);
  17542. index--;
  17543. }
  17544. }
  17545. engine.bindSamplers(this);
  17546. this._isReady = true;
  17547. if (this.onCompiled) {
  17548. this.onCompiled(this);
  17549. }
  17550. }
  17551. catch (e) {
  17552. // Is it a problem with precision?
  17553. if (e.message.indexOf("highp") !== -1) {
  17554. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17555. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17556. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17557. return;
  17558. }
  17559. // Let's go through fallbacks then
  17560. if (fallbacks && fallbacks.isMoreFallbacks) {
  17561. defines = fallbacks.reduce(defines);
  17562. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17563. }
  17564. else {
  17565. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17566. BABYLON.Tools.Error("Defines: " + defines);
  17567. BABYLON.Tools.Error("Error: " + e.message);
  17568. this._compilationError = e.message;
  17569. if (this.onError) {
  17570. this.onError(this, this._compilationError);
  17571. }
  17572. }
  17573. }
  17574. };
  17575. Effect.prototype._bindTexture = function (channel, texture) {
  17576. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17577. };
  17578. Effect.prototype.setTexture = function (channel, texture) {
  17579. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17580. };
  17581. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17582. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17583. };
  17584. //public _cacheMatrix(uniformName, matrix) {
  17585. // if (!this._valueCache[uniformName]) {
  17586. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17587. // }
  17588. // for (var index = 0; index < 16; index++) {
  17589. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17590. // }
  17591. //};
  17592. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17593. if (!this._valueCache[uniformName]) {
  17594. this._valueCache[uniformName] = [x, y];
  17595. return;
  17596. }
  17597. this._valueCache[uniformName][0] = x;
  17598. this._valueCache[uniformName][1] = y;
  17599. };
  17600. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17601. if (!this._valueCache[uniformName]) {
  17602. this._valueCache[uniformName] = [x, y, z];
  17603. return;
  17604. }
  17605. this._valueCache[uniformName][0] = x;
  17606. this._valueCache[uniformName][1] = y;
  17607. this._valueCache[uniformName][2] = z;
  17608. };
  17609. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17610. if (!this._valueCache[uniformName]) {
  17611. this._valueCache[uniformName] = [x, y, z, w];
  17612. return;
  17613. }
  17614. this._valueCache[uniformName][0] = x;
  17615. this._valueCache[uniformName][1] = y;
  17616. this._valueCache[uniformName][2] = z;
  17617. this._valueCache[uniformName][3] = w;
  17618. };
  17619. Effect.prototype.setArray = function (uniformName, array) {
  17620. this._engine.setArray(this.getUniform(uniformName), array);
  17621. return this;
  17622. };
  17623. Effect.prototype.setArray2 = function (uniformName, array) {
  17624. this._engine.setArray2(this.getUniform(uniformName), array);
  17625. return this;
  17626. };
  17627. Effect.prototype.setArray3 = function (uniformName, array) {
  17628. this._engine.setArray3(this.getUniform(uniformName), array);
  17629. return this;
  17630. };
  17631. Effect.prototype.setArray4 = function (uniformName, array) {
  17632. this._engine.setArray4(this.getUniform(uniformName), array);
  17633. return this;
  17634. };
  17635. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17636. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17637. return this;
  17638. };
  17639. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17640. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17641. // return;
  17642. //this._cacheMatrix(uniformName, matrix);
  17643. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17644. return this;
  17645. };
  17646. Effect.prototype.setFloat = function (uniformName, value) {
  17647. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17648. return this;
  17649. this._valueCache[uniformName] = value;
  17650. this._engine.setFloat(this.getUniform(uniformName), value);
  17651. return this;
  17652. };
  17653. Effect.prototype.setBool = function (uniformName, bool) {
  17654. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17655. return this;
  17656. this._valueCache[uniformName] = bool;
  17657. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17658. return this;
  17659. };
  17660. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17661. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17662. return this;
  17663. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17664. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17665. return this;
  17666. };
  17667. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17668. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17669. return this;
  17670. this._cacheFloat2(uniformName, x, y);
  17671. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17672. return this;
  17673. };
  17674. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17675. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17676. return this;
  17677. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17678. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17679. return this;
  17680. };
  17681. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17682. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17683. return this;
  17684. this._cacheFloat3(uniformName, x, y, z);
  17685. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17686. return this;
  17687. };
  17688. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17689. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17690. return this;
  17691. this._cacheFloat4(uniformName, x, y, z, w);
  17692. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17693. return this;
  17694. };
  17695. Effect.prototype.setColor3 = function (uniformName, color3) {
  17696. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17697. return this;
  17698. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17699. this._engine.setColor3(this.getUniform(uniformName), color3);
  17700. return this;
  17701. };
  17702. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17703. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  17704. return this;
  17705. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17706. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17707. return this;
  17708. };
  17709. // Statics
  17710. Effect.ShadersStore = {};
  17711. return Effect;
  17712. })();
  17713. BABYLON.Effect = Effect;
  17714. })(BABYLON || (BABYLON = {}));
  17715. //# sourceMappingURL=babylon.effect.js.map
  17716. var BABYLON;
  17717. (function (BABYLON) {
  17718. var Material = (function () {
  17719. function Material(name, scene, doNotAdd) {
  17720. this.name = name;
  17721. this.checkReadyOnEveryCall = true;
  17722. this.checkReadyOnlyOnce = false;
  17723. this.state = "";
  17724. this.alpha = 1.0;
  17725. this.backFaceCulling = true;
  17726. this._wasPreviouslyReady = false;
  17727. this._fillMode = Material.TriangleFillMode;
  17728. this.pointSize = 1.0;
  17729. this.zOffset = 0;
  17730. this.id = name;
  17731. this._scene = scene;
  17732. if (!doNotAdd) {
  17733. scene.materials.push(this);
  17734. }
  17735. }
  17736. Object.defineProperty(Material, "TriangleFillMode", {
  17737. get: function () {
  17738. return Material._TriangleFillMode;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(Material, "WireFrameFillMode", {
  17744. get: function () {
  17745. return Material._WireFrameFillMode;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(Material, "PointFillMode", {
  17751. get: function () {
  17752. return Material._PointFillMode;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(Material.prototype, "wireframe", {
  17758. get: function () {
  17759. return this._fillMode === Material.WireFrameFillMode;
  17760. },
  17761. set: function (value) {
  17762. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Material.prototype, "pointsCloud", {
  17768. get: function () {
  17769. return this._fillMode === Material.PointFillMode;
  17770. },
  17771. set: function (value) {
  17772. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(Material.prototype, "fillMode", {
  17778. get: function () {
  17779. return this._fillMode;
  17780. },
  17781. set: function (value) {
  17782. this._fillMode = value;
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. Material.prototype.isReady = function (mesh, useInstances) {
  17788. return true;
  17789. };
  17790. Material.prototype.getEffect = function () {
  17791. return this._effect;
  17792. };
  17793. Material.prototype.getScene = function () {
  17794. return this._scene;
  17795. };
  17796. Material.prototype.needAlphaBlending = function () {
  17797. return (this.alpha < 1.0);
  17798. };
  17799. Material.prototype.needAlphaTesting = function () {
  17800. return false;
  17801. };
  17802. Material.prototype.getAlphaTestTexture = function () {
  17803. return null;
  17804. };
  17805. Material.prototype.trackCreation = function (onCompiled, onError) {
  17806. };
  17807. Material.prototype._preBind = function () {
  17808. var engine = this._scene.getEngine();
  17809. engine.enableEffect(this._effect);
  17810. engine.setState(this.backFaceCulling, this.zOffset);
  17811. };
  17812. Material.prototype.bind = function (world, mesh) {
  17813. this._scene._cachedMaterial = this;
  17814. if (this.onBind) {
  17815. this.onBind(this, mesh);
  17816. }
  17817. };
  17818. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17819. };
  17820. Material.prototype.unbind = function () {
  17821. };
  17822. Material.prototype.dispose = function (forceDisposeEffect) {
  17823. // Remove from scene
  17824. var index = this._scene.materials.indexOf(this);
  17825. this._scene.materials.splice(index, 1);
  17826. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17827. if (forceDisposeEffect && this._effect) {
  17828. this._scene.getEngine()._releaseEffect(this._effect);
  17829. this._effect = null;
  17830. }
  17831. // Callback
  17832. if (this.onDispose) {
  17833. this.onDispose();
  17834. }
  17835. };
  17836. Material._TriangleFillMode = 0;
  17837. Material._WireFrameFillMode = 1;
  17838. Material._PointFillMode = 2;
  17839. return Material;
  17840. })();
  17841. BABYLON.Material = Material;
  17842. })(BABYLON || (BABYLON = {}));
  17843. //# sourceMappingURL=babylon.material.js.map
  17844. var BABYLON;
  17845. (function (BABYLON) {
  17846. var maxSimultaneousLights = 4;
  17847. var FresnelParameters = (function () {
  17848. function FresnelParameters() {
  17849. this.isEnabled = true;
  17850. this.leftColor = BABYLON.Color3.White();
  17851. this.rightColor = BABYLON.Color3.Black();
  17852. this.bias = 0;
  17853. this.power = 1;
  17854. }
  17855. return FresnelParameters;
  17856. })();
  17857. BABYLON.FresnelParameters = FresnelParameters;
  17858. var StandardMaterial = (function (_super) {
  17859. __extends(StandardMaterial, _super);
  17860. function StandardMaterial(name, scene) {
  17861. var _this = this;
  17862. _super.call(this, name, scene);
  17863. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17864. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17865. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17866. this.specularPower = 64;
  17867. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17868. this.useAlphaFromDiffuseTexture = false;
  17869. this.useSpecularOverAlpha = true;
  17870. this.fogEnabled = true;
  17871. this._cachedDefines = null;
  17872. this._renderTargets = new BABYLON.SmartArray(16);
  17873. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17874. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17875. this._scaledDiffuse = new BABYLON.Color3();
  17876. this._scaledSpecular = new BABYLON.Color3();
  17877. this.getRenderTargetTextures = function () {
  17878. _this._renderTargets.reset();
  17879. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17880. _this._renderTargets.push(_this.reflectionTexture);
  17881. }
  17882. return _this._renderTargets;
  17883. };
  17884. }
  17885. StandardMaterial.prototype.needAlphaBlending = function () {
  17886. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17887. };
  17888. StandardMaterial.prototype.needAlphaTesting = function () {
  17889. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17890. };
  17891. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17892. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17893. };
  17894. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17895. return this.diffuseTexture;
  17896. };
  17897. // Methods
  17898. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17899. if (this.checkReadyOnlyOnce) {
  17900. if (this._wasPreviouslyReady) {
  17901. return true;
  17902. }
  17903. }
  17904. var scene = this.getScene();
  17905. if (!this.checkReadyOnEveryCall) {
  17906. if (this._renderId === scene.getRenderId()) {
  17907. return true;
  17908. }
  17909. }
  17910. var engine = scene.getEngine();
  17911. var defines = [];
  17912. var fallbacks = new BABYLON.EffectFallbacks();
  17913. var needNormals = false;
  17914. var needUVs = false;
  17915. // Textures
  17916. if (scene.texturesEnabled) {
  17917. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17918. if (!this.diffuseTexture.isReady()) {
  17919. return false;
  17920. }
  17921. else {
  17922. needUVs = true;
  17923. defines.push("#define DIFFUSE");
  17924. }
  17925. }
  17926. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17927. if (!this.ambientTexture.isReady()) {
  17928. return false;
  17929. }
  17930. else {
  17931. needUVs = true;
  17932. defines.push("#define AMBIENT");
  17933. }
  17934. }
  17935. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17936. if (!this.opacityTexture.isReady()) {
  17937. return false;
  17938. }
  17939. else {
  17940. needUVs = true;
  17941. defines.push("#define OPACITY");
  17942. if (this.opacityTexture.getAlphaFromRGB) {
  17943. defines.push("#define OPACITYRGB");
  17944. }
  17945. }
  17946. }
  17947. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17948. if (!this.reflectionTexture.isReady()) {
  17949. return false;
  17950. }
  17951. else {
  17952. needNormals = true;
  17953. needUVs = true;
  17954. defines.push("#define REFLECTION");
  17955. fallbacks.addFallback(0, "REFLECTION");
  17956. }
  17957. }
  17958. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17959. if (!this.emissiveTexture.isReady()) {
  17960. return false;
  17961. }
  17962. else {
  17963. needUVs = true;
  17964. defines.push("#define EMISSIVE");
  17965. }
  17966. }
  17967. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17968. if (!this.specularTexture.isReady()) {
  17969. return false;
  17970. }
  17971. else {
  17972. needUVs = true;
  17973. defines.push("#define SPECULAR");
  17974. fallbacks.addFallback(0, "SPECULAR");
  17975. }
  17976. }
  17977. }
  17978. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  17979. if (!this.bumpTexture.isReady()) {
  17980. return false;
  17981. }
  17982. else {
  17983. needUVs = true;
  17984. defines.push("#define BUMP");
  17985. fallbacks.addFallback(0, "BUMP");
  17986. }
  17987. }
  17988. // Effect
  17989. if (this.useSpecularOverAlpha) {
  17990. defines.push("#define SPECULAROVERALPHA");
  17991. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  17992. }
  17993. if (scene.clipPlane) {
  17994. defines.push("#define CLIPPLANE");
  17995. }
  17996. if (engine.getAlphaTesting()) {
  17997. defines.push("#define ALPHATEST");
  17998. }
  17999. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18000. defines.push("#define ALPHAFROMDIFFUSE");
  18001. }
  18002. // Point size
  18003. if (this.pointsCloud || scene.forcePointsCloud) {
  18004. defines.push("#define POINTSIZE");
  18005. }
  18006. // Fog
  18007. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18008. defines.push("#define FOG");
  18009. fallbacks.addFallback(1, "FOG");
  18010. }
  18011. var shadowsActivated = false;
  18012. var lightIndex = 0;
  18013. if (scene.lightsEnabled) {
  18014. for (var index = 0; index < scene.lights.length; index++) {
  18015. var light = scene.lights[index];
  18016. if (!light.isEnabled()) {
  18017. continue;
  18018. }
  18019. // Excluded check
  18020. if (light._excludedMeshesIds.length > 0) {
  18021. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18022. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18023. if (excludedMesh) {
  18024. light.excludedMeshes.push(excludedMesh);
  18025. }
  18026. }
  18027. light._excludedMeshesIds = [];
  18028. }
  18029. // Included check
  18030. if (light._includedOnlyMeshesIds.length > 0) {
  18031. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18032. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18033. if (includedOnlyMesh) {
  18034. light.includedOnlyMeshes.push(includedOnlyMesh);
  18035. }
  18036. }
  18037. light._includedOnlyMeshesIds = [];
  18038. }
  18039. if (!light.canAffectMesh(mesh)) {
  18040. continue;
  18041. }
  18042. needNormals = true;
  18043. defines.push("#define LIGHT" + lightIndex);
  18044. if (lightIndex > 0) {
  18045. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18046. }
  18047. var type;
  18048. if (light instanceof BABYLON.SpotLight) {
  18049. type = "#define SPOTLIGHT" + lightIndex;
  18050. }
  18051. else if (light instanceof BABYLON.HemisphericLight) {
  18052. type = "#define HEMILIGHT" + lightIndex;
  18053. }
  18054. else {
  18055. type = "#define POINTDIRLIGHT" + lightIndex;
  18056. }
  18057. defines.push(type);
  18058. if (lightIndex > 0) {
  18059. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18060. }
  18061. // Shadows
  18062. if (scene.shadowsEnabled) {
  18063. var shadowGenerator = light.getShadowGenerator();
  18064. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18065. defines.push("#define SHADOW" + lightIndex);
  18066. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18067. if (!shadowsActivated) {
  18068. defines.push("#define SHADOWS");
  18069. shadowsActivated = true;
  18070. }
  18071. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18072. defines.push("#define SHADOWVSM" + lightIndex);
  18073. if (lightIndex > 0) {
  18074. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18075. }
  18076. }
  18077. if (shadowGenerator.usePoissonSampling) {
  18078. defines.push("#define SHADOWPCF" + lightIndex);
  18079. if (lightIndex > 0) {
  18080. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18081. }
  18082. }
  18083. }
  18084. }
  18085. lightIndex++;
  18086. if (lightIndex === maxSimultaneousLights)
  18087. break;
  18088. }
  18089. }
  18090. if (StandardMaterial.FresnelEnabled) {
  18091. // Fresnel
  18092. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18093. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18094. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18095. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18096. var fresnelRank = 1;
  18097. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18098. defines.push("#define DIFFUSEFRESNEL");
  18099. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18100. fresnelRank++;
  18101. }
  18102. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18103. defines.push("#define OPACITYFRESNEL");
  18104. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18105. fresnelRank++;
  18106. }
  18107. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18108. defines.push("#define REFLECTIONFRESNEL");
  18109. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18110. fresnelRank++;
  18111. }
  18112. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18113. defines.push("#define EMISSIVEFRESNEL");
  18114. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18115. fresnelRank++;
  18116. }
  18117. needNormals = true;
  18118. defines.push("#define FRESNEL");
  18119. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18120. }
  18121. }
  18122. // Attribs
  18123. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18124. if (mesh) {
  18125. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18126. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18127. defines.push("#define NORMAL");
  18128. }
  18129. if (needUVs) {
  18130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18131. attribs.push(BABYLON.VertexBuffer.UVKind);
  18132. defines.push("#define UV1");
  18133. }
  18134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18135. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18136. defines.push("#define UV2");
  18137. }
  18138. }
  18139. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18140. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18141. defines.push("#define VERTEXCOLOR");
  18142. if (mesh.hasVertexAlpha) {
  18143. defines.push("#define VERTEXALPHA");
  18144. }
  18145. }
  18146. if (mesh.useBones) {
  18147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18149. defines.push("#define BONES");
  18150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18151. defines.push("#define BONES4");
  18152. fallbacks.addFallback(0, "BONES4");
  18153. }
  18154. // Instances
  18155. if (useInstances) {
  18156. defines.push("#define INSTANCES");
  18157. attribs.push("world0");
  18158. attribs.push("world1");
  18159. attribs.push("world2");
  18160. attribs.push("world3");
  18161. }
  18162. }
  18163. // Get correct effect
  18164. var join = defines.join("\n");
  18165. if (this._cachedDefines !== join) {
  18166. this._cachedDefines = join;
  18167. scene.resetCachedMaterial();
  18168. // Legacy browser patch
  18169. var shaderName = "default";
  18170. if (!scene.getEngine().getCaps().standardDerivatives) {
  18171. shaderName = "legacydefault";
  18172. }
  18173. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18174. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18175. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18176. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18177. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18178. "vFogInfos", "vFogColor", "pointSize",
  18179. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18180. "mBones",
  18181. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18182. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18183. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18184. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18185. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18186. ], join, fallbacks, this.onCompiled, this.onError);
  18187. }
  18188. if (!this._effect.isReady()) {
  18189. return false;
  18190. }
  18191. this._renderId = scene.getRenderId();
  18192. this._wasPreviouslyReady = true;
  18193. return true;
  18194. };
  18195. StandardMaterial.prototype.unbind = function () {
  18196. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18197. this._effect.setTexture("reflection2DSampler", null);
  18198. }
  18199. };
  18200. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18201. this._effect.setMatrix("world", world);
  18202. };
  18203. StandardMaterial.prototype.bind = function (world, mesh) {
  18204. var scene = this.getScene();
  18205. // Matrices
  18206. this.bindOnlyWorldMatrix(world);
  18207. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18208. // Bones
  18209. if (mesh && mesh.useBones) {
  18210. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18211. }
  18212. if (scene.getCachedMaterial() !== this) {
  18213. if (StandardMaterial.FresnelEnabled) {
  18214. // Fresnel
  18215. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18216. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18217. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18218. }
  18219. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18220. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18221. }
  18222. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18223. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18224. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18225. }
  18226. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18227. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18228. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18229. }
  18230. }
  18231. // Textures
  18232. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18233. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18234. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18235. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18236. }
  18237. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18238. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18239. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18240. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18241. }
  18242. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18243. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18244. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18245. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18246. }
  18247. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18248. if (this.reflectionTexture.isCube) {
  18249. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18250. }
  18251. else {
  18252. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18253. }
  18254. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18255. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18256. }
  18257. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18258. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18259. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18260. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18261. }
  18262. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18263. this._effect.setTexture("specularSampler", this.specularTexture);
  18264. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18265. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18266. }
  18267. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18268. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18269. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18270. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18271. }
  18272. // Clip plane
  18273. if (scene.clipPlane) {
  18274. var clipPlane = scene.clipPlane;
  18275. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18276. }
  18277. // Point size
  18278. if (this.pointsCloud) {
  18279. this._effect.setFloat("pointSize", this.pointSize);
  18280. }
  18281. // Colors
  18282. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18283. // Scaling down color according to emissive
  18284. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18285. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18286. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18287. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18288. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18289. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18290. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18291. }
  18292. // Scaling down color according to emissive
  18293. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18294. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18295. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18296. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18297. if (scene.lightsEnabled) {
  18298. var lightIndex = 0;
  18299. for (var index = 0; index < scene.lights.length; index++) {
  18300. var light = scene.lights[index];
  18301. if (!light.isEnabled()) {
  18302. continue;
  18303. }
  18304. if (!light.canAffectMesh(mesh)) {
  18305. continue;
  18306. }
  18307. if (light instanceof BABYLON.PointLight) {
  18308. // Point Light
  18309. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18310. }
  18311. else if (light instanceof BABYLON.DirectionalLight) {
  18312. // Directional Light
  18313. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18314. }
  18315. else if (light instanceof BABYLON.SpotLight) {
  18316. // Spot Light
  18317. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18318. }
  18319. else if (light instanceof BABYLON.HemisphericLight) {
  18320. // Hemispheric Light
  18321. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18322. }
  18323. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18324. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18325. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18326. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18327. // Shadows
  18328. if (scene.shadowsEnabled) {
  18329. var shadowGenerator = light.getShadowGenerator();
  18330. if (mesh.receiveShadows && shadowGenerator) {
  18331. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18332. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18333. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18334. }
  18335. }
  18336. lightIndex++;
  18337. if (lightIndex === maxSimultaneousLights)
  18338. break;
  18339. }
  18340. }
  18341. // View
  18342. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18343. this._effect.setMatrix("view", scene.getViewMatrix());
  18344. }
  18345. // Fog
  18346. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18347. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18348. this._effect.setColor3("vFogColor", scene.fogColor);
  18349. }
  18350. _super.prototype.bind.call(this, world, mesh);
  18351. };
  18352. StandardMaterial.prototype.getAnimatables = function () {
  18353. var results = [];
  18354. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18355. results.push(this.diffuseTexture);
  18356. }
  18357. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18358. results.push(this.ambientTexture);
  18359. }
  18360. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18361. results.push(this.opacityTexture);
  18362. }
  18363. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18364. results.push(this.reflectionTexture);
  18365. }
  18366. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18367. results.push(this.emissiveTexture);
  18368. }
  18369. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18370. results.push(this.specularTexture);
  18371. }
  18372. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18373. results.push(this.bumpTexture);
  18374. }
  18375. return results;
  18376. };
  18377. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18378. if (this.diffuseTexture) {
  18379. this.diffuseTexture.dispose();
  18380. }
  18381. if (this.ambientTexture) {
  18382. this.ambientTexture.dispose();
  18383. }
  18384. if (this.opacityTexture) {
  18385. this.opacityTexture.dispose();
  18386. }
  18387. if (this.reflectionTexture) {
  18388. this.reflectionTexture.dispose();
  18389. }
  18390. if (this.emissiveTexture) {
  18391. this.emissiveTexture.dispose();
  18392. }
  18393. if (this.specularTexture) {
  18394. this.specularTexture.dispose();
  18395. }
  18396. if (this.bumpTexture) {
  18397. this.bumpTexture.dispose();
  18398. }
  18399. _super.prototype.dispose.call(this, forceDisposeEffect);
  18400. };
  18401. StandardMaterial.prototype.clone = function (name) {
  18402. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18403. // Base material
  18404. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18405. newStandardMaterial.alpha = this.alpha;
  18406. newStandardMaterial.fillMode = this.fillMode;
  18407. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18408. // Standard material
  18409. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18410. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18411. }
  18412. if (this.ambientTexture && this.ambientTexture.clone) {
  18413. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18414. }
  18415. if (this.opacityTexture && this.opacityTexture.clone) {
  18416. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18417. }
  18418. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18419. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18420. }
  18421. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18422. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18423. }
  18424. if (this.specularTexture && this.specularTexture.clone) {
  18425. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18426. }
  18427. if (this.bumpTexture && this.bumpTexture.clone) {
  18428. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18429. }
  18430. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18431. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18432. newStandardMaterial.specularColor = this.specularColor.clone();
  18433. newStandardMaterial.specularPower = this.specularPower;
  18434. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18435. return newStandardMaterial;
  18436. };
  18437. // Statics
  18438. // Flags used to enable or disable a type of texture for all Standard Materials
  18439. StandardMaterial.DiffuseTextureEnabled = true;
  18440. StandardMaterial.AmbientTextureEnabled = true;
  18441. StandardMaterial.OpacityTextureEnabled = true;
  18442. StandardMaterial.ReflectionTextureEnabled = true;
  18443. StandardMaterial.EmissiveTextureEnabled = true;
  18444. StandardMaterial.SpecularTextureEnabled = true;
  18445. StandardMaterial.BumpTextureEnabled = true;
  18446. StandardMaterial.FresnelEnabled = true;
  18447. return StandardMaterial;
  18448. })(BABYLON.Material);
  18449. BABYLON.StandardMaterial = StandardMaterial;
  18450. })(BABYLON || (BABYLON = {}));
  18451. //# sourceMappingURL=babylon.standardMaterial.js.map
  18452. var BABYLON;
  18453. (function (BABYLON) {
  18454. var MultiMaterial = (function (_super) {
  18455. __extends(MultiMaterial, _super);
  18456. function MultiMaterial(name, scene) {
  18457. _super.call(this, name, scene, true);
  18458. this.subMaterials = new Array();
  18459. scene.multiMaterials.push(this);
  18460. }
  18461. // Properties
  18462. MultiMaterial.prototype.getSubMaterial = function (index) {
  18463. if (index < 0 || index >= this.subMaterials.length) {
  18464. return this.getScene().defaultMaterial;
  18465. }
  18466. return this.subMaterials[index];
  18467. };
  18468. // Methods
  18469. MultiMaterial.prototype.isReady = function (mesh) {
  18470. for (var index = 0; index < this.subMaterials.length; index++) {
  18471. var subMaterial = this.subMaterials[index];
  18472. if (subMaterial) {
  18473. if (!this.subMaterials[index].isReady(mesh)) {
  18474. return false;
  18475. }
  18476. }
  18477. }
  18478. return true;
  18479. };
  18480. MultiMaterial.prototype.clone = function (name) {
  18481. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18482. for (var index = 0; index < this.subMaterials.length; index++) {
  18483. var subMaterial = this.subMaterials[index];
  18484. newMultiMaterial.subMaterials.push(subMaterial);
  18485. }
  18486. return newMultiMaterial;
  18487. };
  18488. return MultiMaterial;
  18489. })(BABYLON.Material);
  18490. BABYLON.MultiMaterial = MultiMaterial;
  18491. })(BABYLON || (BABYLON = {}));
  18492. //# sourceMappingURL=babylon.multiMaterial.js.map
  18493. var BABYLON;
  18494. (function (BABYLON) {
  18495. var SceneLoader = (function () {
  18496. function SceneLoader() {
  18497. }
  18498. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18499. get: function () {
  18500. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18501. },
  18502. set: function (value) {
  18503. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18509. get: function () {
  18510. return SceneLoader._ShowLoadingScreen;
  18511. },
  18512. set: function (value) {
  18513. SceneLoader._ShowLoadingScreen = value;
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18519. var dotPosition = sceneFilename.lastIndexOf(".");
  18520. var queryStringPosition = sceneFilename.indexOf("?");
  18521. if (queryStringPosition === -1) {
  18522. queryStringPosition = sceneFilename.length;
  18523. }
  18524. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18525. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18526. var plugin = this._registeredPlugins[index];
  18527. if (plugin.extensions.indexOf(extension) !== -1) {
  18528. return plugin;
  18529. }
  18530. }
  18531. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18532. };
  18533. // Public functions
  18534. SceneLoader.RegisterPlugin = function (plugin) {
  18535. plugin.extensions = plugin.extensions.toLowerCase();
  18536. SceneLoader._registeredPlugins.push(plugin);
  18537. };
  18538. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18539. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18540. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18541. return;
  18542. }
  18543. var manifestChecked = function (success) {
  18544. scene.database = database;
  18545. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18546. var importMeshFromData = function (data) {
  18547. var meshes = [];
  18548. var particleSystems = [];
  18549. var skeletons = [];
  18550. try {
  18551. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18552. if (onerror) {
  18553. onerror(scene, 'unable to load the scene');
  18554. }
  18555. return;
  18556. }
  18557. }
  18558. catch (e) {
  18559. if (onerror) {
  18560. onerror(scene, e);
  18561. }
  18562. return;
  18563. }
  18564. if (onsuccess) {
  18565. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18566. onsuccess(meshes, particleSystems, skeletons);
  18567. }
  18568. };
  18569. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18570. // Direct load
  18571. importMeshFromData(sceneFilename.substr(5));
  18572. return;
  18573. }
  18574. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18575. importMeshFromData(data);
  18576. }, progressCallBack, database);
  18577. };
  18578. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18579. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18580. };
  18581. /**
  18582. * Load a scene
  18583. * @param rootUrl a string that defines the root url for scene and resources
  18584. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18585. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18586. */
  18587. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18588. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18589. };
  18590. /**
  18591. * Append a scene
  18592. * @param rootUrl a string that defines the root url for scene and resources
  18593. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18594. * @param scene is the instance of BABYLON.Scene to append to
  18595. */
  18596. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18597. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18598. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18599. return;
  18600. }
  18601. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18602. var database;
  18603. if (SceneLoader.ShowLoadingScreen) {
  18604. scene.getEngine().displayLoadingUI();
  18605. }
  18606. var loadSceneFromData = function (data) {
  18607. scene.database = database;
  18608. if (!plugin.load(scene, data, rootUrl)) {
  18609. if (onerror) {
  18610. onerror(scene);
  18611. }
  18612. scene.getEngine().hideLoadingUI();
  18613. return;
  18614. }
  18615. if (onsuccess) {
  18616. onsuccess(scene);
  18617. }
  18618. if (SceneLoader.ShowLoadingScreen) {
  18619. scene.executeWhenReady(function () {
  18620. scene.getEngine().hideLoadingUI();
  18621. });
  18622. }
  18623. };
  18624. var manifestChecked = function (success) {
  18625. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18626. };
  18627. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18628. // Direct load
  18629. loadSceneFromData(sceneFilename.substr(5));
  18630. return;
  18631. }
  18632. if (rootUrl.indexOf("file:") === -1) {
  18633. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18634. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18635. }
  18636. else {
  18637. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18638. }
  18639. };
  18640. // Flags
  18641. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18642. SceneLoader._ShowLoadingScreen = true;
  18643. // Members
  18644. SceneLoader._registeredPlugins = new Array();
  18645. return SceneLoader;
  18646. })();
  18647. BABYLON.SceneLoader = SceneLoader;
  18648. ;
  18649. })(BABYLON || (BABYLON = {}));
  18650. //# sourceMappingURL=babylon.sceneLoader.js.map
  18651. var BABYLON;
  18652. (function (BABYLON) {
  18653. var Internals;
  18654. (function (Internals) {
  18655. var checkColors4 = function (colors, count) {
  18656. // Check if color3 was used
  18657. if (colors.length === count * 3) {
  18658. var colors4 = [];
  18659. for (var index = 0; index < colors.length; index += 3) {
  18660. var newIndex = (index / 3) * 4;
  18661. colors4[newIndex] = colors[index];
  18662. colors4[newIndex + 1] = colors[index + 1];
  18663. colors4[newIndex + 2] = colors[index + 2];
  18664. colors4[newIndex + 3] = 1.0;
  18665. }
  18666. return colors4;
  18667. }
  18668. return colors;
  18669. };
  18670. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18671. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18672. texture.name = parsedTexture.name;
  18673. texture.hasAlpha = parsedTexture.hasAlpha;
  18674. texture.level = parsedTexture.level;
  18675. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18676. return texture;
  18677. };
  18678. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18679. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18680. return null;
  18681. }
  18682. if (parsedTexture.isCube) {
  18683. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18684. }
  18685. var texture;
  18686. if (parsedTexture.mirrorPlane) {
  18687. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18688. texture._waitingRenderList = parsedTexture.renderList;
  18689. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18690. }
  18691. else if (parsedTexture.isRenderTarget) {
  18692. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18693. texture._waitingRenderList = parsedTexture.renderList;
  18694. }
  18695. else {
  18696. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18697. }
  18698. texture.name = parsedTexture.name;
  18699. texture.hasAlpha = parsedTexture.hasAlpha;
  18700. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18701. texture.level = parsedTexture.level;
  18702. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18703. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18704. texture.uOffset = parsedTexture.uOffset;
  18705. texture.vOffset = parsedTexture.vOffset;
  18706. texture.uScale = parsedTexture.uScale;
  18707. texture.vScale = parsedTexture.vScale;
  18708. texture.uAng = parsedTexture.uAng;
  18709. texture.vAng = parsedTexture.vAng;
  18710. texture.wAng = parsedTexture.wAng;
  18711. texture.wrapU = parsedTexture.wrapU;
  18712. texture.wrapV = parsedTexture.wrapV;
  18713. // Animations
  18714. if (parsedTexture.animations) {
  18715. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18716. var parsedAnimation = parsedTexture.animations[animationIndex];
  18717. texture.animations.push(parseAnimation(parsedAnimation));
  18718. }
  18719. }
  18720. return texture;
  18721. };
  18722. var parseSkeleton = function (parsedSkeleton, scene) {
  18723. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18724. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18725. var parsedBone = parsedSkeleton.bones[index];
  18726. var parentBone = null;
  18727. if (parsedBone.parentBoneIndex > -1) {
  18728. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18729. }
  18730. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18731. if (parsedBone.animation) {
  18732. bone.animations.push(parseAnimation(parsedBone.animation));
  18733. }
  18734. }
  18735. return skeleton;
  18736. };
  18737. var parseFresnelParameters = function (parsedFresnelParameters) {
  18738. var fresnelParameters = new BABYLON.FresnelParameters();
  18739. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18740. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18741. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18742. fresnelParameters.bias = parsedFresnelParameters.bias;
  18743. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18744. return fresnelParameters;
  18745. };
  18746. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18747. var material;
  18748. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18749. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18750. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18751. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18752. material.specularPower = parsedMaterial.specularPower;
  18753. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18754. material.alpha = parsedMaterial.alpha;
  18755. material.id = parsedMaterial.id;
  18756. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18757. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18758. material.wireframe = parsedMaterial.wireframe;
  18759. if (parsedMaterial.diffuseTexture) {
  18760. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18761. }
  18762. if (parsedMaterial.diffuseFresnelParameters) {
  18763. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18764. }
  18765. if (parsedMaterial.ambientTexture) {
  18766. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18767. }
  18768. if (parsedMaterial.opacityTexture) {
  18769. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18770. }
  18771. if (parsedMaterial.opacityFresnelParameters) {
  18772. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18773. }
  18774. if (parsedMaterial.reflectionTexture) {
  18775. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18776. }
  18777. if (parsedMaterial.reflectionFresnelParameters) {
  18778. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18779. }
  18780. if (parsedMaterial.emissiveTexture) {
  18781. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18782. }
  18783. if (parsedMaterial.emissiveFresnelParameters) {
  18784. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18785. }
  18786. if (parsedMaterial.specularTexture) {
  18787. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18788. }
  18789. if (parsedMaterial.bumpTexture) {
  18790. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18791. }
  18792. return material;
  18793. };
  18794. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18795. for (var index = 0; index < parsedData.materials.length; index++) {
  18796. var parsedMaterial = parsedData.materials[index];
  18797. if (parsedMaterial.id === id) {
  18798. return parseMaterial(parsedMaterial, scene, rootUrl);
  18799. }
  18800. }
  18801. return null;
  18802. };
  18803. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18804. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18805. multiMaterial.id = parsedMultiMaterial.id;
  18806. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18807. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18808. var subMatId = parsedMultiMaterial.materials[matIndex];
  18809. if (subMatId) {
  18810. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18811. }
  18812. else {
  18813. multiMaterial.subMaterials.push(null);
  18814. }
  18815. }
  18816. return multiMaterial;
  18817. };
  18818. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18819. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18820. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18821. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18822. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18823. var parsedFlare = parsedLensFlareSystem.flares[index];
  18824. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18825. }
  18826. return lensFlareSystem;
  18827. };
  18828. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18829. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18830. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18831. if (parsedParticleSystem.textureName) {
  18832. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18833. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18834. }
  18835. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18836. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18837. particleSystem.minSize = parsedParticleSystem.minSize;
  18838. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18839. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18840. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18841. particleSystem.emitter = emitter;
  18842. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18843. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18844. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18845. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18846. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18847. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18848. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18849. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18850. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18851. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18852. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18853. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18854. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18855. particleSystem.start();
  18856. return particleSystem;
  18857. };
  18858. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18859. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18860. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18861. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18862. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18863. shadowGenerator.getShadowMap().renderList.push(mesh);
  18864. }
  18865. if (parsedShadowGenerator.usePoissonSampling) {
  18866. shadowGenerator.usePoissonSampling = true;
  18867. }
  18868. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18869. shadowGenerator.useVarianceShadowMap = true;
  18870. }
  18871. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18872. shadowGenerator.useBlurVarianceShadowMap = true;
  18873. if (parsedShadowGenerator.blurScale) {
  18874. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18875. }
  18876. if (parsedShadowGenerator.blurBoxOffset) {
  18877. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18878. }
  18879. }
  18880. if (parsedShadowGenerator.bias !== undefined) {
  18881. shadowGenerator.bias = parsedShadowGenerator.bias;
  18882. }
  18883. return shadowGenerator;
  18884. };
  18885. var parseAnimation = function (parsedAnimation) {
  18886. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18887. var dataType = parsedAnimation.dataType;
  18888. var keys = [];
  18889. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18890. var key = parsedAnimation.keys[index];
  18891. var data;
  18892. switch (dataType) {
  18893. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18894. data = key.values[0];
  18895. break;
  18896. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18897. data = BABYLON.Quaternion.FromArray(key.values);
  18898. break;
  18899. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18900. data = BABYLON.Matrix.FromArray(key.values);
  18901. break;
  18902. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18903. default:
  18904. data = BABYLON.Vector3.FromArray(key.values);
  18905. break;
  18906. }
  18907. keys.push({
  18908. frame: key.frame,
  18909. value: data
  18910. });
  18911. }
  18912. animation.setKeys(keys);
  18913. return animation;
  18914. };
  18915. var parseLight = function (parsedLight, scene) {
  18916. var light;
  18917. switch (parsedLight.type) {
  18918. case 0:
  18919. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18920. break;
  18921. case 1:
  18922. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18923. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18924. break;
  18925. case 2:
  18926. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18927. break;
  18928. case 3:
  18929. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18930. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18931. break;
  18932. }
  18933. light.id = parsedLight.id;
  18934. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18935. if (parsedLight.intensity !== undefined) {
  18936. light.intensity = parsedLight.intensity;
  18937. }
  18938. if (parsedLight.range) {
  18939. light.range = parsedLight.range;
  18940. }
  18941. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18942. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18943. if (parsedLight.excludedMeshesIds) {
  18944. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18945. }
  18946. // Parent
  18947. if (parsedLight.parentId) {
  18948. light._waitingParentId = parsedLight.parentId;
  18949. }
  18950. if (parsedLight.includedOnlyMeshesIds) {
  18951. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18952. }
  18953. // Animations
  18954. if (parsedLight.animations) {
  18955. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18956. var parsedAnimation = parsedLight.animations[animationIndex];
  18957. light.animations.push(parseAnimation(parsedAnimation));
  18958. }
  18959. }
  18960. if (parsedLight.autoAnimate) {
  18961. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18962. }
  18963. };
  18964. var parseCamera = function (parsedCamera, scene) {
  18965. var camera;
  18966. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18967. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18968. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18969. var alpha = parsedCamera.alpha;
  18970. var beta = parsedCamera.beta;
  18971. var radius = parsedCamera.radius;
  18972. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18973. var eye_space = parsedCamera.eye_space;
  18974. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18975. }
  18976. else {
  18977. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18978. }
  18979. }
  18980. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18981. eye_space = parsedCamera.eye_space;
  18982. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18983. }
  18984. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18985. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18986. }
  18987. else if (parsedCamera.type === "FollowCamera") {
  18988. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18989. camera.heightOffset = parsedCamera.heightOffset;
  18990. camera.radius = parsedCamera.radius;
  18991. camera.rotationOffset = parsedCamera.rotationOffset;
  18992. if (lockedTargetMesh)
  18993. camera.target = lockedTargetMesh;
  18994. }
  18995. else if (parsedCamera.type === "GamepadCamera") {
  18996. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18997. }
  18998. else if (parsedCamera.type === "TouchCamera") {
  18999. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19000. }
  19001. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19002. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19003. }
  19004. else if (parsedCamera.type === "WebVRFreeCamera") {
  19005. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19006. }
  19007. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19008. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19009. }
  19010. else {
  19011. // Free Camera is the default value
  19012. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19013. }
  19014. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19015. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19016. camera.lockedTarget = lockedTargetMesh;
  19017. }
  19018. camera.id = parsedCamera.id;
  19019. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19020. // Parent
  19021. if (parsedCamera.parentId) {
  19022. camera._waitingParentId = parsedCamera.parentId;
  19023. }
  19024. // Target
  19025. if (parsedCamera.target) {
  19026. if (camera.setTarget) {
  19027. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19028. }
  19029. else {
  19030. //For ArcRotate
  19031. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19032. }
  19033. }
  19034. else {
  19035. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19036. }
  19037. camera.fov = parsedCamera.fov;
  19038. camera.minZ = parsedCamera.minZ;
  19039. camera.maxZ = parsedCamera.maxZ;
  19040. camera.speed = parsedCamera.speed;
  19041. camera.inertia = parsedCamera.inertia;
  19042. camera.checkCollisions = parsedCamera.checkCollisions;
  19043. camera.applyGravity = parsedCamera.applyGravity;
  19044. if (parsedCamera.ellipsoid) {
  19045. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19046. }
  19047. // Animations
  19048. if (parsedCamera.animations) {
  19049. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19050. var parsedAnimation = parsedCamera.animations[animationIndex];
  19051. camera.animations.push(parseAnimation(parsedAnimation));
  19052. }
  19053. }
  19054. if (parsedCamera.autoAnimate) {
  19055. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19056. }
  19057. // Layer Mask
  19058. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19059. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19060. }
  19061. else {
  19062. camera.layerMask = 0xFFFFFFFF;
  19063. }
  19064. return camera;
  19065. };
  19066. var parseGeometry = function (parsedGeometry, scene) {
  19067. var id = parsedGeometry.id;
  19068. return scene.getGeometryByID(id);
  19069. };
  19070. var parseBox = function (parsedBox, scene) {
  19071. if (parseGeometry(parsedBox, scene)) {
  19072. return null; // null since geometry could be something else than a box...
  19073. }
  19074. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19075. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19076. scene.pushGeometry(box, true);
  19077. return box;
  19078. };
  19079. var parseSphere = function (parsedSphere, scene) {
  19080. if (parseGeometry(parsedSphere, scene)) {
  19081. return null; // null since geometry could be something else than a sphere...
  19082. }
  19083. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19084. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19085. scene.pushGeometry(sphere, true);
  19086. return sphere;
  19087. };
  19088. var parseCylinder = function (parsedCylinder, scene) {
  19089. if (parseGeometry(parsedCylinder, scene)) {
  19090. return null; // null since geometry could be something else than a cylinder...
  19091. }
  19092. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19093. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19094. scene.pushGeometry(cylinder, true);
  19095. return cylinder;
  19096. };
  19097. var parseTorus = function (parsedTorus, scene) {
  19098. if (parseGeometry(parsedTorus, scene)) {
  19099. return null; // null since geometry could be something else than a torus...
  19100. }
  19101. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19102. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19103. scene.pushGeometry(torus, true);
  19104. return torus;
  19105. };
  19106. var parseGround = function (parsedGround, scene) {
  19107. if (parseGeometry(parsedGround, scene)) {
  19108. return null; // null since geometry could be something else than a ground...
  19109. }
  19110. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19111. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19112. scene.pushGeometry(ground, true);
  19113. return ground;
  19114. };
  19115. var parsePlane = function (parsedPlane, scene) {
  19116. if (parseGeometry(parsedPlane, scene)) {
  19117. return null; // null since geometry could be something else than a plane...
  19118. }
  19119. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19120. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19121. scene.pushGeometry(plane, true);
  19122. return plane;
  19123. };
  19124. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19125. if (parseGeometry(parsedTorusKnot, scene)) {
  19126. return null; // null since geometry could be something else than a torusKnot...
  19127. }
  19128. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  19129. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19130. scene.pushGeometry(torusKnot, true);
  19131. return torusKnot;
  19132. };
  19133. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19134. if (parseGeometry(parsedVertexData, scene)) {
  19135. return null; // null since geometry could be a primitive
  19136. }
  19137. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19138. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19139. if (parsedVertexData.delayLoadingFile) {
  19140. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19141. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19142. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19143. geometry._delayInfo = [];
  19144. if (parsedVertexData.hasUVs) {
  19145. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19146. }
  19147. if (parsedVertexData.hasUVs2) {
  19148. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19149. }
  19150. if (parsedVertexData.hasColors) {
  19151. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19152. }
  19153. if (parsedVertexData.hasMatricesIndices) {
  19154. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19155. }
  19156. if (parsedVertexData.hasMatricesWeights) {
  19157. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19158. }
  19159. geometry._delayLoadingFunction = importVertexData;
  19160. }
  19161. else {
  19162. importVertexData(parsedVertexData, geometry);
  19163. }
  19164. scene.pushGeometry(geometry, true);
  19165. return geometry;
  19166. };
  19167. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19168. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19169. mesh.id = parsedMesh.id;
  19170. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19171. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19172. if (parsedMesh.rotationQuaternion) {
  19173. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19174. }
  19175. else if (parsedMesh.rotation) {
  19176. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19177. }
  19178. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19179. if (parsedMesh.localMatrix) {
  19180. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19181. }
  19182. else if (parsedMesh.pivotMatrix) {
  19183. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19184. }
  19185. mesh.setEnabled(parsedMesh.isEnabled);
  19186. mesh.isVisible = parsedMesh.isVisible;
  19187. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19188. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19189. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19190. if (parsedMesh.applyFog !== undefined) {
  19191. mesh.applyFog = parsedMesh.applyFog;
  19192. }
  19193. if (parsedMesh.pickable !== undefined) {
  19194. mesh.isPickable = parsedMesh.pickable;
  19195. }
  19196. if (parsedMesh.alphaIndex !== undefined) {
  19197. mesh.alphaIndex = parsedMesh.alphaIndex;
  19198. }
  19199. mesh.receiveShadows = parsedMesh.receiveShadows;
  19200. mesh.billboardMode = parsedMesh.billboardMode;
  19201. if (parsedMesh.visibility !== undefined) {
  19202. mesh.visibility = parsedMesh.visibility;
  19203. }
  19204. mesh.checkCollisions = parsedMesh.checkCollisions;
  19205. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19206. // Parent
  19207. if (parsedMesh.parentId) {
  19208. mesh._waitingParentId = parsedMesh.parentId;
  19209. }
  19210. // Actions
  19211. if (parsedMesh.actions !== undefined) {
  19212. mesh._waitingActions = parsedMesh.actions;
  19213. }
  19214. // Geometry
  19215. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19216. if (parsedMesh.delayLoadingFile) {
  19217. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19218. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19219. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19220. if (parsedMesh._binaryInfo) {
  19221. mesh._binaryInfo = parsedMesh._binaryInfo;
  19222. }
  19223. mesh._delayInfo = [];
  19224. if (parsedMesh.hasUVs) {
  19225. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19226. }
  19227. if (parsedMesh.hasUVs2) {
  19228. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19229. }
  19230. if (parsedMesh.hasColors) {
  19231. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19232. }
  19233. if (parsedMesh.hasMatricesIndices) {
  19234. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19235. }
  19236. if (parsedMesh.hasMatricesWeights) {
  19237. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19238. }
  19239. mesh._delayLoadingFunction = importGeometry;
  19240. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19241. mesh._checkDelayState();
  19242. }
  19243. }
  19244. else {
  19245. importGeometry(parsedMesh, mesh);
  19246. }
  19247. // Material
  19248. if (parsedMesh.materialId) {
  19249. mesh.setMaterialByID(parsedMesh.materialId);
  19250. }
  19251. else {
  19252. mesh.material = null;
  19253. }
  19254. // Skeleton
  19255. if (parsedMesh.skeletonId > -1) {
  19256. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19257. }
  19258. // Physics
  19259. if (parsedMesh.physicsImpostor) {
  19260. if (!scene.isPhysicsEnabled()) {
  19261. scene.enablePhysics();
  19262. }
  19263. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19264. }
  19265. // Animations
  19266. if (parsedMesh.animations) {
  19267. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19268. var parsedAnimation = parsedMesh.animations[animationIndex];
  19269. mesh.animations.push(parseAnimation(parsedAnimation));
  19270. }
  19271. }
  19272. if (parsedMesh.autoAnimate) {
  19273. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19274. }
  19275. // Layer Mask
  19276. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19277. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19278. }
  19279. else {
  19280. mesh.layerMask = 0xFFFFFFFF;
  19281. }
  19282. // Instances
  19283. if (parsedMesh.instances) {
  19284. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19285. var parsedInstance = parsedMesh.instances[index];
  19286. var instance = mesh.createInstance(parsedInstance.name);
  19287. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19288. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19289. if (parsedInstance.rotationQuaternion) {
  19290. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19291. }
  19292. else if (parsedInstance.rotation) {
  19293. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19294. }
  19295. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19296. instance.checkCollisions = mesh.checkCollisions;
  19297. if (parsedMesh.animations) {
  19298. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19299. parsedAnimation = parsedMesh.animations[animationIndex];
  19300. instance.animations.push(parseAnimation(parsedAnimation));
  19301. }
  19302. }
  19303. }
  19304. }
  19305. return mesh;
  19306. };
  19307. var parseActions = function (parsedActions, object, scene) {
  19308. var actionManager = new BABYLON.ActionManager(scene);
  19309. if (object === null)
  19310. scene.actionManager = actionManager;
  19311. else
  19312. object.actionManager = actionManager;
  19313. // instanciate a new object
  19314. var instanciate = function (name, params) {
  19315. var newInstance = Object.create(BABYLON[name].prototype);
  19316. newInstance.constructor.apply(newInstance, params);
  19317. return newInstance;
  19318. };
  19319. var parseParameter = function (name, value, target, propertyPath) {
  19320. if (propertyPath === null) {
  19321. // String, boolean or float
  19322. var floatValue = parseFloat(value);
  19323. if (value === "true" || value === "false")
  19324. return value === "true";
  19325. else
  19326. return isNaN(floatValue) ? value : floatValue;
  19327. }
  19328. var effectiveTarget = propertyPath.split(".");
  19329. var values = value.split(",");
  19330. // Get effective Target
  19331. for (var i = 0; i < effectiveTarget.length; i++) {
  19332. target = target[effectiveTarget[i]];
  19333. }
  19334. // Return appropriate value with its type
  19335. if (typeof (target) === "boolean")
  19336. return values[0] === "true";
  19337. if (typeof (target) === "string")
  19338. return values[0];
  19339. // Parameters with multiple values such as Vector3 etc.
  19340. var split = new Array();
  19341. for (var i = 0; i < values.length; i++)
  19342. split.push(parseFloat(values[i]));
  19343. if (target instanceof BABYLON.Vector3)
  19344. return BABYLON.Vector3.FromArray(split);
  19345. if (target instanceof BABYLON.Vector4)
  19346. return BABYLON.Vector4.FromArray(split);
  19347. if (target instanceof BABYLON.Color3)
  19348. return BABYLON.Color3.FromArray(split);
  19349. if (target instanceof BABYLON.Color4)
  19350. return BABYLON.Color4.FromArray(split);
  19351. return parseFloat(values[0]);
  19352. };
  19353. // traverse graph per trigger
  19354. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19355. if (combineArray === void 0) { combineArray = null; }
  19356. if (parsedAction.detached)
  19357. return;
  19358. var parameters = new Array();
  19359. var target = null;
  19360. var propertyPath = null;
  19361. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19362. // Parameters
  19363. if (parsedAction.type === 2)
  19364. parameters.push(actionManager);
  19365. else
  19366. parameters.push(trigger);
  19367. if (combine) {
  19368. var actions = new Array();
  19369. for (var j = 0; j < parsedAction.combine.length; j++) {
  19370. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19371. }
  19372. parameters.push(actions);
  19373. }
  19374. else {
  19375. for (var i = 0; i < parsedAction.properties.length; i++) {
  19376. var value = parsedAction.properties[i].value;
  19377. var name = parsedAction.properties[i].name;
  19378. var targetType = parsedAction.properties[i].targetType;
  19379. if (name === "target")
  19380. if (targetType !== null && targetType === "SceneProperties")
  19381. value = target = scene;
  19382. else
  19383. value = target = scene.getNodeByName(value);
  19384. else if (name === "parent")
  19385. value = scene.getNodeByName(value);
  19386. else if (name === "sound")
  19387. value = scene.getSoundByName(value);
  19388. else if (name !== "propertyPath") {
  19389. if (parsedAction.type === 2 && name === "operator")
  19390. value = BABYLON.ValueCondition[value];
  19391. else
  19392. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19393. }
  19394. else {
  19395. propertyPath = value;
  19396. }
  19397. parameters.push(value);
  19398. }
  19399. }
  19400. if (combineArray === null) {
  19401. parameters.push(condition);
  19402. }
  19403. else {
  19404. parameters.push(null);
  19405. }
  19406. // If interpolate value action
  19407. if (parsedAction.name === "InterpolateValueAction") {
  19408. var param = parameters[parameters.length - 2];
  19409. parameters[parameters.length - 1] = param;
  19410. parameters[parameters.length - 2] = condition;
  19411. }
  19412. // Action or condition(s) and not CombineAction
  19413. var newAction = instanciate(parsedAction.name, parameters);
  19414. if (combineArray === null) {
  19415. if (newAction instanceof BABYLON.Condition) {
  19416. condition = newAction;
  19417. newAction = action;
  19418. }
  19419. else {
  19420. condition = null;
  19421. if (action)
  19422. action.then(newAction);
  19423. else
  19424. actionManager.registerAction(newAction);
  19425. }
  19426. }
  19427. else {
  19428. combineArray.push(newAction);
  19429. }
  19430. for (var i = 0; i < parsedAction.children.length; i++)
  19431. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19432. };
  19433. // triggers
  19434. for (var i = 0; i < parsedActions.children.length; i++) {
  19435. var triggerParams;
  19436. var trigger = parsedActions.children[i];
  19437. if (trigger.properties.length > 0) {
  19438. var param = trigger.properties[0].value;
  19439. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19440. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19441. }
  19442. else
  19443. triggerParams = BABYLON.ActionManager[trigger.name];
  19444. for (var j = 0; j < trigger.children.length; j++) {
  19445. if (!trigger.detached)
  19446. traverse(trigger.children[j], triggerParams, null, null);
  19447. }
  19448. }
  19449. };
  19450. var parseSound = function (parsedSound, scene, rootUrl) {
  19451. var soundName = parsedSound.name;
  19452. var soundUrl = rootUrl + soundName;
  19453. var options = {
  19454. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19455. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19456. rolloffFactor: parsedSound.rolloffFactor,
  19457. refDistance: parsedSound.refDistance,
  19458. distanceModel: parsedSound.distanceModel,
  19459. playbackRate: parsedSound.playbackRate
  19460. };
  19461. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19462. scene._addPendingData(newSound);
  19463. if (parsedSound.position) {
  19464. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19465. newSound.setPosition(soundPosition);
  19466. }
  19467. if (parsedSound.isDirectional) {
  19468. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19469. if (parsedSound.localDirectionToMesh) {
  19470. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19471. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19472. }
  19473. }
  19474. if (parsedSound.connectedMeshId) {
  19475. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19476. if (connectedMesh) {
  19477. newSound.attachToMesh(connectedMesh);
  19478. }
  19479. }
  19480. };
  19481. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19482. names = (names instanceof Array) ? names : [names];
  19483. for (var i in names) {
  19484. if (mesh.name === names[i]) {
  19485. hierarchyIds.push(mesh.id);
  19486. return true;
  19487. }
  19488. }
  19489. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19490. hierarchyIds.push(mesh.id);
  19491. return true;
  19492. }
  19493. return false;
  19494. };
  19495. var importVertexData = function (parsedVertexData, geometry) {
  19496. var vertexData = new BABYLON.VertexData();
  19497. // positions
  19498. var positions = parsedVertexData.positions;
  19499. if (positions) {
  19500. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19501. }
  19502. // normals
  19503. var normals = parsedVertexData.normals;
  19504. if (normals) {
  19505. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19506. }
  19507. // uvs
  19508. var uvs = parsedVertexData.uvs;
  19509. if (uvs) {
  19510. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19511. }
  19512. // uv2s
  19513. var uv2s = parsedVertexData.uv2s;
  19514. if (uv2s) {
  19515. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19516. }
  19517. // colors
  19518. var colors = parsedVertexData.colors;
  19519. if (colors) {
  19520. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19521. }
  19522. // matricesIndices
  19523. var matricesIndices = parsedVertexData.matricesIndices;
  19524. if (matricesIndices) {
  19525. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19526. }
  19527. // matricesWeights
  19528. var matricesWeights = parsedVertexData.matricesWeights;
  19529. if (matricesWeights) {
  19530. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19531. }
  19532. // indices
  19533. var indices = parsedVertexData.indices;
  19534. if (indices) {
  19535. vertexData.indices = indices;
  19536. }
  19537. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19538. };
  19539. var importGeometry = function (parsedGeometry, mesh) {
  19540. var scene = mesh.getScene();
  19541. // Geometry
  19542. var geometryId = parsedGeometry.geometryId;
  19543. if (geometryId) {
  19544. var geometry = scene.getGeometryByID(geometryId);
  19545. if (geometry) {
  19546. geometry.applyToMesh(mesh);
  19547. }
  19548. }
  19549. else if (parsedGeometry instanceof ArrayBuffer) {
  19550. var binaryInfo = mesh._binaryInfo;
  19551. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19552. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19553. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19554. }
  19555. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19556. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19557. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19558. }
  19559. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19560. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19561. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19562. }
  19563. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19564. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19565. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19566. }
  19567. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19568. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19569. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19570. }
  19571. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19572. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19573. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19574. }
  19575. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19576. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19577. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19578. }
  19579. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19580. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19581. mesh.setIndices(indicesData);
  19582. }
  19583. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19584. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19585. mesh.subMeshes = [];
  19586. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19587. var materialIndex = subMeshesData[(i * 5) + 0];
  19588. var verticesStart = subMeshesData[(i * 5) + 1];
  19589. var verticesCount = subMeshesData[(i * 5) + 2];
  19590. var indexStart = subMeshesData[(i * 5) + 3];
  19591. var indexCount = subMeshesData[(i * 5) + 4];
  19592. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19593. }
  19594. }
  19595. }
  19596. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19597. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19598. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19599. if (parsedGeometry.uvs) {
  19600. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19601. }
  19602. if (parsedGeometry.uvs2) {
  19603. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19604. }
  19605. if (parsedGeometry.colors) {
  19606. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19607. }
  19608. if (parsedGeometry.matricesIndices) {
  19609. if (!parsedGeometry.matricesIndices._isExpanded) {
  19610. var floatIndices = [];
  19611. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19612. var matricesIndex = parsedGeometry.matricesIndices[i];
  19613. floatIndices.push(matricesIndex & 0x000000FF);
  19614. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19615. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19616. floatIndices.push(matricesIndex >> 24);
  19617. }
  19618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19619. }
  19620. else {
  19621. delete parsedGeometry.matricesIndices._isExpanded;
  19622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19623. }
  19624. }
  19625. if (parsedGeometry.matricesWeights) {
  19626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19627. }
  19628. mesh.setIndices(parsedGeometry.indices);
  19629. // SubMeshes
  19630. if (parsedGeometry.subMeshes) {
  19631. mesh.subMeshes = [];
  19632. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19633. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19634. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19635. }
  19636. }
  19637. }
  19638. // Flat shading
  19639. if (mesh._shouldGenerateFlatShading) {
  19640. mesh.convertToFlatShadedMesh();
  19641. delete mesh._shouldGenerateFlatShading;
  19642. }
  19643. // Update
  19644. mesh.computeWorldMatrix(true);
  19645. // Octree
  19646. if (scene._selectionOctree) {
  19647. scene._selectionOctree.addMesh(mesh);
  19648. }
  19649. };
  19650. BABYLON.SceneLoader.RegisterPlugin({
  19651. extensions: ".babylon",
  19652. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19653. var parsedData = JSON.parse(data);
  19654. var loadedSkeletonsIds = [];
  19655. var loadedMaterialsIds = [];
  19656. var hierarchyIds = [];
  19657. for (var index = 0; index < parsedData.meshes.length; index++) {
  19658. var parsedMesh = parsedData.meshes[index];
  19659. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19660. if (meshesNames instanceof Array) {
  19661. // Remove found mesh name from list.
  19662. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19663. }
  19664. //Geometry?
  19665. if (parsedMesh.geometryId) {
  19666. //does the file contain geometries?
  19667. if (parsedData.geometries) {
  19668. //find the correct geometry and add it to the scene
  19669. var found = false;
  19670. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19671. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19672. return;
  19673. }
  19674. else {
  19675. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19676. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19677. switch (geometryType) {
  19678. case "boxes":
  19679. parseBox(parsedGeometryData, scene);
  19680. break;
  19681. case "spheres":
  19682. parseSphere(parsedGeometryData, scene);
  19683. break;
  19684. case "cylinders":
  19685. parseCylinder(parsedGeometryData, scene);
  19686. break;
  19687. case "toruses":
  19688. parseTorus(parsedGeometryData, scene);
  19689. break;
  19690. case "grounds":
  19691. parseGround(parsedGeometryData, scene);
  19692. break;
  19693. case "planes":
  19694. parsePlane(parsedGeometryData, scene);
  19695. break;
  19696. case "torusKnots":
  19697. parseTorusKnot(parsedGeometryData, scene);
  19698. break;
  19699. case "vertexData":
  19700. parseVertexData(parsedGeometryData, scene, rootUrl);
  19701. break;
  19702. }
  19703. found = true;
  19704. }
  19705. });
  19706. }
  19707. });
  19708. }
  19709. }
  19710. // Material ?
  19711. if (parsedMesh.materialId) {
  19712. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19713. if (!materialFound) {
  19714. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19715. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19716. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19717. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19718. var subMatId = parsedMultiMaterial.materials[matIndex];
  19719. loadedMaterialsIds.push(subMatId);
  19720. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19721. }
  19722. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19723. parseMultiMaterial(parsedMultiMaterial, scene);
  19724. materialFound = true;
  19725. break;
  19726. }
  19727. }
  19728. }
  19729. if (!materialFound) {
  19730. loadedMaterialsIds.push(parsedMesh.materialId);
  19731. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19732. }
  19733. }
  19734. // Skeleton ?
  19735. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19736. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19737. if (!skeletonAlreadyLoaded) {
  19738. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19739. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19740. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19741. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19742. loadedSkeletonsIds.push(parsedSkeleton.id);
  19743. }
  19744. }
  19745. }
  19746. }
  19747. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19748. meshes.push(mesh);
  19749. }
  19750. }
  19751. // Connecting parents
  19752. for (index = 0; index < scene.meshes.length; index++) {
  19753. var currentMesh = scene.meshes[index];
  19754. if (currentMesh._waitingParentId) {
  19755. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19756. currentMesh._waitingParentId = undefined;
  19757. }
  19758. }
  19759. // Particles
  19760. if (parsedData.particleSystems) {
  19761. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19762. var parsedParticleSystem = parsedData.particleSystems[index];
  19763. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19764. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19765. }
  19766. }
  19767. }
  19768. return true;
  19769. },
  19770. load: function (scene, data, rootUrl) {
  19771. var parsedData = JSON.parse(data);
  19772. // Scene
  19773. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19774. scene.autoClear = parsedData.autoClear;
  19775. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19776. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19777. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19778. // Fog
  19779. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19780. scene.fogMode = parsedData.fogMode;
  19781. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19782. scene.fogStart = parsedData.fogStart;
  19783. scene.fogEnd = parsedData.fogEnd;
  19784. scene.fogDensity = parsedData.fogDensity;
  19785. }
  19786. // Lights
  19787. for (var index = 0; index < parsedData.lights.length; index++) {
  19788. var parsedLight = parsedData.lights[index];
  19789. parseLight(parsedLight, scene);
  19790. }
  19791. // Materials
  19792. if (parsedData.materials) {
  19793. for (index = 0; index < parsedData.materials.length; index++) {
  19794. var parsedMaterial = parsedData.materials[index];
  19795. parseMaterial(parsedMaterial, scene, rootUrl);
  19796. }
  19797. }
  19798. if (parsedData.multiMaterials) {
  19799. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19800. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19801. parseMultiMaterial(parsedMultiMaterial, scene);
  19802. }
  19803. }
  19804. // Skeletons
  19805. if (parsedData.skeletons) {
  19806. for (index = 0; index < parsedData.skeletons.length; index++) {
  19807. var parsedSkeleton = parsedData.skeletons[index];
  19808. parseSkeleton(parsedSkeleton, scene);
  19809. }
  19810. }
  19811. // Geometries
  19812. var geometries = parsedData.geometries;
  19813. if (geometries) {
  19814. // Boxes
  19815. var boxes = geometries.boxes;
  19816. if (boxes) {
  19817. for (index = 0; index < boxes.length; index++) {
  19818. var parsedBox = boxes[index];
  19819. parseBox(parsedBox, scene);
  19820. }
  19821. }
  19822. // Spheres
  19823. var spheres = geometries.spheres;
  19824. if (spheres) {
  19825. for (index = 0; index < spheres.length; index++) {
  19826. var parsedSphere = spheres[index];
  19827. parseSphere(parsedSphere, scene);
  19828. }
  19829. }
  19830. // Cylinders
  19831. var cylinders = geometries.cylinders;
  19832. if (cylinders) {
  19833. for (index = 0; index < cylinders.length; index++) {
  19834. var parsedCylinder = cylinders[index];
  19835. parseCylinder(parsedCylinder, scene);
  19836. }
  19837. }
  19838. // Toruses
  19839. var toruses = geometries.toruses;
  19840. if (toruses) {
  19841. for (index = 0; index < toruses.length; index++) {
  19842. var parsedTorus = toruses[index];
  19843. parseTorus(parsedTorus, scene);
  19844. }
  19845. }
  19846. // Grounds
  19847. var grounds = geometries.grounds;
  19848. if (grounds) {
  19849. for (index = 0; index < grounds.length; index++) {
  19850. var parsedGround = grounds[index];
  19851. parseGround(parsedGround, scene);
  19852. }
  19853. }
  19854. // Planes
  19855. var planes = geometries.planes;
  19856. if (planes) {
  19857. for (index = 0; index < planes.length; index++) {
  19858. var parsedPlane = planes[index];
  19859. parsePlane(parsedPlane, scene);
  19860. }
  19861. }
  19862. // TorusKnots
  19863. var torusKnots = geometries.torusKnots;
  19864. if (torusKnots) {
  19865. for (index = 0; index < torusKnots.length; index++) {
  19866. var parsedTorusKnot = torusKnots[index];
  19867. parseTorusKnot(parsedTorusKnot, scene);
  19868. }
  19869. }
  19870. // VertexData
  19871. var vertexData = geometries.vertexData;
  19872. if (vertexData) {
  19873. for (index = 0; index < vertexData.length; index++) {
  19874. var parsedVertexData = vertexData[index];
  19875. parseVertexData(parsedVertexData, scene, rootUrl);
  19876. }
  19877. }
  19878. }
  19879. // Meshes
  19880. for (index = 0; index < parsedData.meshes.length; index++) {
  19881. var parsedMesh = parsedData.meshes[index];
  19882. parseMesh(parsedMesh, scene, rootUrl);
  19883. }
  19884. // Cameras
  19885. for (index = 0; index < parsedData.cameras.length; index++) {
  19886. var parsedCamera = parsedData.cameras[index];
  19887. parseCamera(parsedCamera, scene);
  19888. }
  19889. if (parsedData.activeCameraID) {
  19890. scene.setActiveCameraByID(parsedData.activeCameraID);
  19891. }
  19892. // Browsing all the graph to connect the dots
  19893. for (index = 0; index < scene.cameras.length; index++) {
  19894. var camera = scene.cameras[index];
  19895. if (camera._waitingParentId) {
  19896. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19897. camera._waitingParentId = undefined;
  19898. }
  19899. }
  19900. for (index = 0; index < scene.lights.length; index++) {
  19901. var light = scene.lights[index];
  19902. if (light._waitingParentId) {
  19903. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19904. light._waitingParentId = undefined;
  19905. }
  19906. }
  19907. // Sounds
  19908. if (parsedData.sounds) {
  19909. for (index = 0; index < parsedData.sounds.length; index++) {
  19910. var parsedSound = parsedData.sounds[index];
  19911. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19912. parseSound(parsedSound, scene, rootUrl);
  19913. }
  19914. else {
  19915. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19916. }
  19917. }
  19918. }
  19919. // Connect parents & children and parse actions
  19920. for (index = 0; index < scene.meshes.length; index++) {
  19921. var mesh = scene.meshes[index];
  19922. if (mesh._waitingParentId) {
  19923. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19924. mesh._waitingParentId = undefined;
  19925. }
  19926. if (mesh._waitingActions) {
  19927. parseActions(mesh._waitingActions, mesh, scene);
  19928. mesh._waitingActions = undefined;
  19929. }
  19930. }
  19931. // Particles Systems
  19932. if (parsedData.particleSystems) {
  19933. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19934. var parsedParticleSystem = parsedData.particleSystems[index];
  19935. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19936. }
  19937. }
  19938. // Lens flares
  19939. if (parsedData.lensFlareSystems) {
  19940. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19941. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19942. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19943. }
  19944. }
  19945. // Shadows
  19946. if (parsedData.shadowGenerators) {
  19947. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19948. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19949. parseShadowGenerator(parsedShadowGenerator, scene);
  19950. }
  19951. }
  19952. // Actions (scene)
  19953. if (parsedData.actions) {
  19954. parseActions(parsedData.actions, null, scene);
  19955. }
  19956. // Finish
  19957. return true;
  19958. }
  19959. });
  19960. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19961. })(BABYLON || (BABYLON = {}));
  19962. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  19963. var BABYLON;
  19964. (function (BABYLON) {
  19965. var SpriteManager = (function () {
  19966. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  19967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19968. this.name = name;
  19969. this.cellSize = cellSize;
  19970. this.sprites = new Array();
  19971. this.renderingGroupId = 0;
  19972. this.fogEnabled = true;
  19973. this._vertexDeclaration = [4, 4, 4, 4];
  19974. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  19975. this._capacity = capacity;
  19976. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  19977. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19978. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19979. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  19980. this._scene = scene;
  19981. this._scene.spriteManagers.push(this);
  19982. // VBO
  19983. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19984. var indices = [];
  19985. var index = 0;
  19986. for (var count = 0; count < capacity; count++) {
  19987. indices.push(index);
  19988. indices.push(index + 1);
  19989. indices.push(index + 2);
  19990. indices.push(index);
  19991. indices.push(index + 2);
  19992. indices.push(index + 3);
  19993. index += 4;
  19994. }
  19995. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19996. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19997. // Effects
  19998. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  19999. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20000. }
  20001. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20002. var arrayOffset = index * 16;
  20003. if (offsetX === 0)
  20004. offsetX = this._epsilon;
  20005. else if (offsetX === 1)
  20006. offsetX = 1 - this._epsilon;
  20007. if (offsetY === 0)
  20008. offsetY = this._epsilon;
  20009. else if (offsetY === 1)
  20010. offsetY = 1 - this._epsilon;
  20011. this._vertices[arrayOffset] = sprite.position.x;
  20012. this._vertices[arrayOffset + 1] = sprite.position.y;
  20013. this._vertices[arrayOffset + 2] = sprite.position.z;
  20014. this._vertices[arrayOffset + 3] = sprite.angle;
  20015. this._vertices[arrayOffset + 4] = sprite.width;
  20016. this._vertices[arrayOffset + 5] = sprite.height;
  20017. this._vertices[arrayOffset + 6] = offsetX;
  20018. this._vertices[arrayOffset + 7] = offsetY;
  20019. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20020. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20021. var offset = (sprite.cellIndex / rowSize) >> 0;
  20022. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20023. this._vertices[arrayOffset + 11] = offset;
  20024. // Color
  20025. this._vertices[arrayOffset + 12] = sprite.color.r;
  20026. this._vertices[arrayOffset + 13] = sprite.color.g;
  20027. this._vertices[arrayOffset + 14] = sprite.color.b;
  20028. this._vertices[arrayOffset + 15] = sprite.color.a;
  20029. };
  20030. SpriteManager.prototype.render = function () {
  20031. // Check
  20032. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20033. return;
  20034. var engine = this._scene.getEngine();
  20035. var baseSize = this._spriteTexture.getBaseSize();
  20036. // Sprites
  20037. var deltaTime = engine.getDeltaTime();
  20038. var max = Math.min(this._capacity, this.sprites.length);
  20039. var rowSize = baseSize.width / this.cellSize;
  20040. var offset = 0;
  20041. for (var index = 0; index < max; index++) {
  20042. var sprite = this.sprites[index];
  20043. if (!sprite) {
  20044. continue;
  20045. }
  20046. sprite._animate(deltaTime);
  20047. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20048. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20049. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20050. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20051. }
  20052. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20053. // Render
  20054. var effect = this._effectBase;
  20055. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20056. effect = this._effectFog;
  20057. }
  20058. engine.enableEffect(effect);
  20059. var viewMatrix = this._scene.getViewMatrix();
  20060. effect.setTexture("diffuseSampler", this._spriteTexture);
  20061. effect.setMatrix("view", viewMatrix);
  20062. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20063. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20064. // Fog
  20065. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20066. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20067. effect.setColor3("vFogColor", this._scene.fogColor);
  20068. }
  20069. // VBOs
  20070. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20071. // Draw order
  20072. engine.setDepthFunctionToLessOrEqual();
  20073. effect.setBool("alphaTest", true);
  20074. engine.setColorWrite(false);
  20075. engine.draw(true, 0, max * 6);
  20076. engine.setColorWrite(true);
  20077. effect.setBool("alphaTest", false);
  20078. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20079. engine.draw(true, 0, max * 6);
  20080. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20081. };
  20082. SpriteManager.prototype.dispose = function () {
  20083. if (this._vertexBuffer) {
  20084. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20085. this._vertexBuffer = null;
  20086. }
  20087. if (this._indexBuffer) {
  20088. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20089. this._indexBuffer = null;
  20090. }
  20091. if (this._spriteTexture) {
  20092. this._spriteTexture.dispose();
  20093. this._spriteTexture = null;
  20094. }
  20095. // Remove from scene
  20096. var index = this._scene.spriteManagers.indexOf(this);
  20097. this._scene.spriteManagers.splice(index, 1);
  20098. // Callback
  20099. if (this.onDispose) {
  20100. this.onDispose();
  20101. }
  20102. };
  20103. return SpriteManager;
  20104. })();
  20105. BABYLON.SpriteManager = SpriteManager;
  20106. })(BABYLON || (BABYLON = {}));
  20107. //# sourceMappingURL=babylon.spriteManager.js.map
  20108. var BABYLON;
  20109. (function (BABYLON) {
  20110. var Sprite = (function () {
  20111. function Sprite(name, manager) {
  20112. this.name = name;
  20113. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20114. this.width = 1.0;
  20115. this.height = 1.0;
  20116. this.angle = 0;
  20117. this.cellIndex = 0;
  20118. this.invertU = 0;
  20119. this.invertV = 0;
  20120. this.animations = new Array();
  20121. this._animationStarted = false;
  20122. this._loopAnimation = false;
  20123. this._fromIndex = 0;
  20124. this._toIndex = 0;
  20125. this._delay = 0;
  20126. this._direction = 1;
  20127. this._frameCount = 0;
  20128. this._time = 0;
  20129. this._manager = manager;
  20130. this._manager.sprites.push(this);
  20131. this.position = BABYLON.Vector3.Zero();
  20132. }
  20133. Object.defineProperty(Sprite.prototype, "size", {
  20134. get: function () {
  20135. return this.width;
  20136. },
  20137. set: function (value) {
  20138. this.width = value;
  20139. this.height = value;
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20145. this._fromIndex = from;
  20146. this._toIndex = to;
  20147. this._loopAnimation = loop;
  20148. this._delay = delay;
  20149. this._animationStarted = true;
  20150. this._direction = from < to ? 1 : -1;
  20151. this.cellIndex = from;
  20152. this._time = 0;
  20153. };
  20154. Sprite.prototype.stopAnimation = function () {
  20155. this._animationStarted = false;
  20156. };
  20157. Sprite.prototype._animate = function (deltaTime) {
  20158. if (!this._animationStarted)
  20159. return;
  20160. this._time += deltaTime;
  20161. if (this._time > this._delay) {
  20162. this._time = this._time % this._delay;
  20163. this.cellIndex += this._direction;
  20164. if (this.cellIndex == this._toIndex) {
  20165. if (this._loopAnimation) {
  20166. this.cellIndex = this._fromIndex;
  20167. }
  20168. else {
  20169. this._animationStarted = false;
  20170. if (this.disposeWhenFinishedAnimating) {
  20171. this.dispose();
  20172. }
  20173. }
  20174. }
  20175. }
  20176. };
  20177. Sprite.prototype.dispose = function () {
  20178. for (var i = 0; i < this._manager.sprites.length; i++) {
  20179. if (this._manager.sprites[i] == this) {
  20180. this._manager.sprites.splice(i, 1);
  20181. }
  20182. }
  20183. };
  20184. return Sprite;
  20185. })();
  20186. BABYLON.Sprite = Sprite;
  20187. })(BABYLON || (BABYLON = {}));
  20188. //# sourceMappingURL=babylon.sprite.js.map
  20189. var BABYLON;
  20190. (function (BABYLON) {
  20191. var Layer = (function () {
  20192. function Layer(name, imgUrl, scene, isBackground, color) {
  20193. this.name = name;
  20194. this._vertexDeclaration = [2];
  20195. this._vertexStrideSize = 2 * 4;
  20196. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20197. this.isBackground = isBackground === undefined ? true : isBackground;
  20198. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20199. this._scene = scene;
  20200. this._scene.layers.push(this);
  20201. // VBO
  20202. var vertices = [];
  20203. vertices.push(1, 1);
  20204. vertices.push(-1, 1);
  20205. vertices.push(-1, -1);
  20206. vertices.push(1, -1);
  20207. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20208. // Indices
  20209. var indices = [];
  20210. indices.push(0);
  20211. indices.push(1);
  20212. indices.push(2);
  20213. indices.push(0);
  20214. indices.push(2);
  20215. indices.push(3);
  20216. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20217. // Effects
  20218. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20219. }
  20220. Layer.prototype.render = function () {
  20221. // Check
  20222. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20223. return;
  20224. var engine = this._scene.getEngine();
  20225. // Render
  20226. engine.enableEffect(this._effect);
  20227. engine.setState(false);
  20228. // Texture
  20229. this._effect.setTexture("textureSampler", this.texture);
  20230. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20231. // Color
  20232. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20233. // VBOs
  20234. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20235. // Draw order
  20236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20237. engine.draw(true, 0, 6);
  20238. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20239. };
  20240. Layer.prototype.dispose = function () {
  20241. if (this._vertexBuffer) {
  20242. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20243. this._vertexBuffer = null;
  20244. }
  20245. if (this._indexBuffer) {
  20246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20247. this._indexBuffer = null;
  20248. }
  20249. if (this.texture) {
  20250. this.texture.dispose();
  20251. this.texture = null;
  20252. }
  20253. // Remove from scene
  20254. var index = this._scene.layers.indexOf(this);
  20255. this._scene.layers.splice(index, 1);
  20256. // Callback
  20257. if (this.onDispose) {
  20258. this.onDispose();
  20259. }
  20260. };
  20261. return Layer;
  20262. })();
  20263. BABYLON.Layer = Layer;
  20264. })(BABYLON || (BABYLON = {}));
  20265. //# sourceMappingURL=babylon.layer.js.map
  20266. var BABYLON;
  20267. (function (BABYLON) {
  20268. var Particle = (function () {
  20269. function Particle() {
  20270. this.position = BABYLON.Vector3.Zero();
  20271. this.direction = BABYLON.Vector3.Zero();
  20272. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20273. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20274. this.lifeTime = 1.0;
  20275. this.age = 0;
  20276. this.size = 0;
  20277. this.angle = 0;
  20278. this.angularSpeed = 0;
  20279. }
  20280. Particle.prototype.copyTo = function (other) {
  20281. other.position.copyFrom(this.position);
  20282. other.direction.copyFrom(this.direction);
  20283. other.color.copyFrom(this.color);
  20284. other.colorStep.copyFrom(this.colorStep);
  20285. other.lifeTime = this.lifeTime;
  20286. other.age = this.age;
  20287. other.size = this.size;
  20288. other.angle = this.angle;
  20289. other.angularSpeed = this.angularSpeed;
  20290. };
  20291. return Particle;
  20292. })();
  20293. BABYLON.Particle = Particle;
  20294. })(BABYLON || (BABYLON = {}));
  20295. //# sourceMappingURL=babylon.particle.js.map
  20296. var BABYLON;
  20297. (function (BABYLON) {
  20298. var randomNumber = function (min, max) {
  20299. if (min === max) {
  20300. return (min);
  20301. }
  20302. var random = Math.random();
  20303. return ((random * (max - min)) + min);
  20304. };
  20305. var ParticleSystem = (function () {
  20306. function ParticleSystem(name, capacity, scene, customEffect) {
  20307. var _this = this;
  20308. this.name = name;
  20309. this.renderingGroupId = 0;
  20310. this.emitter = null;
  20311. this.emitRate = 10;
  20312. this.manualEmitCount = -1;
  20313. this.updateSpeed = 0.01;
  20314. this.targetStopDuration = 0;
  20315. this.disposeOnStop = false;
  20316. this.minEmitPower = 1;
  20317. this.maxEmitPower = 1;
  20318. this.minLifeTime = 1;
  20319. this.maxLifeTime = 1;
  20320. this.minSize = 1;
  20321. this.maxSize = 1;
  20322. this.minAngularSpeed = 0;
  20323. this.maxAngularSpeed = 0;
  20324. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20325. this.forceDepthWrite = false;
  20326. this.gravity = BABYLON.Vector3.Zero();
  20327. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20328. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20329. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20330. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20331. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20332. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20333. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20334. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20335. this.particles = new Array();
  20336. this._vertexDeclaration = [3, 4, 4];
  20337. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20338. this._stockParticles = new Array();
  20339. this._newPartsExcess = 0;
  20340. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20341. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20342. this._scaledDirection = BABYLON.Vector3.Zero();
  20343. this._scaledGravity = BABYLON.Vector3.Zero();
  20344. this._currentRenderId = -1;
  20345. this._started = false;
  20346. this._stopped = false;
  20347. this._actualFrame = 0;
  20348. this.id = name;
  20349. this._capacity = capacity;
  20350. this._scene = scene;
  20351. this._customEffect = customEffect;
  20352. scene.particleSystems.push(this);
  20353. // VBO
  20354. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20355. var indices = [];
  20356. var index = 0;
  20357. for (var count = 0; count < capacity; count++) {
  20358. indices.push(index);
  20359. indices.push(index + 1);
  20360. indices.push(index + 2);
  20361. indices.push(index);
  20362. indices.push(index + 2);
  20363. indices.push(index + 3);
  20364. index += 4;
  20365. }
  20366. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20367. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20368. // Default behaviors
  20369. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20370. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20371. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20372. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20373. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20374. };
  20375. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20376. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20377. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20378. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20380. };
  20381. this.updateFunction = function (particles) {
  20382. for (var index = 0; index < particles.length; index++) {
  20383. var particle = particles[index];
  20384. particle.age += _this._scaledUpdateSpeed;
  20385. if (particle.age >= particle.lifeTime) {
  20386. _this.recycleParticle(particle);
  20387. index--;
  20388. continue;
  20389. }
  20390. else {
  20391. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20392. particle.color.addInPlace(_this._scaledColorStep);
  20393. if (particle.color.a < 0)
  20394. particle.color.a = 0;
  20395. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20396. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20397. particle.position.addInPlace(_this._scaledDirection);
  20398. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20399. particle.direction.addInPlace(_this._scaledGravity);
  20400. }
  20401. }
  20402. };
  20403. }
  20404. ParticleSystem.prototype.recycleParticle = function (particle) {
  20405. var lastParticle = this.particles.pop();
  20406. if (lastParticle !== particle) {
  20407. lastParticle.copyTo(particle);
  20408. this._stockParticles.push(lastParticle);
  20409. }
  20410. };
  20411. ParticleSystem.prototype.getCapacity = function () {
  20412. return this._capacity;
  20413. };
  20414. ParticleSystem.prototype.isAlive = function () {
  20415. return this._alive;
  20416. };
  20417. ParticleSystem.prototype.isStarted = function () {
  20418. return this._started;
  20419. };
  20420. ParticleSystem.prototype.start = function () {
  20421. this._started = true;
  20422. this._stopped = false;
  20423. this._actualFrame = 0;
  20424. };
  20425. ParticleSystem.prototype.stop = function () {
  20426. this._stopped = true;
  20427. };
  20428. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20429. var offset = index * 11;
  20430. this._vertices[offset] = particle.position.x;
  20431. this._vertices[offset + 1] = particle.position.y;
  20432. this._vertices[offset + 2] = particle.position.z;
  20433. this._vertices[offset + 3] = particle.color.r;
  20434. this._vertices[offset + 4] = particle.color.g;
  20435. this._vertices[offset + 5] = particle.color.b;
  20436. this._vertices[offset + 6] = particle.color.a;
  20437. this._vertices[offset + 7] = particle.angle;
  20438. this._vertices[offset + 8] = particle.size;
  20439. this._vertices[offset + 9] = offsetX;
  20440. this._vertices[offset + 10] = offsetY;
  20441. };
  20442. ParticleSystem.prototype._update = function (newParticles) {
  20443. // Update current
  20444. this._alive = this.particles.length > 0;
  20445. this.updateFunction(this.particles);
  20446. // Add new ones
  20447. var worldMatrix;
  20448. if (this.emitter.position) {
  20449. worldMatrix = this.emitter.getWorldMatrix();
  20450. }
  20451. else {
  20452. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20453. }
  20454. for (var index = 0; index < newParticles; index++) {
  20455. if (this.particles.length === this._capacity) {
  20456. break;
  20457. }
  20458. if (this._stockParticles.length !== 0) {
  20459. var particle = this._stockParticles.pop();
  20460. particle.age = 0;
  20461. }
  20462. else {
  20463. particle = new BABYLON.Particle();
  20464. }
  20465. this.particles.push(particle);
  20466. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20467. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20468. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20469. particle.size = randomNumber(this.minSize, this.maxSize);
  20470. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20471. this.startPositionFunction(worldMatrix, particle.position);
  20472. var step = randomNumber(0, 1.0);
  20473. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20474. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20475. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20476. }
  20477. };
  20478. ParticleSystem.prototype._getEffect = function () {
  20479. if (this._customEffect) {
  20480. return this._customEffect;
  20481. }
  20482. ;
  20483. var defines = [];
  20484. if (this._scene.clipPlane) {
  20485. defines.push("#define CLIPPLANE");
  20486. }
  20487. // Effect
  20488. var join = defines.join("\n");
  20489. if (this._cachedDefines !== join) {
  20490. this._cachedDefines = join;
  20491. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20492. }
  20493. return this._effect;
  20494. };
  20495. ParticleSystem.prototype.animate = function () {
  20496. if (!this._started)
  20497. return;
  20498. var effect = this._getEffect();
  20499. // Check
  20500. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20501. return;
  20502. if (this._currentRenderId === this._scene.getRenderId()) {
  20503. return;
  20504. }
  20505. this._currentRenderId = this._scene.getRenderId();
  20506. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20507. // determine the number of particles we need to create
  20508. var emitCout;
  20509. if (this.manualEmitCount > -1) {
  20510. emitCout = this.manualEmitCount;
  20511. this.manualEmitCount = 0;
  20512. }
  20513. else {
  20514. emitCout = this.emitRate;
  20515. }
  20516. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20517. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20518. if (this._newPartsExcess > 1.0) {
  20519. newParticles += this._newPartsExcess >> 0;
  20520. this._newPartsExcess -= this._newPartsExcess >> 0;
  20521. }
  20522. this._alive = false;
  20523. if (!this._stopped) {
  20524. this._actualFrame += this._scaledUpdateSpeed;
  20525. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20526. this.stop();
  20527. }
  20528. else {
  20529. newParticles = 0;
  20530. }
  20531. this._update(newParticles);
  20532. // Stopped?
  20533. if (this._stopped) {
  20534. if (!this._alive) {
  20535. this._started = false;
  20536. if (this.disposeOnStop) {
  20537. this._scene._toBeDisposed.push(this);
  20538. }
  20539. }
  20540. }
  20541. // Update VBO
  20542. var offset = 0;
  20543. for (var index = 0; index < this.particles.length; index++) {
  20544. var particle = this.particles[index];
  20545. this._appendParticleVertex(offset++, particle, 0, 0);
  20546. this._appendParticleVertex(offset++, particle, 1, 0);
  20547. this._appendParticleVertex(offset++, particle, 1, 1);
  20548. this._appendParticleVertex(offset++, particle, 0, 1);
  20549. }
  20550. var engine = this._scene.getEngine();
  20551. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20552. };
  20553. ParticleSystem.prototype.render = function () {
  20554. var effect = this._getEffect();
  20555. // Check
  20556. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20557. return 0;
  20558. var engine = this._scene.getEngine();
  20559. // Render
  20560. engine.enableEffect(effect);
  20561. engine.setState(false);
  20562. var viewMatrix = this._scene.getViewMatrix();
  20563. effect.setTexture("diffuseSampler", this.particleTexture);
  20564. effect.setMatrix("view", viewMatrix);
  20565. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20566. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20567. if (this._scene.clipPlane) {
  20568. var clipPlane = this._scene.clipPlane;
  20569. var invView = viewMatrix.clone();
  20570. invView.invert();
  20571. effect.setMatrix("invView", invView);
  20572. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20573. }
  20574. // VBOs
  20575. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20576. // Draw order
  20577. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20578. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20579. }
  20580. else {
  20581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20582. }
  20583. if (this.forceDepthWrite) {
  20584. engine.setDepthWrite(true);
  20585. }
  20586. engine.draw(true, 0, this.particles.length * 6);
  20587. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20588. return this.particles.length;
  20589. };
  20590. ParticleSystem.prototype.dispose = function () {
  20591. if (this._vertexBuffer) {
  20592. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20593. this._vertexBuffer = null;
  20594. }
  20595. if (this._indexBuffer) {
  20596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20597. this._indexBuffer = null;
  20598. }
  20599. if (this.particleTexture) {
  20600. this.particleTexture.dispose();
  20601. this.particleTexture = null;
  20602. }
  20603. // Remove from scene
  20604. var index = this._scene.particleSystems.indexOf(this);
  20605. this._scene.particleSystems.splice(index, 1);
  20606. // Callback
  20607. if (this.onDispose) {
  20608. this.onDispose();
  20609. }
  20610. };
  20611. // Clone
  20612. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20613. var result = new ParticleSystem(name, this._capacity, this._scene);
  20614. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20615. if (newEmitter === undefined) {
  20616. newEmitter = this.emitter;
  20617. }
  20618. result.emitter = newEmitter;
  20619. if (this.particleTexture) {
  20620. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20621. }
  20622. result.start();
  20623. return result;
  20624. };
  20625. // Statics
  20626. ParticleSystem.BLENDMODE_ONEONE = 0;
  20627. ParticleSystem.BLENDMODE_STANDARD = 1;
  20628. return ParticleSystem;
  20629. })();
  20630. BABYLON.ParticleSystem = ParticleSystem;
  20631. })(BABYLON || (BABYLON = {}));
  20632. //# sourceMappingURL=babylon.particleSystem.js.map
  20633. var BABYLON;
  20634. (function (BABYLON) {
  20635. var Animation = (function () {
  20636. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20637. this.name = name;
  20638. this.targetProperty = targetProperty;
  20639. this.framePerSecond = framePerSecond;
  20640. this.dataType = dataType;
  20641. this.loopMode = loopMode;
  20642. this._offsetsCache = {};
  20643. this._highLimitsCache = {};
  20644. this._stopped = false;
  20645. this.targetPropertyPath = targetProperty.split(".");
  20646. this.dataType = dataType;
  20647. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20648. }
  20649. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20650. var dataType = undefined;
  20651. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20652. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20653. }
  20654. else if (from instanceof BABYLON.Quaternion) {
  20655. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20656. }
  20657. else if (from instanceof BABYLON.Vector3) {
  20658. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20659. }
  20660. else if (from instanceof BABYLON.Vector2) {
  20661. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20662. }
  20663. else if (from instanceof BABYLON.Color3) {
  20664. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20665. }
  20666. if (dataType == undefined) {
  20667. return null;
  20668. }
  20669. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20670. var keys = [];
  20671. keys.push({ frame: 0, value: from });
  20672. keys.push({ frame: totalFrame, value: to });
  20673. animation.setKeys(keys);
  20674. mesh.animations.push(animation);
  20675. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20676. };
  20677. // Methods
  20678. Animation.prototype.isStopped = function () {
  20679. return this._stopped;
  20680. };
  20681. Animation.prototype.getKeys = function () {
  20682. return this._keys;
  20683. };
  20684. Animation.prototype.getEasingFunction = function () {
  20685. return this._easingFunction;
  20686. };
  20687. Animation.prototype.setEasingFunction = function (easingFunction) {
  20688. this._easingFunction = easingFunction;
  20689. };
  20690. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20691. return startValue + (endValue - startValue) * gradient;
  20692. };
  20693. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20694. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20695. };
  20696. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20697. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20698. };
  20699. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20700. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20701. };
  20702. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20703. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20704. };
  20705. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20706. var startScale = new BABYLON.Vector3(0, 0, 0);
  20707. var startRotation = new BABYLON.Quaternion();
  20708. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20709. startValue.decompose(startScale, startRotation, startTranslation);
  20710. var endScale = new BABYLON.Vector3(0, 0, 0);
  20711. var endRotation = new BABYLON.Quaternion();
  20712. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20713. endValue.decompose(endScale, endRotation, endTranslation);
  20714. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20715. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20716. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20717. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20718. return result;
  20719. };
  20720. Animation.prototype.clone = function () {
  20721. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20722. clone.setKeys(this._keys);
  20723. return clone;
  20724. };
  20725. Animation.prototype.setKeys = function (values) {
  20726. this._keys = values.slice(0);
  20727. this._offsetsCache = {};
  20728. this._highLimitsCache = {};
  20729. };
  20730. Animation.prototype._getKeyValue = function (value) {
  20731. if (typeof value === "function") {
  20732. return value();
  20733. }
  20734. return value;
  20735. };
  20736. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20737. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20738. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20739. }
  20740. this.currentFrame = currentFrame;
  20741. // Try to get a hash to find the right key
  20742. 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));
  20743. if (this._keys[startKey].frame >= currentFrame) {
  20744. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20745. startKey--;
  20746. }
  20747. }
  20748. for (var key = startKey; key < this._keys.length; key++) {
  20749. if (this._keys[key + 1].frame >= currentFrame) {
  20750. var startValue = this._getKeyValue(this._keys[key].value);
  20751. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20752. // gradient : percent of currentFrame between the frame inf and the frame sup
  20753. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20754. // check for easingFunction and correction of gradient
  20755. if (this._easingFunction != null) {
  20756. gradient = this._easingFunction.ease(gradient);
  20757. }
  20758. switch (this.dataType) {
  20759. // Float
  20760. case Animation.ANIMATIONTYPE_FLOAT:
  20761. switch (loopMode) {
  20762. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20763. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20764. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20765. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20766. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20767. }
  20768. break;
  20769. // Quaternion
  20770. case Animation.ANIMATIONTYPE_QUATERNION:
  20771. var quaternion = null;
  20772. switch (loopMode) {
  20773. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20774. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20775. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20776. break;
  20777. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20778. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20779. break;
  20780. }
  20781. return quaternion;
  20782. // Vector3
  20783. case Animation.ANIMATIONTYPE_VECTOR3:
  20784. switch (loopMode) {
  20785. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20786. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20787. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20788. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20789. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20790. }
  20791. // Vector2
  20792. case Animation.ANIMATIONTYPE_VECTOR2:
  20793. switch (loopMode) {
  20794. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20795. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20796. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20797. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20798. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20799. }
  20800. // Color3
  20801. case Animation.ANIMATIONTYPE_COLOR3:
  20802. switch (loopMode) {
  20803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20805. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20807. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20808. }
  20809. // Matrix
  20810. case Animation.ANIMATIONTYPE_MATRIX:
  20811. switch (loopMode) {
  20812. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20813. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20814. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20815. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20816. return startValue;
  20817. }
  20818. default:
  20819. break;
  20820. }
  20821. break;
  20822. }
  20823. }
  20824. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20825. };
  20826. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20827. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20828. this._stopped = true;
  20829. return false;
  20830. }
  20831. var returnValue = true;
  20832. // Adding a start key at frame 0 if missing
  20833. if (this._keys[0].frame !== 0) {
  20834. var newKey = { frame: 0, value: this._keys[0].value };
  20835. this._keys.splice(0, 0, newKey);
  20836. }
  20837. // Check limits
  20838. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20839. from = this._keys[0].frame;
  20840. }
  20841. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20842. to = this._keys[this._keys.length - 1].frame;
  20843. }
  20844. // Compute ratio
  20845. var range = to - from;
  20846. var offsetValue;
  20847. // ratio represents the frame delta between from and to
  20848. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20849. var highLimitValue = 0;
  20850. if (ratio > range && !loop) {
  20851. returnValue = false;
  20852. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20853. }
  20854. else {
  20855. // Get max value if required
  20856. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20857. var keyOffset = to.toString() + from.toString();
  20858. if (!this._offsetsCache[keyOffset]) {
  20859. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20860. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20861. switch (this.dataType) {
  20862. // Float
  20863. case Animation.ANIMATIONTYPE_FLOAT:
  20864. this._offsetsCache[keyOffset] = toValue - fromValue;
  20865. break;
  20866. // Quaternion
  20867. case Animation.ANIMATIONTYPE_QUATERNION:
  20868. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20869. break;
  20870. // Vector3
  20871. case Animation.ANIMATIONTYPE_VECTOR3:
  20872. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20873. // Vector2
  20874. case Animation.ANIMATIONTYPE_VECTOR2:
  20875. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20876. // Color3
  20877. case Animation.ANIMATIONTYPE_COLOR3:
  20878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20879. default:
  20880. break;
  20881. }
  20882. this._highLimitsCache[keyOffset] = toValue;
  20883. }
  20884. highLimitValue = this._highLimitsCache[keyOffset];
  20885. offsetValue = this._offsetsCache[keyOffset];
  20886. }
  20887. }
  20888. if (offsetValue === undefined) {
  20889. switch (this.dataType) {
  20890. // Float
  20891. case Animation.ANIMATIONTYPE_FLOAT:
  20892. offsetValue = 0;
  20893. break;
  20894. // Quaternion
  20895. case Animation.ANIMATIONTYPE_QUATERNION:
  20896. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20897. break;
  20898. // Vector3
  20899. case Animation.ANIMATIONTYPE_VECTOR3:
  20900. offsetValue = BABYLON.Vector3.Zero();
  20901. break;
  20902. // Vector2
  20903. case Animation.ANIMATIONTYPE_VECTOR2:
  20904. offsetValue = BABYLON.Vector2.Zero();
  20905. break;
  20906. // Color3
  20907. case Animation.ANIMATIONTYPE_COLOR3:
  20908. offsetValue = BABYLON.Color3.Black();
  20909. }
  20910. }
  20911. // Compute value
  20912. var repeatCount = (ratio / range) >> 0;
  20913. var currentFrame = returnValue ? from + ratio % range : to;
  20914. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  20915. // Set value
  20916. if (this.targetPropertyPath.length > 1) {
  20917. var property = this._target[this.targetPropertyPath[0]];
  20918. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  20919. property = property[this.targetPropertyPath[index]];
  20920. }
  20921. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  20922. }
  20923. else {
  20924. this._target[this.targetPropertyPath[0]] = currentValue;
  20925. }
  20926. if (this._target.markAsDirty) {
  20927. this._target.markAsDirty(this.targetProperty);
  20928. }
  20929. if (!returnValue) {
  20930. this._stopped = true;
  20931. }
  20932. return returnValue;
  20933. };
  20934. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  20935. get: function () {
  20936. return Animation._ANIMATIONTYPE_FLOAT;
  20937. },
  20938. enumerable: true,
  20939. configurable: true
  20940. });
  20941. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  20942. get: function () {
  20943. return Animation._ANIMATIONTYPE_VECTOR3;
  20944. },
  20945. enumerable: true,
  20946. configurable: true
  20947. });
  20948. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  20949. get: function () {
  20950. return Animation._ANIMATIONTYPE_VECTOR2;
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  20956. get: function () {
  20957. return Animation._ANIMATIONTYPE_QUATERNION;
  20958. },
  20959. enumerable: true,
  20960. configurable: true
  20961. });
  20962. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  20963. get: function () {
  20964. return Animation._ANIMATIONTYPE_MATRIX;
  20965. },
  20966. enumerable: true,
  20967. configurable: true
  20968. });
  20969. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  20970. get: function () {
  20971. return Animation._ANIMATIONTYPE_COLOR3;
  20972. },
  20973. enumerable: true,
  20974. configurable: true
  20975. });
  20976. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  20977. get: function () {
  20978. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  20984. get: function () {
  20985. return Animation._ANIMATIONLOOPMODE_CYCLE;
  20986. },
  20987. enumerable: true,
  20988. configurable: true
  20989. });
  20990. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  20991. get: function () {
  20992. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. // Statics
  20998. Animation._ANIMATIONTYPE_FLOAT = 0;
  20999. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21000. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21001. Animation._ANIMATIONTYPE_MATRIX = 3;
  21002. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21003. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21004. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21005. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21006. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21007. return Animation;
  21008. })();
  21009. BABYLON.Animation = Animation;
  21010. })(BABYLON || (BABYLON = {}));
  21011. //# sourceMappingURL=babylon.animation.js.map
  21012. var BABYLON;
  21013. (function (BABYLON) {
  21014. var Animatable = (function () {
  21015. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21016. if (fromFrame === void 0) { fromFrame = 0; }
  21017. if (toFrame === void 0) { toFrame = 100; }
  21018. if (loopAnimation === void 0) { loopAnimation = false; }
  21019. if (speedRatio === void 0) { speedRatio = 1.0; }
  21020. this.target = target;
  21021. this.fromFrame = fromFrame;
  21022. this.toFrame = toFrame;
  21023. this.loopAnimation = loopAnimation;
  21024. this.speedRatio = speedRatio;
  21025. this.onAnimationEnd = onAnimationEnd;
  21026. this._animations = new Array();
  21027. this._paused = false;
  21028. this.animationStarted = false;
  21029. if (animations) {
  21030. this.appendAnimations(target, animations);
  21031. }
  21032. this._scene = scene;
  21033. scene._activeAnimatables.push(this);
  21034. }
  21035. // Methods
  21036. Animatable.prototype.appendAnimations = function (target, animations) {
  21037. for (var index = 0; index < animations.length; index++) {
  21038. var animation = animations[index];
  21039. animation._target = target;
  21040. this._animations.push(animation);
  21041. }
  21042. };
  21043. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21044. var animations = this._animations;
  21045. for (var index = 0; index < animations.length; index++) {
  21046. if (animations[index].targetProperty === property) {
  21047. return animations[index];
  21048. }
  21049. }
  21050. return null;
  21051. };
  21052. Animatable.prototype.pause = function () {
  21053. if (this._paused) {
  21054. return;
  21055. }
  21056. this._paused = true;
  21057. };
  21058. Animatable.prototype.restart = function () {
  21059. this._paused = false;
  21060. };
  21061. Animatable.prototype.stop = function () {
  21062. var index = this._scene._activeAnimatables.indexOf(this);
  21063. if (index > -1) {
  21064. this._scene._activeAnimatables.splice(index, 1);
  21065. }
  21066. if (this.onAnimationEnd) {
  21067. this.onAnimationEnd();
  21068. }
  21069. };
  21070. Animatable.prototype._animate = function (delay) {
  21071. if (this._paused) {
  21072. if (!this._pausedDelay) {
  21073. this._pausedDelay = delay;
  21074. }
  21075. return true;
  21076. }
  21077. if (!this._localDelayOffset) {
  21078. this._localDelayOffset = delay;
  21079. }
  21080. else if (this._pausedDelay) {
  21081. this._localDelayOffset += delay - this._pausedDelay;
  21082. this._pausedDelay = null;
  21083. }
  21084. // Animating
  21085. var running = false;
  21086. var animations = this._animations;
  21087. for (var index = 0; index < animations.length; index++) {
  21088. var animation = animations[index];
  21089. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21090. running = running || isRunning;
  21091. }
  21092. if (!running) {
  21093. // Remove from active animatables
  21094. index = this._scene._activeAnimatables.indexOf(this);
  21095. this._scene._activeAnimatables.splice(index, 1);
  21096. }
  21097. if (!running && this.onAnimationEnd) {
  21098. this.onAnimationEnd();
  21099. }
  21100. return running;
  21101. };
  21102. return Animatable;
  21103. })();
  21104. BABYLON.Animatable = Animatable;
  21105. })(BABYLON || (BABYLON = {}));
  21106. //# sourceMappingURL=babylon.animatable.js.map
  21107. var BABYLON;
  21108. (function (BABYLON) {
  21109. var EasingFunction = (function () {
  21110. function EasingFunction() {
  21111. // Properties
  21112. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21113. }
  21114. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21115. get: function () {
  21116. return EasingFunction._EASINGMODE_EASEIN;
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21122. get: function () {
  21123. return EasingFunction._EASINGMODE_EASEOUT;
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21129. get: function () {
  21130. return EasingFunction._EASINGMODE_EASEINOUT;
  21131. },
  21132. enumerable: true,
  21133. configurable: true
  21134. });
  21135. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21136. var n = Math.min(Math.max(easingMode, 0), 2);
  21137. this._easingMode = n;
  21138. };
  21139. EasingFunction.prototype.getEasingMode = function () {
  21140. return this._easingMode;
  21141. };
  21142. EasingFunction.prototype.easeInCore = function (gradient) {
  21143. throw new Error('You must implement this method');
  21144. };
  21145. EasingFunction.prototype.ease = function (gradient) {
  21146. switch (this._easingMode) {
  21147. case EasingFunction.EASINGMODE_EASEIN:
  21148. return this.easeInCore(gradient);
  21149. case EasingFunction.EASINGMODE_EASEOUT:
  21150. return (1 - this.easeInCore(1 - gradient));
  21151. }
  21152. if (gradient >= 0.5) {
  21153. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21154. }
  21155. return (this.easeInCore(gradient * 2) * 0.5);
  21156. };
  21157. //Statics
  21158. EasingFunction._EASINGMODE_EASEIN = 0;
  21159. EasingFunction._EASINGMODE_EASEOUT = 1;
  21160. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21161. return EasingFunction;
  21162. })();
  21163. BABYLON.EasingFunction = EasingFunction;
  21164. var CircleEase = (function (_super) {
  21165. __extends(CircleEase, _super);
  21166. function CircleEase() {
  21167. _super.apply(this, arguments);
  21168. }
  21169. CircleEase.prototype.easeInCore = function (gradient) {
  21170. gradient = Math.max(0, Math.min(1, gradient));
  21171. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21172. };
  21173. return CircleEase;
  21174. })(EasingFunction);
  21175. BABYLON.CircleEase = CircleEase;
  21176. var BackEase = (function (_super) {
  21177. __extends(BackEase, _super);
  21178. function BackEase(amplitude) {
  21179. if (amplitude === void 0) { amplitude = 1; }
  21180. _super.call(this);
  21181. this.amplitude = amplitude;
  21182. }
  21183. BackEase.prototype.easeInCore = function (gradient) {
  21184. var num = Math.max(0, this.amplitude);
  21185. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21186. };
  21187. return BackEase;
  21188. })(EasingFunction);
  21189. BABYLON.BackEase = BackEase;
  21190. var BounceEase = (function (_super) {
  21191. __extends(BounceEase, _super);
  21192. function BounceEase(bounces, bounciness) {
  21193. if (bounces === void 0) { bounces = 3; }
  21194. if (bounciness === void 0) { bounciness = 2; }
  21195. _super.call(this);
  21196. this.bounces = bounces;
  21197. this.bounciness = bounciness;
  21198. }
  21199. BounceEase.prototype.easeInCore = function (gradient) {
  21200. var y = Math.max(0.0, this.bounces);
  21201. var bounciness = this.bounciness;
  21202. if (bounciness <= 1.0) {
  21203. bounciness = 1.001;
  21204. }
  21205. var num9 = Math.pow(bounciness, y);
  21206. var num5 = 1.0 - bounciness;
  21207. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21208. var num15 = gradient * num4;
  21209. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21210. var num3 = Math.floor(num65);
  21211. var num13 = num3 + 1.0;
  21212. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21213. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21214. var num7 = (num8 + num12) * 0.5;
  21215. var num6 = gradient - num7;
  21216. var num2 = num7 - num8;
  21217. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21218. };
  21219. return BounceEase;
  21220. })(EasingFunction);
  21221. BABYLON.BounceEase = BounceEase;
  21222. var CubicEase = (function (_super) {
  21223. __extends(CubicEase, _super);
  21224. function CubicEase() {
  21225. _super.apply(this, arguments);
  21226. }
  21227. CubicEase.prototype.easeInCore = function (gradient) {
  21228. return (gradient * gradient * gradient);
  21229. };
  21230. return CubicEase;
  21231. })(EasingFunction);
  21232. BABYLON.CubicEase = CubicEase;
  21233. var ElasticEase = (function (_super) {
  21234. __extends(ElasticEase, _super);
  21235. function ElasticEase(oscillations, springiness) {
  21236. if (oscillations === void 0) { oscillations = 3; }
  21237. if (springiness === void 0) { springiness = 3; }
  21238. _super.call(this);
  21239. this.oscillations = oscillations;
  21240. this.springiness = springiness;
  21241. }
  21242. ElasticEase.prototype.easeInCore = function (gradient) {
  21243. var num2;
  21244. var num3 = Math.max(0.0, this.oscillations);
  21245. var num = Math.max(0.0, this.springiness);
  21246. if (num == 0) {
  21247. num2 = gradient;
  21248. }
  21249. else {
  21250. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21251. }
  21252. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21253. };
  21254. return ElasticEase;
  21255. })(EasingFunction);
  21256. BABYLON.ElasticEase = ElasticEase;
  21257. var ExponentialEase = (function (_super) {
  21258. __extends(ExponentialEase, _super);
  21259. function ExponentialEase(exponent) {
  21260. if (exponent === void 0) { exponent = 2; }
  21261. _super.call(this);
  21262. this.exponent = exponent;
  21263. }
  21264. ExponentialEase.prototype.easeInCore = function (gradient) {
  21265. if (this.exponent <= 0) {
  21266. return gradient;
  21267. }
  21268. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21269. };
  21270. return ExponentialEase;
  21271. })(EasingFunction);
  21272. BABYLON.ExponentialEase = ExponentialEase;
  21273. var PowerEase = (function (_super) {
  21274. __extends(PowerEase, _super);
  21275. function PowerEase(power) {
  21276. if (power === void 0) { power = 2; }
  21277. _super.call(this);
  21278. this.power = power;
  21279. }
  21280. PowerEase.prototype.easeInCore = function (gradient) {
  21281. var y = Math.max(0.0, this.power);
  21282. return Math.pow(gradient, y);
  21283. };
  21284. return PowerEase;
  21285. })(EasingFunction);
  21286. BABYLON.PowerEase = PowerEase;
  21287. var QuadraticEase = (function (_super) {
  21288. __extends(QuadraticEase, _super);
  21289. function QuadraticEase() {
  21290. _super.apply(this, arguments);
  21291. }
  21292. QuadraticEase.prototype.easeInCore = function (gradient) {
  21293. return (gradient * gradient);
  21294. };
  21295. return QuadraticEase;
  21296. })(EasingFunction);
  21297. BABYLON.QuadraticEase = QuadraticEase;
  21298. var QuarticEase = (function (_super) {
  21299. __extends(QuarticEase, _super);
  21300. function QuarticEase() {
  21301. _super.apply(this, arguments);
  21302. }
  21303. QuarticEase.prototype.easeInCore = function (gradient) {
  21304. return (gradient * gradient * gradient * gradient);
  21305. };
  21306. return QuarticEase;
  21307. })(EasingFunction);
  21308. BABYLON.QuarticEase = QuarticEase;
  21309. var QuinticEase = (function (_super) {
  21310. __extends(QuinticEase, _super);
  21311. function QuinticEase() {
  21312. _super.apply(this, arguments);
  21313. }
  21314. QuinticEase.prototype.easeInCore = function (gradient) {
  21315. return (gradient * gradient * gradient * gradient * gradient);
  21316. };
  21317. return QuinticEase;
  21318. })(EasingFunction);
  21319. BABYLON.QuinticEase = QuinticEase;
  21320. var SineEase = (function (_super) {
  21321. __extends(SineEase, _super);
  21322. function SineEase() {
  21323. _super.apply(this, arguments);
  21324. }
  21325. SineEase.prototype.easeInCore = function (gradient) {
  21326. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21327. };
  21328. return SineEase;
  21329. })(EasingFunction);
  21330. BABYLON.SineEase = SineEase;
  21331. var BezierCurveEase = (function (_super) {
  21332. __extends(BezierCurveEase, _super);
  21333. function BezierCurveEase(x1, y1, x2, y2) {
  21334. if (x1 === void 0) { x1 = 0; }
  21335. if (y1 === void 0) { y1 = 0; }
  21336. if (x2 === void 0) { x2 = 1; }
  21337. if (y2 === void 0) { y2 = 1; }
  21338. _super.call(this);
  21339. this.x1 = x1;
  21340. this.y1 = y1;
  21341. this.x2 = x2;
  21342. this.y2 = y2;
  21343. }
  21344. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21345. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21346. };
  21347. return BezierCurveEase;
  21348. })(EasingFunction);
  21349. BABYLON.BezierCurveEase = BezierCurveEase;
  21350. })(BABYLON || (BABYLON = {}));
  21351. //# sourceMappingURL=babylon.easing.js.map
  21352. var BABYLON;
  21353. (function (BABYLON) {
  21354. var Octree = (function () {
  21355. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21356. if (maxDepth === void 0) { maxDepth = 2; }
  21357. this.maxDepth = maxDepth;
  21358. this.dynamicContent = new Array();
  21359. this._maxBlockCapacity = maxBlockCapacity || 64;
  21360. this._selectionContent = new BABYLON.SmartArray(1024);
  21361. this._creationFunc = creationFunc;
  21362. }
  21363. // Methods
  21364. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21365. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21366. };
  21367. Octree.prototype.addMesh = function (entry) {
  21368. for (var index = 0; index < this.blocks.length; index++) {
  21369. var block = this.blocks[index];
  21370. block.addEntry(entry);
  21371. }
  21372. };
  21373. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21374. this._selectionContent.reset();
  21375. for (var index = 0; index < this.blocks.length; index++) {
  21376. var block = this.blocks[index];
  21377. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21378. }
  21379. if (allowDuplicate) {
  21380. this._selectionContent.concat(this.dynamicContent);
  21381. }
  21382. else {
  21383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21384. }
  21385. return this._selectionContent;
  21386. };
  21387. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21388. this._selectionContent.reset();
  21389. for (var index = 0; index < this.blocks.length; index++) {
  21390. var block = this.blocks[index];
  21391. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21392. }
  21393. if (allowDuplicate) {
  21394. this._selectionContent.concat(this.dynamicContent);
  21395. }
  21396. else {
  21397. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21398. }
  21399. return this._selectionContent;
  21400. };
  21401. Octree.prototype.intersectsRay = function (ray) {
  21402. this._selectionContent.reset();
  21403. for (var index = 0; index < this.blocks.length; index++) {
  21404. var block = this.blocks[index];
  21405. block.intersectsRay(ray, this._selectionContent);
  21406. }
  21407. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21408. return this._selectionContent;
  21409. };
  21410. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21411. target.blocks = new Array();
  21412. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21413. // Segmenting space
  21414. for (var x = 0; x < 2; x++) {
  21415. for (var y = 0; y < 2; y++) {
  21416. for (var z = 0; z < 2; z++) {
  21417. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21418. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21419. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21420. block.addEntries(entries);
  21421. target.blocks.push(block);
  21422. }
  21423. }
  21424. }
  21425. };
  21426. Octree.CreationFuncForMeshes = function (entry, block) {
  21427. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21428. block.entries.push(entry);
  21429. }
  21430. };
  21431. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21432. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21433. block.entries.push(entry);
  21434. }
  21435. };
  21436. return Octree;
  21437. })();
  21438. BABYLON.Octree = Octree;
  21439. })(BABYLON || (BABYLON = {}));
  21440. //# sourceMappingURL=babylon.octree.js.map
  21441. var BABYLON;
  21442. (function (BABYLON) {
  21443. var OctreeBlock = (function () {
  21444. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21445. this.entries = new Array();
  21446. this._boundingVectors = new Array();
  21447. this._capacity = capacity;
  21448. this._depth = depth;
  21449. this._maxDepth = maxDepth;
  21450. this._creationFunc = creationFunc;
  21451. this._minPoint = minPoint;
  21452. this._maxPoint = maxPoint;
  21453. this._boundingVectors.push(minPoint.clone());
  21454. this._boundingVectors.push(maxPoint.clone());
  21455. this._boundingVectors.push(minPoint.clone());
  21456. this._boundingVectors[2].x = maxPoint.x;
  21457. this._boundingVectors.push(minPoint.clone());
  21458. this._boundingVectors[3].y = maxPoint.y;
  21459. this._boundingVectors.push(minPoint.clone());
  21460. this._boundingVectors[4].z = maxPoint.z;
  21461. this._boundingVectors.push(maxPoint.clone());
  21462. this._boundingVectors[5].z = minPoint.z;
  21463. this._boundingVectors.push(maxPoint.clone());
  21464. this._boundingVectors[6].x = minPoint.x;
  21465. this._boundingVectors.push(maxPoint.clone());
  21466. this._boundingVectors[7].y = minPoint.y;
  21467. }
  21468. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21469. // Property
  21470. get: function () {
  21471. return this._capacity;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21477. get: function () {
  21478. return this._minPoint;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21484. get: function () {
  21485. return this._maxPoint;
  21486. },
  21487. enumerable: true,
  21488. configurable: true
  21489. });
  21490. // Methods
  21491. OctreeBlock.prototype.addEntry = function (entry) {
  21492. if (this.blocks) {
  21493. for (var index = 0; index < this.blocks.length; index++) {
  21494. var block = this.blocks[index];
  21495. block.addEntry(entry);
  21496. }
  21497. return;
  21498. }
  21499. this._creationFunc(entry, this);
  21500. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21501. this.createInnerBlocks();
  21502. }
  21503. };
  21504. OctreeBlock.prototype.addEntries = function (entries) {
  21505. for (var index = 0; index < entries.length; index++) {
  21506. var mesh = entries[index];
  21507. this.addEntry(mesh);
  21508. }
  21509. };
  21510. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21511. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21512. if (this.blocks) {
  21513. for (var index = 0; index < this.blocks.length; index++) {
  21514. var block = this.blocks[index];
  21515. block.select(frustumPlanes, selection, allowDuplicate);
  21516. }
  21517. return;
  21518. }
  21519. if (allowDuplicate) {
  21520. selection.concat(this.entries);
  21521. }
  21522. else {
  21523. selection.concatWithNoDuplicate(this.entries);
  21524. }
  21525. }
  21526. };
  21527. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21528. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21529. if (this.blocks) {
  21530. for (var index = 0; index < this.blocks.length; index++) {
  21531. var block = this.blocks[index];
  21532. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21533. }
  21534. return;
  21535. }
  21536. if (allowDuplicate) {
  21537. selection.concat(this.entries);
  21538. }
  21539. else {
  21540. selection.concatWithNoDuplicate(this.entries);
  21541. }
  21542. }
  21543. };
  21544. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21545. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21546. if (this.blocks) {
  21547. for (var index = 0; index < this.blocks.length; index++) {
  21548. var block = this.blocks[index];
  21549. block.intersectsRay(ray, selection);
  21550. }
  21551. return;
  21552. }
  21553. selection.concatWithNoDuplicate(this.entries);
  21554. }
  21555. };
  21556. OctreeBlock.prototype.createInnerBlocks = function () {
  21557. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21558. };
  21559. return OctreeBlock;
  21560. })();
  21561. BABYLON.OctreeBlock = OctreeBlock;
  21562. })(BABYLON || (BABYLON = {}));
  21563. //# sourceMappingURL=babylon.octreeBlock.js.map
  21564. var BABYLON;
  21565. (function (BABYLON) {
  21566. var Bone = (function () {
  21567. function Bone(name, skeleton, parentBone, matrix) {
  21568. this.name = name;
  21569. this.children = new Array();
  21570. this.animations = new Array();
  21571. this._worldTransform = new BABYLON.Matrix();
  21572. this._absoluteTransform = new BABYLON.Matrix();
  21573. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21574. this._skeleton = skeleton;
  21575. this._matrix = matrix;
  21576. this._baseMatrix = matrix;
  21577. skeleton.bones.push(this);
  21578. if (parentBone) {
  21579. this._parent = parentBone;
  21580. parentBone.children.push(this);
  21581. }
  21582. else {
  21583. this._parent = null;
  21584. }
  21585. this._updateDifferenceMatrix();
  21586. }
  21587. // Members
  21588. Bone.prototype.getParent = function () {
  21589. return this._parent;
  21590. };
  21591. Bone.prototype.getLocalMatrix = function () {
  21592. return this._matrix;
  21593. };
  21594. Bone.prototype.getBaseMatrix = function () {
  21595. return this._baseMatrix;
  21596. };
  21597. Bone.prototype.getWorldMatrix = function () {
  21598. return this._worldTransform;
  21599. };
  21600. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21601. return this._invertedAbsoluteTransform;
  21602. };
  21603. Bone.prototype.getAbsoluteMatrix = function () {
  21604. var matrix = this._matrix.clone();
  21605. var parent = this._parent;
  21606. while (parent) {
  21607. matrix = matrix.multiply(parent.getLocalMatrix());
  21608. parent = parent.getParent();
  21609. }
  21610. return matrix;
  21611. };
  21612. // Methods
  21613. Bone.prototype.updateMatrix = function (matrix) {
  21614. this._matrix = matrix;
  21615. this._skeleton._markAsDirty();
  21616. this._updateDifferenceMatrix();
  21617. };
  21618. Bone.prototype._updateDifferenceMatrix = function () {
  21619. if (this._parent) {
  21620. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21621. }
  21622. else {
  21623. this._absoluteTransform.copyFrom(this._matrix);
  21624. }
  21625. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21626. for (var index = 0; index < this.children.length; index++) {
  21627. this.children[index]._updateDifferenceMatrix();
  21628. }
  21629. };
  21630. Bone.prototype.markAsDirty = function () {
  21631. this._skeleton._markAsDirty();
  21632. };
  21633. return Bone;
  21634. })();
  21635. BABYLON.Bone = Bone;
  21636. })(BABYLON || (BABYLON = {}));
  21637. //# sourceMappingURL=babylon.bone.js.map
  21638. var BABYLON;
  21639. (function (BABYLON) {
  21640. var Skeleton = (function () {
  21641. function Skeleton(name, id, scene) {
  21642. this.name = name;
  21643. this.id = id;
  21644. this.bones = new Array();
  21645. this._isDirty = true;
  21646. this._identity = BABYLON.Matrix.Identity();
  21647. this.bones = [];
  21648. this._scene = scene;
  21649. scene.skeletons.push(this);
  21650. this.prepare();
  21651. //make sure it will recalculate the matrix next time prepare is called.
  21652. this._isDirty = true;
  21653. }
  21654. // Members
  21655. Skeleton.prototype.getTransformMatrices = function () {
  21656. return this._transformMatrices;
  21657. };
  21658. // Methods
  21659. Skeleton.prototype._markAsDirty = function () {
  21660. this._isDirty = true;
  21661. };
  21662. Skeleton.prototype.prepare = function () {
  21663. if (!this._isDirty) {
  21664. return;
  21665. }
  21666. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21667. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21668. }
  21669. for (var index = 0; index < this.bones.length; index++) {
  21670. var bone = this.bones[index];
  21671. var parentBone = bone.getParent();
  21672. if (parentBone) {
  21673. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21674. }
  21675. else {
  21676. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21677. }
  21678. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21679. }
  21680. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21681. this._isDirty = false;
  21682. this._scene._activeBones += this.bones.length;
  21683. };
  21684. Skeleton.prototype.getAnimatables = function () {
  21685. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21686. this._animatables = [];
  21687. for (var index = 0; index < this.bones.length; index++) {
  21688. this._animatables.push(this.bones[index]);
  21689. }
  21690. }
  21691. return this._animatables;
  21692. };
  21693. Skeleton.prototype.clone = function (name, id) {
  21694. var result = new Skeleton(name, id || name, this._scene);
  21695. for (var index = 0; index < this.bones.length; index++) {
  21696. var source = this.bones[index];
  21697. var parentBone = null;
  21698. if (source.getParent()) {
  21699. var parentIndex = this.bones.indexOf(source.getParent());
  21700. parentBone = result.bones[parentIndex];
  21701. }
  21702. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21703. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21704. }
  21705. return result;
  21706. };
  21707. return Skeleton;
  21708. })();
  21709. BABYLON.Skeleton = Skeleton;
  21710. })(BABYLON || (BABYLON = {}));
  21711. //# sourceMappingURL=babylon.skeleton.js.map
  21712. var BABYLON;
  21713. (function (BABYLON) {
  21714. var PostProcess = (function () {
  21715. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21717. this.name = name;
  21718. this.width = -1;
  21719. this.height = -1;
  21720. this._reusable = false;
  21721. this._textures = new BABYLON.SmartArray(2);
  21722. this._currentRenderTextureInd = 0;
  21723. if (camera != null) {
  21724. this._camera = camera;
  21725. this._scene = camera.getScene();
  21726. camera.attachPostProcess(this);
  21727. this._engine = this._scene.getEngine();
  21728. }
  21729. else {
  21730. this._engine = engine;
  21731. }
  21732. this._renderRatio = ratio;
  21733. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21734. this._reusable = reusable || false;
  21735. samplers = samplers || [];
  21736. samplers.push("textureSampler");
  21737. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21738. }
  21739. PostProcess.prototype.isReusable = function () {
  21740. return this._reusable;
  21741. };
  21742. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21743. camera = camera || this._camera;
  21744. var scene = camera.getScene();
  21745. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21746. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21747. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21748. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21749. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21750. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21751. if (this._textures.length > 0) {
  21752. for (var i = 0; i < this._textures.length; i++) {
  21753. this._engine._releaseTexture(this._textures.data[i]);
  21754. }
  21755. this._textures.reset();
  21756. }
  21757. this.width = desiredWidth;
  21758. this.height = desiredHeight;
  21759. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  21760. if (this._reusable) {
  21761. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  21762. }
  21763. if (this.onSizeChanged) {
  21764. this.onSizeChanged();
  21765. }
  21766. }
  21767. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21768. if (this.onActivate) {
  21769. this.onActivate(camera);
  21770. }
  21771. // Clear
  21772. if (this.clearColor) {
  21773. this._engine.clear(this.clearColor, true, true);
  21774. }
  21775. else {
  21776. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21777. }
  21778. if (this._reusable) {
  21779. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21780. }
  21781. };
  21782. PostProcess.prototype.apply = function () {
  21783. // Check
  21784. if (!this._effect.isReady())
  21785. return null;
  21786. // States
  21787. this._engine.enableEffect(this._effect);
  21788. this._engine.setState(false);
  21789. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21790. this._engine.setDepthBuffer(false);
  21791. this._engine.setDepthWrite(false);
  21792. // Texture
  21793. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21794. // Parameters
  21795. if (this.onApply) {
  21796. this.onApply(this._effect);
  21797. }
  21798. return this._effect;
  21799. };
  21800. PostProcess.prototype.dispose = function (camera) {
  21801. camera = camera || this._camera;
  21802. if (this._textures.length > 0) {
  21803. for (var i = 0; i < this._textures.length; i++) {
  21804. this._engine._releaseTexture(this._textures.data[i]);
  21805. }
  21806. this._textures.reset();
  21807. }
  21808. if (!camera) {
  21809. return;
  21810. }
  21811. camera.detachPostProcess(this);
  21812. var index = camera._postProcesses.indexOf(this);
  21813. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21814. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21815. }
  21816. };
  21817. return PostProcess;
  21818. })();
  21819. BABYLON.PostProcess = PostProcess;
  21820. })(BABYLON || (BABYLON = {}));
  21821. //# sourceMappingURL=babylon.postProcess.js.map
  21822. var BABYLON;
  21823. (function (BABYLON) {
  21824. var PostProcessManager = (function () {
  21825. function PostProcessManager(scene) {
  21826. this._vertexDeclaration = [2];
  21827. this._vertexStrideSize = 2 * 4;
  21828. this._scene = scene;
  21829. }
  21830. PostProcessManager.prototype._prepareBuffers = function () {
  21831. if (this._vertexBuffer) {
  21832. return;
  21833. }
  21834. // VBO
  21835. var vertices = [];
  21836. vertices.push(1, 1);
  21837. vertices.push(-1, 1);
  21838. vertices.push(-1, -1);
  21839. vertices.push(1, -1);
  21840. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21841. // Indices
  21842. var indices = [];
  21843. indices.push(0);
  21844. indices.push(1);
  21845. indices.push(2);
  21846. indices.push(0);
  21847. indices.push(2);
  21848. indices.push(3);
  21849. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21850. };
  21851. // Methods
  21852. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21853. var postProcesses = this._scene.activeCamera._postProcesses;
  21854. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21855. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21856. return false;
  21857. }
  21858. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21859. return true;
  21860. };
  21861. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21862. var engine = this._scene.getEngine();
  21863. for (var index = 0; index < postProcesses.length; index++) {
  21864. if (index < postProcesses.length - 1) {
  21865. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21866. }
  21867. else {
  21868. if (targetTexture) {
  21869. engine.bindFramebuffer(targetTexture);
  21870. }
  21871. else {
  21872. engine.restoreDefaultFramebuffer();
  21873. }
  21874. }
  21875. var pp = postProcesses[index];
  21876. var effect = pp.apply();
  21877. if (effect) {
  21878. if (pp.onBeforeRender) {
  21879. pp.onBeforeRender(effect);
  21880. }
  21881. // VBOs
  21882. this._prepareBuffers();
  21883. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21884. // Draw order
  21885. engine.draw(true, 0, 6);
  21886. }
  21887. }
  21888. // Restore depth buffer
  21889. engine.setDepthBuffer(true);
  21890. engine.setDepthWrite(true);
  21891. };
  21892. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21893. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21894. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21895. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21896. return;
  21897. }
  21898. var engine = this._scene.getEngine();
  21899. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  21900. if (index < postProcessesTakenIndices.length - 1) {
  21901. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  21902. }
  21903. else {
  21904. if (targetTexture) {
  21905. engine.bindFramebuffer(targetTexture);
  21906. }
  21907. else {
  21908. engine.restoreDefaultFramebuffer();
  21909. }
  21910. }
  21911. if (doNotPresent) {
  21912. break;
  21913. }
  21914. var pp = postProcesses[postProcessesTakenIndices[index]];
  21915. var effect = pp.apply();
  21916. if (effect) {
  21917. if (pp.onBeforeRender) {
  21918. pp.onBeforeRender(effect);
  21919. }
  21920. // VBOs
  21921. this._prepareBuffers();
  21922. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21923. // Draw order
  21924. engine.draw(true, 0, 6);
  21925. }
  21926. }
  21927. // Restore depth buffer
  21928. engine.setDepthBuffer(true);
  21929. engine.setDepthWrite(true);
  21930. };
  21931. PostProcessManager.prototype.dispose = function () {
  21932. if (this._vertexBuffer) {
  21933. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21934. this._vertexBuffer = null;
  21935. }
  21936. if (this._indexBuffer) {
  21937. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21938. this._indexBuffer = null;
  21939. }
  21940. };
  21941. return PostProcessManager;
  21942. })();
  21943. BABYLON.PostProcessManager = PostProcessManager;
  21944. })(BABYLON || (BABYLON = {}));
  21945. //# sourceMappingURL=babylon.postProcessManager.js.map
  21946. var BABYLON;
  21947. (function (BABYLON) {
  21948. var PassPostProcess = (function (_super) {
  21949. __extends(PassPostProcess, _super);
  21950. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21951. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  21952. }
  21953. return PassPostProcess;
  21954. })(BABYLON.PostProcess);
  21955. BABYLON.PassPostProcess = PassPostProcess;
  21956. })(BABYLON || (BABYLON = {}));
  21957. //# sourceMappingURL=babylon.passPostProcess.js.map
  21958. var BABYLON;
  21959. (function (BABYLON) {
  21960. var BlurPostProcess = (function (_super) {
  21961. __extends(BlurPostProcess, _super);
  21962. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  21963. var _this = this;
  21964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  21965. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  21966. this.direction = direction;
  21967. this.blurWidth = blurWidth;
  21968. this.onApply = function (effect) {
  21969. effect.setFloat2("screenSize", _this.width, _this.height);
  21970. effect.setVector2("direction", _this.direction);
  21971. effect.setFloat("blurWidth", _this.blurWidth);
  21972. };
  21973. }
  21974. return BlurPostProcess;
  21975. })(BABYLON.PostProcess);
  21976. BABYLON.BlurPostProcess = BlurPostProcess;
  21977. })(BABYLON || (BABYLON = {}));
  21978. //# sourceMappingURL=babylon.blurPostProcess.js.map
  21979. var BABYLON;
  21980. (function (BABYLON) {
  21981. var RefractionPostProcess = (function (_super) {
  21982. __extends(RefractionPostProcess, _super);
  21983. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  21984. var _this = this;
  21985. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  21986. this.color = color;
  21987. this.depth = depth;
  21988. this.colorLevel = colorLevel;
  21989. this.onActivate = function (cam) {
  21990. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  21991. };
  21992. this.onApply = function (effect) {
  21993. effect.setColor3("baseColor", _this.color);
  21994. effect.setFloat("depth", _this.depth);
  21995. effect.setFloat("colorLevel", _this.colorLevel);
  21996. effect.setTexture("refractionSampler", _this._refRexture);
  21997. };
  21998. }
  21999. // Methods
  22000. RefractionPostProcess.prototype.dispose = function (camera) {
  22001. if (this._refRexture) {
  22002. this._refRexture.dispose();
  22003. }
  22004. _super.prototype.dispose.call(this, camera);
  22005. };
  22006. return RefractionPostProcess;
  22007. })(BABYLON.PostProcess);
  22008. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22009. })(BABYLON || (BABYLON = {}));
  22010. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22011. var BABYLON;
  22012. (function (BABYLON) {
  22013. var BlackAndWhitePostProcess = (function (_super) {
  22014. __extends(BlackAndWhitePostProcess, _super);
  22015. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22016. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22017. }
  22018. return BlackAndWhitePostProcess;
  22019. })(BABYLON.PostProcess);
  22020. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22021. })(BABYLON || (BABYLON = {}));
  22022. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22023. var BABYLON;
  22024. (function (BABYLON) {
  22025. var ConvolutionPostProcess = (function (_super) {
  22026. __extends(ConvolutionPostProcess, _super);
  22027. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22028. var _this = this;
  22029. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22030. this.kernel = kernel;
  22031. this.onApply = function (effect) {
  22032. effect.setFloat2("screenSize", _this.width, _this.height);
  22033. effect.setArray("kernel", _this.kernel);
  22034. };
  22035. }
  22036. // Statics
  22037. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22038. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22039. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22040. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22041. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22042. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22043. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22044. return ConvolutionPostProcess;
  22045. })(BABYLON.PostProcess);
  22046. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22047. })(BABYLON || (BABYLON = {}));
  22048. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22049. var BABYLON;
  22050. (function (BABYLON) {
  22051. var FilterPostProcess = (function (_super) {
  22052. __extends(FilterPostProcess, _super);
  22053. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22054. var _this = this;
  22055. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22056. this.kernelMatrix = kernelMatrix;
  22057. this.onApply = function (effect) {
  22058. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22059. };
  22060. }
  22061. return FilterPostProcess;
  22062. })(BABYLON.PostProcess);
  22063. BABYLON.FilterPostProcess = FilterPostProcess;
  22064. })(BABYLON || (BABYLON = {}));
  22065. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22066. var BABYLON;
  22067. (function (BABYLON) {
  22068. var FxaaPostProcess = (function (_super) {
  22069. __extends(FxaaPostProcess, _super);
  22070. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22071. var _this = this;
  22072. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22073. this.onSizeChanged = function () {
  22074. _this.texelWidth = 1.0 / _this.width;
  22075. _this.texelHeight = 1.0 / _this.height;
  22076. };
  22077. this.onApply = function (effect) {
  22078. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22079. };
  22080. }
  22081. return FxaaPostProcess;
  22082. })(BABYLON.PostProcess);
  22083. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22084. })(BABYLON || (BABYLON = {}));
  22085. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22086. var BABYLON;
  22087. (function (BABYLON) {
  22088. var StereoscopicInterlacePostProcess = (function (_super) {
  22089. __extends(StereoscopicInterlacePostProcess, _super);
  22090. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22091. var _this = this;
  22092. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22093. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22094. this.onSizeChanged = function () {
  22095. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22096. };
  22097. this.onApply = function (effect) {
  22098. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22099. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22100. };
  22101. }
  22102. return StereoscopicInterlacePostProcess;
  22103. })(BABYLON.PostProcess);
  22104. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22105. })(BABYLON || (BABYLON = {}));
  22106. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22107. var BABYLON;
  22108. (function (BABYLON) {
  22109. var LensFlare = (function () {
  22110. function LensFlare(size, position, color, imgUrl, system) {
  22111. this.size = size;
  22112. this.position = position;
  22113. this.dispose = function () {
  22114. if (this.texture) {
  22115. this.texture.dispose();
  22116. }
  22117. // Remove from scene
  22118. var index = this._system.lensFlares.indexOf(this);
  22119. this._system.lensFlares.splice(index, 1);
  22120. };
  22121. this.color = color || new BABYLON.Color3(1, 1, 1);
  22122. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22123. this._system = system;
  22124. system.lensFlares.push(this);
  22125. }
  22126. return LensFlare;
  22127. })();
  22128. BABYLON.LensFlare = LensFlare;
  22129. })(BABYLON || (BABYLON = {}));
  22130. //# sourceMappingURL=babylon.lensFlare.js.map
  22131. var BABYLON;
  22132. (function (BABYLON) {
  22133. var LensFlareSystem = (function () {
  22134. function LensFlareSystem(name, emitter, scene) {
  22135. this.name = name;
  22136. this.lensFlares = new Array();
  22137. this.borderLimit = 300;
  22138. this._vertexDeclaration = [2];
  22139. this._vertexStrideSize = 2 * 4;
  22140. this._isEnabled = true;
  22141. this._scene = scene;
  22142. this._emitter = emitter;
  22143. scene.lensFlareSystems.push(this);
  22144. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22145. // VBO
  22146. var vertices = [];
  22147. vertices.push(1, 1);
  22148. vertices.push(-1, 1);
  22149. vertices.push(-1, -1);
  22150. vertices.push(1, -1);
  22151. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22152. // Indices
  22153. var indices = [];
  22154. indices.push(0);
  22155. indices.push(1);
  22156. indices.push(2);
  22157. indices.push(0);
  22158. indices.push(2);
  22159. indices.push(3);
  22160. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22161. // Effects
  22162. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22163. }
  22164. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22165. get: function () {
  22166. return this._isEnabled;
  22167. },
  22168. set: function (value) {
  22169. this._isEnabled = value;
  22170. },
  22171. enumerable: true,
  22172. configurable: true
  22173. });
  22174. LensFlareSystem.prototype.getScene = function () {
  22175. return this._scene;
  22176. };
  22177. LensFlareSystem.prototype.getEmitter = function () {
  22178. return this._emitter;
  22179. };
  22180. LensFlareSystem.prototype.getEmitterPosition = function () {
  22181. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22182. };
  22183. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22184. var position = this.getEmitterPosition();
  22185. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22186. this._positionX = position.x;
  22187. this._positionY = position.y;
  22188. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22189. if (position.z > 0) {
  22190. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22191. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22192. return true;
  22193. }
  22194. }
  22195. return false;
  22196. };
  22197. LensFlareSystem.prototype._isVisible = function () {
  22198. if (!this._isEnabled) {
  22199. return false;
  22200. }
  22201. var emitterPosition = this.getEmitterPosition();
  22202. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22203. var distance = direction.length();
  22204. direction.normalize();
  22205. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22206. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22207. return !pickInfo.hit || pickInfo.distance > distance;
  22208. };
  22209. LensFlareSystem.prototype.render = function () {
  22210. if (!this._effect.isReady())
  22211. return false;
  22212. var engine = this._scene.getEngine();
  22213. var viewport = this._scene.activeCamera.viewport;
  22214. var globalViewport = viewport.toGlobal(engine);
  22215. // Position
  22216. if (!this.computeEffectivePosition(globalViewport)) {
  22217. return false;
  22218. }
  22219. // Visibility
  22220. if (!this._isVisible()) {
  22221. return false;
  22222. }
  22223. // Intensity
  22224. var awayX;
  22225. var awayY;
  22226. if (this._positionX < this.borderLimit + globalViewport.x) {
  22227. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22228. }
  22229. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22230. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22231. }
  22232. else {
  22233. awayX = 0;
  22234. }
  22235. if (this._positionY < this.borderLimit + globalViewport.y) {
  22236. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22237. }
  22238. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22239. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22240. }
  22241. else {
  22242. awayY = 0;
  22243. }
  22244. var away = (awayX > awayY) ? awayX : awayY;
  22245. if (away > this.borderLimit) {
  22246. away = this.borderLimit;
  22247. }
  22248. var intensity = 1.0 - (away / this.borderLimit);
  22249. if (intensity < 0) {
  22250. return false;
  22251. }
  22252. if (intensity > 1.0) {
  22253. intensity = 1.0;
  22254. }
  22255. // Position
  22256. var centerX = globalViewport.x + globalViewport.width / 2;
  22257. var centerY = globalViewport.y + globalViewport.height / 2;
  22258. var distX = centerX - this._positionX;
  22259. var distY = centerY - this._positionY;
  22260. // Effects
  22261. engine.enableEffect(this._effect);
  22262. engine.setState(false);
  22263. engine.setDepthBuffer(false);
  22264. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22265. // VBOs
  22266. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22267. // Flares
  22268. for (var index = 0; index < this.lensFlares.length; index++) {
  22269. var flare = this.lensFlares[index];
  22270. var x = centerX - (distX * flare.position);
  22271. var y = centerY - (distY * flare.position);
  22272. var cw = flare.size;
  22273. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22274. var cx = 2 * (x / globalViewport.width) - 1.0;
  22275. var cy = 1.0 - 2 * (y / globalViewport.height);
  22276. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22277. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22278. // Texture
  22279. this._effect.setTexture("textureSampler", flare.texture);
  22280. // Color
  22281. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22282. // Draw order
  22283. engine.draw(true, 0, 6);
  22284. }
  22285. engine.setDepthBuffer(true);
  22286. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22287. return true;
  22288. };
  22289. LensFlareSystem.prototype.dispose = function () {
  22290. if (this._vertexBuffer) {
  22291. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22292. this._vertexBuffer = null;
  22293. }
  22294. if (this._indexBuffer) {
  22295. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22296. this._indexBuffer = null;
  22297. }
  22298. while (this.lensFlares.length) {
  22299. this.lensFlares[0].dispose();
  22300. }
  22301. // Remove from scene
  22302. var index = this._scene.lensFlareSystems.indexOf(this);
  22303. this._scene.lensFlareSystems.splice(index, 1);
  22304. };
  22305. return LensFlareSystem;
  22306. })();
  22307. BABYLON.LensFlareSystem = LensFlareSystem;
  22308. })(BABYLON || (BABYLON = {}));
  22309. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22310. var BABYLON;
  22311. (function (BABYLON) {
  22312. var CannonJSPlugin = (function () {
  22313. function CannonJSPlugin() {
  22314. this._registeredMeshes = [];
  22315. this._physicsMaterials = [];
  22316. this.updateBodyPosition = function (mesh) {
  22317. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22318. var registeredMesh = this._registeredMeshes[index];
  22319. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22320. var body = registeredMesh.body;
  22321. var center = mesh.getBoundingInfo().boundingBox.center;
  22322. body.position.set(center.x, center.z, center.y);
  22323. body.quaternion.x = mesh.rotationQuaternion.x;
  22324. body.quaternion.z = mesh.rotationQuaternion.y;
  22325. body.quaternion.y = mesh.rotationQuaternion.z;
  22326. body.quaternion.w = -mesh.rotationQuaternion.w;
  22327. return;
  22328. }
  22329. }
  22330. };
  22331. }
  22332. CannonJSPlugin.prototype.initialize = function (iterations) {
  22333. if (iterations === void 0) { iterations = 10; }
  22334. this._world = new CANNON.World();
  22335. this._world.broadphase = new CANNON.NaiveBroadphase();
  22336. this._world.solver.iterations = iterations;
  22337. };
  22338. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22339. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22340. };
  22341. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22342. this._world.step(delta);
  22343. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22344. var registeredMesh = this._registeredMeshes[index];
  22345. if (registeredMesh.isChild) {
  22346. continue;
  22347. }
  22348. // Body position
  22349. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22350. var deltaPos = registeredMesh.delta;
  22351. if (deltaPos) {
  22352. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22353. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22354. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22355. }
  22356. else {
  22357. registeredMesh.mesh.position.x = bodyX;
  22358. registeredMesh.mesh.position.y = bodyZ;
  22359. registeredMesh.mesh.position.z = bodyY;
  22360. }
  22361. if (!registeredMesh.mesh.rotationQuaternion) {
  22362. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22363. }
  22364. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22365. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22366. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22367. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22368. }
  22369. };
  22370. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22371. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22372. };
  22373. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22374. this.unregisterMesh(mesh);
  22375. mesh.computeWorldMatrix(true);
  22376. switch (impostor) {
  22377. case BABYLON.PhysicsEngine.SphereImpostor:
  22378. var bbox = mesh.getBoundingInfo().boundingBox;
  22379. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22380. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22381. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22382. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22383. case BABYLON.PhysicsEngine.BoxImpostor:
  22384. bbox = mesh.getBoundingInfo().boundingBox;
  22385. var min = bbox.minimumWorld;
  22386. var max = bbox.maximumWorld;
  22387. var box = max.subtract(min).scale(0.5);
  22388. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22389. case BABYLON.PhysicsEngine.PlaneImpostor:
  22390. return this._createPlane(mesh, options);
  22391. case BABYLON.PhysicsEngine.MeshImpostor:
  22392. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22393. var rawFaces = mesh.getIndices();
  22394. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22395. }
  22396. return null;
  22397. };
  22398. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22399. var shape = new CANNON.Sphere(radius);
  22400. if (!options) {
  22401. return shape;
  22402. }
  22403. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22404. };
  22405. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22406. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22407. if (!options) {
  22408. return shape;
  22409. }
  22410. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22411. };
  22412. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22413. var shape = new CANNON.Plane();
  22414. if (!options) {
  22415. return shape;
  22416. }
  22417. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22418. };
  22419. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22420. var verts = [], faces = [];
  22421. mesh.computeWorldMatrix(true);
  22422. // Get vertices
  22423. for (var i = 0; i < rawVerts.length; i += 3) {
  22424. var transformed = BABYLON.Vector3.Zero();
  22425. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22426. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22427. }
  22428. // Get faces
  22429. for (var j = 0; j < rawFaces.length; j += 3) {
  22430. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22431. }
  22432. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22433. if (!options) {
  22434. return shape;
  22435. }
  22436. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22437. };
  22438. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22439. var index;
  22440. var mat;
  22441. for (index = 0; index < this._physicsMaterials.length; index++) {
  22442. mat = this._physicsMaterials[index];
  22443. if (mat.friction === friction && mat.restitution === restitution) {
  22444. return mat;
  22445. }
  22446. }
  22447. var currentMat = new CANNON.Material();
  22448. currentMat.friction = friction;
  22449. currentMat.restitution = restitution;
  22450. this._physicsMaterials.push(currentMat);
  22451. for (index = 0; index < this._physicsMaterials.length; index++) {
  22452. mat = this._physicsMaterials[index];
  22453. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22454. contactMaterial.contactEquationStiffness = 1e10;
  22455. contactMaterial.contactEquationRegularizationTime = 10;
  22456. this._world.addContactMaterial(contactMaterial);
  22457. }
  22458. return currentMat;
  22459. };
  22460. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22461. var initialRotation = null;
  22462. if (mesh.rotationQuaternion) {
  22463. initialRotation = mesh.rotationQuaternion.clone();
  22464. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22465. }
  22466. // The delta between the mesh position and the mesh bounding box center
  22467. var bbox = mesh.getBoundingInfo().boundingBox;
  22468. var deltaPosition = mesh.position.subtract(bbox.center);
  22469. var material = this._addMaterial(friction, restitution);
  22470. var body = new CANNON.RigidBody(mass, shape, material);
  22471. if (initialRotation) {
  22472. body.quaternion.x = initialRotation.x;
  22473. body.quaternion.z = initialRotation.y;
  22474. body.quaternion.y = initialRotation.z;
  22475. body.quaternion.w = -initialRotation.w;
  22476. }
  22477. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22478. this._world.add(body);
  22479. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22480. return body;
  22481. };
  22482. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22483. var compoundShape = new CANNON.Compound();
  22484. for (var index = 0; index < parts.length; index++) {
  22485. var mesh = parts[index].mesh;
  22486. var shape = this.registerMesh(mesh, parts[index].impostor);
  22487. if (index == 0) {
  22488. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22489. }
  22490. else {
  22491. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22492. }
  22493. }
  22494. var initialMesh = parts[0].mesh;
  22495. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22496. body.parts = parts;
  22497. return body;
  22498. };
  22499. CannonJSPlugin.prototype._unbindBody = function (body) {
  22500. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22501. var registeredMesh = this._registeredMeshes[index];
  22502. if (registeredMesh.body === body) {
  22503. registeredMesh.body = null;
  22504. registeredMesh.delta = 0;
  22505. }
  22506. }
  22507. };
  22508. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22509. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22510. var registeredMesh = this._registeredMeshes[index];
  22511. if (registeredMesh.mesh === mesh) {
  22512. // Remove body
  22513. if (registeredMesh.body) {
  22514. this._world.remove(registeredMesh.body);
  22515. this._unbindBody(registeredMesh.body);
  22516. }
  22517. this._registeredMeshes.splice(index, 1);
  22518. return;
  22519. }
  22520. }
  22521. };
  22522. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22523. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22524. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22525. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22526. var registeredMesh = this._registeredMeshes[index];
  22527. if (registeredMesh.mesh === mesh) {
  22528. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22529. return;
  22530. }
  22531. }
  22532. };
  22533. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22534. var body1 = null, body2 = null;
  22535. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22536. var registeredMesh = this._registeredMeshes[index];
  22537. if (registeredMesh.mesh === mesh1) {
  22538. body1 = registeredMesh.body;
  22539. }
  22540. else if (registeredMesh.mesh === mesh2) {
  22541. body2 = registeredMesh.body;
  22542. }
  22543. }
  22544. if (!body1 || !body2) {
  22545. return false;
  22546. }
  22547. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  22548. this._world.addConstraint(constraint);
  22549. return true;
  22550. };
  22551. CannonJSPlugin.prototype.dispose = function () {
  22552. while (this._registeredMeshes.length) {
  22553. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22554. }
  22555. };
  22556. CannonJSPlugin.prototype.isSupported = function () {
  22557. return window.CANNON !== undefined;
  22558. };
  22559. return CannonJSPlugin;
  22560. })();
  22561. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22562. })(BABYLON || (BABYLON = {}));
  22563. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22564. var BABYLON;
  22565. (function (BABYLON) {
  22566. var OimoJSPlugin = (function () {
  22567. function OimoJSPlugin() {
  22568. this._registeredMeshes = [];
  22569. /**
  22570. * Update the body position according to the mesh position
  22571. * @param mesh
  22572. */
  22573. this.updateBodyPosition = function (mesh) {
  22574. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22575. var registeredMesh = this._registeredMeshes[index];
  22576. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22577. var body = registeredMesh.body.body;
  22578. mesh.computeWorldMatrix(true);
  22579. var center = mesh.getBoundingInfo().boundingBox.center;
  22580. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22581. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22582. body.sleeping = false;
  22583. return;
  22584. }
  22585. // Case where the parent has been updated
  22586. if (registeredMesh.mesh.parent === mesh) {
  22587. mesh.computeWorldMatrix(true);
  22588. registeredMesh.mesh.computeWorldMatrix(true);
  22589. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22590. var absoluteRotation = mesh.rotation;
  22591. body = registeredMesh.body.body;
  22592. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22593. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22594. body.sleeping = false;
  22595. return;
  22596. }
  22597. }
  22598. };
  22599. }
  22600. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22601. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22602. };
  22603. OimoJSPlugin.prototype.initialize = function (iterations) {
  22604. this._world = new OIMO.World();
  22605. this._world.clear();
  22606. };
  22607. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22608. this._world.gravity = gravity;
  22609. };
  22610. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22611. var body = null;
  22612. this.unregisterMesh(mesh);
  22613. mesh.computeWorldMatrix(true);
  22614. var initialRotation = null;
  22615. if (mesh.rotationQuaternion) {
  22616. initialRotation = mesh.rotationQuaternion.clone();
  22617. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22618. mesh.computeWorldMatrix(true);
  22619. }
  22620. var bbox = mesh.getBoundingInfo().boundingBox;
  22621. // The delta between the mesh position and the mesh bounding box center
  22622. var deltaPosition = mesh.position.subtract(bbox.center);
  22623. // Transform delta position with the rotation
  22624. if (initialRotation) {
  22625. var m = new BABYLON.Matrix();
  22626. initialRotation.toRotationMatrix(m);
  22627. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22628. }
  22629. // register mesh
  22630. switch (impostor) {
  22631. case BABYLON.PhysicsEngine.SphereImpostor:
  22632. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22633. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22634. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22635. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22636. body = new OIMO.Body({
  22637. type: 'sphere',
  22638. size: [size],
  22639. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22640. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22641. move: options.mass != 0,
  22642. config: [options.mass, options.friction, options.restitution],
  22643. world: this._world
  22644. });
  22645. break;
  22646. case BABYLON.PhysicsEngine.PlaneImpostor:
  22647. //Oimo "fakes" a cylinder as a box, so why don't we!
  22648. case BABYLON.PhysicsEngine.CylinderImpostor:
  22649. case BABYLON.PhysicsEngine.BoxImpostor:
  22650. var min = bbox.minimumWorld;
  22651. var max = bbox.maximumWorld;
  22652. var box = max.subtract(min);
  22653. var sizeX = this._checkWithEpsilon(box.x);
  22654. var sizeY = this._checkWithEpsilon(box.y);
  22655. var sizeZ = this._checkWithEpsilon(box.z);
  22656. body = new OIMO.Body({
  22657. type: 'box',
  22658. size: [sizeX, sizeY, sizeZ],
  22659. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22660. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22661. move: options.mass != 0,
  22662. config: [options.mass, options.friction, options.restitution],
  22663. world: this._world
  22664. });
  22665. break;
  22666. }
  22667. //If quaternion was set as the rotation of the object
  22668. if (initialRotation) {
  22669. //We have to access the rigid body's properties to set the quaternion.
  22670. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22671. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22672. //update the internal rotation matrix
  22673. body.body.syncShapes();
  22674. }
  22675. this._registeredMeshes.push({
  22676. mesh: mesh,
  22677. body: body,
  22678. delta: deltaPosition
  22679. });
  22680. return body;
  22681. };
  22682. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22683. var types = [], sizes = [], positions = [], rotations = [];
  22684. var initialMesh = parts[0].mesh;
  22685. for (var index = 0; index < parts.length; index++) {
  22686. var part = parts[index];
  22687. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22688. types.push(bodyParameters.type);
  22689. sizes.push.apply(sizes, bodyParameters.size);
  22690. positions.push.apply(positions, bodyParameters.pos);
  22691. rotations.push.apply(rotations, bodyParameters.rot);
  22692. }
  22693. var body = new OIMO.Body({
  22694. type: types,
  22695. size: sizes,
  22696. pos: positions,
  22697. rot: rotations,
  22698. move: options.mass != 0,
  22699. config: [options.mass, options.friction, options.restitution],
  22700. world: this._world
  22701. });
  22702. this._registeredMeshes.push({
  22703. mesh: initialMesh,
  22704. body: body
  22705. });
  22706. return body;
  22707. };
  22708. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22709. var bodyParameters = null;
  22710. var mesh = part.mesh;
  22711. // We need the bounding box/sphere info to compute the physics body
  22712. mesh.computeWorldMatrix();
  22713. switch (part.impostor) {
  22714. case BABYLON.PhysicsEngine.SphereImpostor:
  22715. var bbox = mesh.getBoundingInfo().boundingBox;
  22716. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22717. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22718. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22719. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22720. bodyParameters = {
  22721. type: 'sphere',
  22722. /* bug with oimo : sphere needs 3 sizes in this case */
  22723. size: [size, -1, -1],
  22724. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22725. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22726. };
  22727. break;
  22728. case BABYLON.PhysicsEngine.PlaneImpostor:
  22729. case BABYLON.PhysicsEngine.BoxImpostor:
  22730. bbox = mesh.getBoundingInfo().boundingBox;
  22731. var min = bbox.minimumWorld;
  22732. var max = bbox.maximumWorld;
  22733. var box = max.subtract(min);
  22734. var sizeX = this._checkWithEpsilon(box.x);
  22735. var sizeY = this._checkWithEpsilon(box.y);
  22736. var sizeZ = this._checkWithEpsilon(box.z);
  22737. var relativePosition = mesh.position;
  22738. bodyParameters = {
  22739. type: 'box',
  22740. size: [sizeX, sizeY, sizeZ],
  22741. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22742. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22743. };
  22744. break;
  22745. }
  22746. return bodyParameters;
  22747. };
  22748. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22749. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22750. var registeredMesh = this._registeredMeshes[index];
  22751. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22752. if (registeredMesh.body) {
  22753. this._world.removeRigidBody(registeredMesh.body.body);
  22754. this._unbindBody(registeredMesh.body);
  22755. }
  22756. this._registeredMeshes.splice(index, 1);
  22757. return;
  22758. }
  22759. }
  22760. };
  22761. OimoJSPlugin.prototype._unbindBody = function (body) {
  22762. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22763. var registeredMesh = this._registeredMeshes[index];
  22764. if (registeredMesh.body === body) {
  22765. registeredMesh.body = null;
  22766. }
  22767. }
  22768. };
  22769. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22770. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22771. var registeredMesh = this._registeredMeshes[index];
  22772. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22773. // Get object mass to have a behaviour similar to cannon.js
  22774. var mass = registeredMesh.body.body.massInfo.mass;
  22775. // The force is scaled with the mass of object
  22776. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22777. return;
  22778. }
  22779. }
  22780. };
  22781. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22782. var body1 = null, body2 = null;
  22783. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22784. var registeredMesh = this._registeredMeshes[index];
  22785. if (registeredMesh.mesh === mesh1) {
  22786. body1 = registeredMesh.body.body;
  22787. }
  22788. else if (registeredMesh.mesh === mesh2) {
  22789. body2 = registeredMesh.body.body;
  22790. }
  22791. }
  22792. if (!body1 || !body2) {
  22793. return false;
  22794. }
  22795. if (!options) {
  22796. options = {};
  22797. }
  22798. new OIMO.Link({
  22799. type: options.type,
  22800. body1: body1,
  22801. body2: body2,
  22802. min: options.min,
  22803. max: options.max,
  22804. axe1: options.axe1,
  22805. axe2: options.axe2,
  22806. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22807. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22808. collision: options.collision,
  22809. spring: options.spring,
  22810. world: this._world
  22811. });
  22812. return true;
  22813. };
  22814. OimoJSPlugin.prototype.dispose = function () {
  22815. this._world.clear();
  22816. while (this._registeredMeshes.length) {
  22817. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22818. }
  22819. };
  22820. OimoJSPlugin.prototype.isSupported = function () {
  22821. return OIMO !== undefined;
  22822. };
  22823. OimoJSPlugin.prototype._getLastShape = function (body) {
  22824. var lastShape = body.shapes;
  22825. while (lastShape.next) {
  22826. lastShape = lastShape.next;
  22827. }
  22828. return lastShape;
  22829. };
  22830. OimoJSPlugin.prototype.runOneStep = function (time) {
  22831. this._world.step();
  22832. // Update the position of all registered meshes
  22833. var i = this._registeredMeshes.length;
  22834. var m;
  22835. while (i--) {
  22836. var body = this._registeredMeshes[i].body.body;
  22837. var mesh = this._registeredMeshes[i].mesh;
  22838. var delta = this._registeredMeshes[i].delta;
  22839. if (!body.sleeping) {
  22840. if (body.shapes.next) {
  22841. var parentShape = this._getLastShape(body);
  22842. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22843. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22844. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22845. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22846. if (!mesh.rotationQuaternion) {
  22847. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22848. }
  22849. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22850. mesh.computeWorldMatrix();
  22851. }
  22852. else {
  22853. m = body.getMatrix();
  22854. mtx = BABYLON.Matrix.FromArray(m);
  22855. // Body position
  22856. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22857. if (!delta) {
  22858. mesh.position.x = bodyX;
  22859. mesh.position.y = bodyY;
  22860. mesh.position.z = bodyZ;
  22861. }
  22862. else {
  22863. mesh.position.x = bodyX + delta.x;
  22864. mesh.position.y = bodyY + delta.y;
  22865. mesh.position.z = bodyZ + delta.z;
  22866. }
  22867. if (!mesh.rotationQuaternion) {
  22868. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22869. }
  22870. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22871. mesh.computeWorldMatrix();
  22872. }
  22873. }
  22874. }
  22875. };
  22876. return OimoJSPlugin;
  22877. })();
  22878. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22879. })(BABYLON || (BABYLON = {}));
  22880. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22881. var BABYLON;
  22882. (function (BABYLON) {
  22883. var PhysicsEngine = (function () {
  22884. function PhysicsEngine(plugin) {
  22885. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22886. }
  22887. PhysicsEngine.prototype._initialize = function (gravity) {
  22888. this._currentPlugin.initialize();
  22889. this._setGravity(gravity);
  22890. };
  22891. PhysicsEngine.prototype._runOneStep = function (delta) {
  22892. if (delta > 0.1) {
  22893. delta = 0.1;
  22894. }
  22895. else if (delta <= 0) {
  22896. delta = 1.0 / 60.0;
  22897. }
  22898. this._currentPlugin.runOneStep(delta);
  22899. };
  22900. PhysicsEngine.prototype._setGravity = function (gravity) {
  22901. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  22902. this._currentPlugin.setGravity(this.gravity);
  22903. };
  22904. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22905. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22906. };
  22907. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22908. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22909. };
  22910. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22911. this._currentPlugin.unregisterMesh(mesh);
  22912. };
  22913. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22914. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22915. };
  22916. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22917. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22918. };
  22919. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22920. this._currentPlugin.updateBodyPosition(mesh);
  22921. };
  22922. PhysicsEngine.prototype.dispose = function () {
  22923. this._currentPlugin.dispose();
  22924. };
  22925. PhysicsEngine.prototype.isSupported = function () {
  22926. return this._currentPlugin.isSupported();
  22927. };
  22928. // Statics
  22929. PhysicsEngine.NoImpostor = 0;
  22930. PhysicsEngine.SphereImpostor = 1;
  22931. PhysicsEngine.BoxImpostor = 2;
  22932. PhysicsEngine.PlaneImpostor = 3;
  22933. PhysicsEngine.MeshImpostor = 4;
  22934. PhysicsEngine.CapsuleImpostor = 5;
  22935. PhysicsEngine.ConeImpostor = 6;
  22936. PhysicsEngine.CylinderImpostor = 7;
  22937. PhysicsEngine.ConvexHullImpostor = 8;
  22938. PhysicsEngine.Epsilon = 0.001;
  22939. return PhysicsEngine;
  22940. })();
  22941. BABYLON.PhysicsEngine = PhysicsEngine;
  22942. })(BABYLON || (BABYLON = {}));
  22943. //# sourceMappingURL=babylon.physicsEngine.js.map
  22944. var BABYLON;
  22945. (function (BABYLON) {
  22946. var serializeLight = function (light) {
  22947. var serializationObject = {};
  22948. serializationObject.name = light.name;
  22949. serializationObject.id = light.id;
  22950. serializationObject.tags = BABYLON.Tags.GetTags(light);
  22951. if (light instanceof BABYLON.PointLight) {
  22952. serializationObject.type = 0;
  22953. serializationObject.position = light.position.asArray();
  22954. }
  22955. else if (light instanceof BABYLON.DirectionalLight) {
  22956. serializationObject.type = 1;
  22957. var directionalLight = light;
  22958. serializationObject.position = directionalLight.position.asArray();
  22959. serializationObject.direction = directionalLight.direction.asArray();
  22960. }
  22961. else if (light instanceof BABYLON.SpotLight) {
  22962. serializationObject.type = 2;
  22963. var spotLight = light;
  22964. serializationObject.position = spotLight.position.asArray();
  22965. serializationObject.direction = spotLight.position.asArray();
  22966. serializationObject.angle = spotLight.angle;
  22967. serializationObject.exponent = spotLight.exponent;
  22968. }
  22969. else if (light instanceof BABYLON.HemisphericLight) {
  22970. serializationObject.type = 3;
  22971. var hemisphericLight = light;
  22972. serializationObject.direction = hemisphericLight.direction.asArray();
  22973. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  22974. }
  22975. if (light.intensity) {
  22976. serializationObject.intensity = light.intensity;
  22977. }
  22978. serializationObject.range = light.range;
  22979. serializationObject.diffuse = light.diffuse.asArray();
  22980. serializationObject.specular = light.specular.asArray();
  22981. return serializationObject;
  22982. };
  22983. var serializeFresnelParameter = function (fresnelParameter) {
  22984. var serializationObject = {};
  22985. serializationObject.isEnabled = fresnelParameter.isEnabled;
  22986. serializationObject.leftColor = fresnelParameter.leftColor;
  22987. serializationObject.rightColor = fresnelParameter.rightColor;
  22988. serializationObject.bias = fresnelParameter.bias;
  22989. serializationObject.power = fresnelParameter.power;
  22990. return serializationObject;
  22991. };
  22992. var appendAnimations = function (source, destination) {
  22993. if (source.animations) {
  22994. destination.animations = [];
  22995. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22996. var animation = source.animations[animationIndex];
  22997. destination.animations.push(serializeAnimation(animation));
  22998. }
  22999. }
  23000. };
  23001. var serializeCamera = function (camera) {
  23002. var serializationObject = {};
  23003. serializationObject.name = camera.name;
  23004. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23005. serializationObject.id = camera.id;
  23006. serializationObject.position = camera.position.asArray();
  23007. // Parent
  23008. if (camera.parent) {
  23009. serializationObject.parentId = camera.parent.id;
  23010. }
  23011. serializationObject.fov = camera.fov;
  23012. serializationObject.minZ = camera.minZ;
  23013. serializationObject.maxZ = camera.maxZ;
  23014. serializationObject.inertia = camera.inertia;
  23015. //setting the type
  23016. if (camera instanceof BABYLON.FreeCamera) {
  23017. serializationObject.type = "FreeCamera";
  23018. }
  23019. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23020. serializationObject.type = "ArcRotateCamera";
  23021. }
  23022. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23023. serializationObject.type = "AnaglyphArcRotateCamera";
  23024. }
  23025. else if (camera instanceof BABYLON.GamepadCamera) {
  23026. serializationObject.type = "GamepadCamera";
  23027. }
  23028. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23029. serializationObject.type = "AnaglyphFreeCamera";
  23030. }
  23031. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23032. serializationObject.type = "DeviceOrientationCamera";
  23033. }
  23034. else if (camera instanceof BABYLON.FollowCamera) {
  23035. serializationObject.type = "FollowCamera";
  23036. }
  23037. else if (camera instanceof BABYLON.TouchCamera) {
  23038. serializationObject.type = "TouchCamera";
  23039. }
  23040. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23041. serializationObject.type = "VirtualJoysticksCamera";
  23042. }
  23043. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23044. serializationObject.type = "WebVRFreeCamera";
  23045. }
  23046. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23047. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23048. }
  23049. //special properties of specific cameras
  23050. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23051. var arcCamera = camera;
  23052. serializationObject.alpha = arcCamera.alpha;
  23053. serializationObject.beta = arcCamera.beta;
  23054. serializationObject.radius = arcCamera.radius;
  23055. if (arcCamera.target && arcCamera.target.id) {
  23056. serializationObject.lockedTargetId = arcCamera.target.id;
  23057. }
  23058. }
  23059. else if (camera instanceof BABYLON.FollowCamera) {
  23060. var followCam = camera;
  23061. serializationObject.radius = followCam.radius;
  23062. serializationObject.heightOffset = followCam.heightOffset;
  23063. serializationObject.rotationOffset = followCam.rotationOffset;
  23064. }
  23065. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23066. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  23067. if (camera['_eyeSpace'] !== undefined) {
  23068. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23069. }
  23070. }
  23071. //general properties that not all cameras have. The [] is due to typescript's type safety
  23072. if (camera['speed'] !== undefined) {
  23073. serializationObject.speed = camera['speed'];
  23074. }
  23075. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23076. serializationObject.target = camera['target'].asArray();
  23077. }
  23078. // Target
  23079. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23080. serializationObject.rotation = camera['rotation'].asArray();
  23081. }
  23082. // Locked target
  23083. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23084. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23085. }
  23086. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23087. serializationObject.applyGravity = camera['applyGravity'] || false;
  23088. if (camera['ellipsoid']) {
  23089. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23090. }
  23091. // Animations
  23092. appendAnimations(camera, serializationObject);
  23093. // Layer mask
  23094. serializationObject.layerMask = camera.layerMask;
  23095. return serializationObject;
  23096. };
  23097. var serializeAnimation = function (animation) {
  23098. var serializationObject = {};
  23099. serializationObject.name = animation.name;
  23100. serializationObject.property = animation.targetProperty;
  23101. serializationObject.framePerSecond = animation.framePerSecond;
  23102. serializationObject.dataType = animation.dataType;
  23103. serializationObject.loopBehavior = animation.loopMode;
  23104. var dataType = animation.dataType;
  23105. serializationObject.keys = [];
  23106. var keys = animation.getKeys();
  23107. for (var index = 0; index < keys.length; index++) {
  23108. var animationKey = keys[index];
  23109. var key = {};
  23110. key.frame = animationKey.frame;
  23111. switch (dataType) {
  23112. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23113. key.values = [animationKey.value];
  23114. break;
  23115. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23116. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23117. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23118. key.values = animationKey.value.asArray();
  23119. break;
  23120. }
  23121. serializationObject.keys.push(key);
  23122. }
  23123. return serializationObject;
  23124. };
  23125. var serializeMultiMaterial = function (material) {
  23126. var serializationObject = {};
  23127. serializationObject.name = material.name;
  23128. serializationObject.id = material.id;
  23129. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23130. serializationObject.materials = [];
  23131. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23132. var subMat = material.subMaterials[matIndex];
  23133. if (subMat) {
  23134. serializationObject.materials.push(subMat.id);
  23135. }
  23136. else {
  23137. serializationObject.materials.push(null);
  23138. }
  23139. }
  23140. return serializationObject;
  23141. };
  23142. var serializeMaterial = function (material) {
  23143. var serializationObject = {};
  23144. serializationObject.name = material.name;
  23145. serializationObject.ambient = material.ambientColor.asArray();
  23146. serializationObject.diffuse = material.diffuseColor.asArray();
  23147. serializationObject.specular = material.specularColor.asArray();
  23148. serializationObject.specularPower = material.specularPower;
  23149. serializationObject.emissive = material.emissiveColor.asArray();
  23150. serializationObject.alpha = material.alpha;
  23151. serializationObject.id = material.id;
  23152. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23153. serializationObject.backFaceCulling = material.backFaceCulling;
  23154. if (material.diffuseTexture) {
  23155. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23156. }
  23157. if (material.diffuseFresnelParameters) {
  23158. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23159. }
  23160. if (material.ambientTexture) {
  23161. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23162. }
  23163. if (material.opacityTexture) {
  23164. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23165. }
  23166. if (material.opacityFresnelParameters) {
  23167. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23168. }
  23169. if (material.reflectionTexture) {
  23170. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23171. }
  23172. if (material.reflectionFresnelParameters) {
  23173. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23174. }
  23175. if (material.emissiveTexture) {
  23176. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23177. }
  23178. if (material.emissiveFresnelParameters) {
  23179. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23180. }
  23181. if (material.specularTexture) {
  23182. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23183. }
  23184. if (material.bumpTexture) {
  23185. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23186. }
  23187. return serializationObject;
  23188. };
  23189. var serializeTexture = function (texture) {
  23190. var serializationObject = {};
  23191. if (!texture.name) {
  23192. return null;
  23193. }
  23194. if (texture instanceof BABYLON.CubeTexture) {
  23195. serializationObject.name = texture.name;
  23196. serializationObject.hasAlpha = texture.hasAlpha;
  23197. serializationObject.level = texture.level;
  23198. serializationObject.coordinatesMode = texture.coordinatesMode;
  23199. return serializationObject;
  23200. }
  23201. if (texture instanceof BABYLON.MirrorTexture) {
  23202. var mirrorTexture = texture;
  23203. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23204. serializationObject.renderList = [];
  23205. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23206. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23207. }
  23208. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23209. }
  23210. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23211. var renderTargetTexture = texture;
  23212. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23213. serializationObject.renderList = [];
  23214. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23215. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23216. }
  23217. }
  23218. var regularTexture = texture;
  23219. serializationObject.name = texture.name;
  23220. serializationObject.hasAlpha = texture.hasAlpha;
  23221. serializationObject.level = texture.level;
  23222. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23223. serializationObject.coordinatesMode = texture.coordinatesMode;
  23224. serializationObject.uOffset = regularTexture.uOffset;
  23225. serializationObject.vOffset = regularTexture.vOffset;
  23226. serializationObject.uScale = regularTexture.uScale;
  23227. serializationObject.vScale = regularTexture.vScale;
  23228. serializationObject.uAng = regularTexture.uAng;
  23229. serializationObject.vAng = regularTexture.vAng;
  23230. serializationObject.wAng = regularTexture.wAng;
  23231. serializationObject.wrapU = texture.wrapU;
  23232. serializationObject.wrapV = texture.wrapV;
  23233. // Animations
  23234. appendAnimations(texture, serializationObject);
  23235. return serializationObject;
  23236. };
  23237. var serializeSkeleton = function (skeleton) {
  23238. var serializationObject = {};
  23239. serializationObject.name = skeleton.name;
  23240. serializationObject.id = skeleton.id;
  23241. serializationObject.bones = [];
  23242. for (var index = 0; index < skeleton.bones.length; index++) {
  23243. var bone = skeleton.bones[index];
  23244. var serializedBone = {
  23245. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23246. name: bone.name,
  23247. matrix: bone.getLocalMatrix().toArray()
  23248. };
  23249. serializationObject.bones.push(serializedBone);
  23250. if (bone.animations && bone.animations.length > 0) {
  23251. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23252. }
  23253. }
  23254. return serializationObject;
  23255. };
  23256. var serializeParticleSystem = function (particleSystem) {
  23257. var serializationObject = {};
  23258. serializationObject.emitterId = particleSystem.emitter.id;
  23259. serializationObject.capacity = particleSystem.getCapacity();
  23260. if (particleSystem.particleTexture) {
  23261. serializationObject.textureName = particleSystem.particleTexture.name;
  23262. }
  23263. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23264. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23265. serializationObject.minSize = particleSystem.minSize;
  23266. serializationObject.maxSize = particleSystem.maxSize;
  23267. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23268. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23269. serializationObject.emitRate = particleSystem.emitRate;
  23270. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23271. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23272. serializationObject.gravity = particleSystem.gravity.asArray();
  23273. serializationObject.direction1 = particleSystem.direction1.asArray();
  23274. serializationObject.direction2 = particleSystem.direction2.asArray();
  23275. serializationObject.color1 = particleSystem.color1.asArray();
  23276. serializationObject.color2 = particleSystem.color2.asArray();
  23277. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23278. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23279. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23280. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23281. serializationObject.blendMode = particleSystem.blendMode;
  23282. return serializationObject;
  23283. };
  23284. var serializeLensFlareSystem = function (lensFlareSystem) {
  23285. var serializationObject = {};
  23286. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23287. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23288. serializationObject.flares = [];
  23289. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23290. var flare = lensFlareSystem.lensFlares[index];
  23291. serializationObject.flares.push({
  23292. size: flare.size,
  23293. position: flare.position,
  23294. color: flare.color.asArray(),
  23295. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23296. });
  23297. }
  23298. return serializationObject;
  23299. };
  23300. var serializeShadowGenerator = function (light) {
  23301. var serializationObject = {};
  23302. var shadowGenerator = light.getShadowGenerator();
  23303. serializationObject.lightId = light.id;
  23304. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23305. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23306. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23307. serializationObject.renderList = [];
  23308. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23309. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23310. serializationObject.renderList.push(mesh.id);
  23311. }
  23312. return serializationObject;
  23313. };
  23314. var serializedGeometries = [];
  23315. var serializeGeometry = function (geometry, serializationGeometries) {
  23316. if (serializedGeometries[geometry.id]) {
  23317. return;
  23318. }
  23319. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23320. serializationGeometries.boxes.push(serializeBox(geometry));
  23321. }
  23322. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23323. serializationGeometries.spheres.push(serializeSphere(geometry));
  23324. }
  23325. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23326. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23327. }
  23328. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23329. serializationGeometries.toruses.push(serializeTorus(geometry));
  23330. }
  23331. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23332. serializationGeometries.grounds.push(serializeGround(geometry));
  23333. }
  23334. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23335. serializationGeometries.planes.push(serializePlane(geometry));
  23336. }
  23337. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23338. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23339. }
  23340. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23341. throw new Error("Unknow primitive type");
  23342. }
  23343. else {
  23344. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23345. }
  23346. serializedGeometries[geometry.id] = true;
  23347. };
  23348. var serializeGeometryBase = function (geometry) {
  23349. var serializationObject = {};
  23350. serializationObject.id = geometry.id;
  23351. if (BABYLON.Tags.HasTags(geometry)) {
  23352. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23353. }
  23354. return serializationObject;
  23355. };
  23356. var serializeVertexData = function (vertexData) {
  23357. var serializationObject = serializeGeometryBase(vertexData);
  23358. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23359. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23360. }
  23361. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23362. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23363. }
  23364. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23365. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23366. }
  23367. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23368. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23369. }
  23370. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23371. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23372. }
  23373. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23374. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23375. serializationObject.matricesIndices._isExpanded = true;
  23376. }
  23377. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23378. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23379. }
  23380. serializationObject.indices = vertexData.getIndices();
  23381. return serializationObject;
  23382. };
  23383. var serializePrimitive = function (primitive) {
  23384. var serializationObject = serializeGeometryBase(primitive);
  23385. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23386. return serializationObject;
  23387. };
  23388. var serializeBox = function (box) {
  23389. var serializationObject = serializePrimitive(box);
  23390. serializationObject.size = box.size;
  23391. return serializationObject;
  23392. };
  23393. var serializeSphere = function (sphere) {
  23394. var serializationObject = serializePrimitive(sphere);
  23395. serializationObject.segments = sphere.segments;
  23396. serializationObject.diameter = sphere.diameter;
  23397. return serializationObject;
  23398. };
  23399. var serializeCylinder = function (cylinder) {
  23400. var serializationObject = serializePrimitive(cylinder);
  23401. serializationObject.height = cylinder.height;
  23402. serializationObject.diameterTop = cylinder.diameterTop;
  23403. serializationObject.diameterBottom = cylinder.diameterBottom;
  23404. serializationObject.tessellation = cylinder.tessellation;
  23405. return serializationObject;
  23406. };
  23407. var serializeTorus = function (torus) {
  23408. var serializationObject = serializePrimitive(torus);
  23409. serializationObject.diameter = torus.diameter;
  23410. serializationObject.thickness = torus.thickness;
  23411. serializationObject.tessellation = torus.tessellation;
  23412. return serializationObject;
  23413. };
  23414. var serializeGround = function (ground) {
  23415. var serializationObject = serializePrimitive(ground);
  23416. serializationObject.width = ground.width;
  23417. serializationObject.height = ground.height;
  23418. serializationObject.subdivisions = ground.subdivisions;
  23419. return serializationObject;
  23420. };
  23421. var serializePlane = function (plane) {
  23422. var serializationObject = serializePrimitive(plane);
  23423. serializationObject.size = plane.size;
  23424. return serializationObject;
  23425. };
  23426. var serializeTorusKnot = function (torusKnot) {
  23427. var serializationObject = serializePrimitive(torusKnot);
  23428. serializationObject.radius = torusKnot.radius;
  23429. serializationObject.tube = torusKnot.tube;
  23430. serializationObject.radialSegments = torusKnot.radialSegments;
  23431. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23432. serializationObject.p = torusKnot.p;
  23433. serializationObject.q = torusKnot.q;
  23434. return serializationObject;
  23435. };
  23436. var serializeMesh = function (mesh, serializationScene) {
  23437. var serializationObject = {};
  23438. serializationObject.name = mesh.name;
  23439. serializationObject.id = mesh.id;
  23440. if (BABYLON.Tags.HasTags(mesh)) {
  23441. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23442. }
  23443. serializationObject.position = mesh.position.asArray();
  23444. if (mesh.rotationQuaternion) {
  23445. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23446. }
  23447. else if (mesh.rotation) {
  23448. serializationObject.rotation = mesh.rotation.asArray();
  23449. }
  23450. serializationObject.scaling = mesh.scaling.asArray();
  23451. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23452. serializationObject.isEnabled = mesh.isEnabled();
  23453. serializationObject.isVisible = mesh.isVisible;
  23454. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23455. serializationObject.pickable = mesh.isPickable;
  23456. serializationObject.receiveShadows = mesh.receiveShadows;
  23457. serializationObject.billboardMode = mesh.billboardMode;
  23458. serializationObject.visibility = mesh.visibility;
  23459. serializationObject.checkCollisions = mesh.checkCollisions;
  23460. // Parent
  23461. if (mesh.parent) {
  23462. serializationObject.parentId = mesh.parent.id;
  23463. }
  23464. // Geometry
  23465. var geometry = mesh._geometry;
  23466. if (geometry) {
  23467. var geometryId = geometry.id;
  23468. serializationObject.geometryId = geometryId;
  23469. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23470. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  23471. serializeGeometry(geometry, serializationScene.geometries);
  23472. }
  23473. // SubMeshes
  23474. serializationObject.subMeshes = [];
  23475. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23476. var subMesh = mesh.subMeshes[subIndex];
  23477. serializationObject.subMeshes.push({
  23478. materialIndex: subMesh.materialIndex,
  23479. verticesStart: subMesh.verticesStart,
  23480. verticesCount: subMesh.verticesCount,
  23481. indexStart: subMesh.indexStart,
  23482. indexCount: subMesh.indexCount
  23483. });
  23484. }
  23485. }
  23486. // Material
  23487. if (mesh.material) {
  23488. serializationObject.materialId = mesh.material.id;
  23489. }
  23490. else {
  23491. mesh.material = null;
  23492. }
  23493. // Skeleton
  23494. if (mesh.skeleton) {
  23495. serializationObject.skeletonId = mesh.skeleton.id;
  23496. }
  23497. // Physics
  23498. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23499. serializationObject.physicsMass = mesh.getPhysicsMass();
  23500. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23501. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23502. switch (mesh.getPhysicsImpostor()) {
  23503. case BABYLON.PhysicsEngine.BoxImpostor:
  23504. serializationObject.physicsImpostor = 1;
  23505. break;
  23506. case BABYLON.PhysicsEngine.SphereImpostor:
  23507. serializationObject.physicsImpostor = 2;
  23508. break;
  23509. }
  23510. }
  23511. // Instances
  23512. serializationObject.instances = [];
  23513. for (var index = 0; index < mesh.instances.length; index++) {
  23514. var instance = mesh.instances[index];
  23515. var serializationInstance = {
  23516. name: instance.name,
  23517. position: instance.position,
  23518. rotation: instance.rotation,
  23519. rotationQuaternion: instance.rotationQuaternion,
  23520. scaling: instance.scaling
  23521. };
  23522. serializationObject.instances.push(serializationInstance);
  23523. // Animations
  23524. appendAnimations(instance, serializationInstance);
  23525. }
  23526. // Animations
  23527. appendAnimations(mesh, serializationObject);
  23528. // Layer mask
  23529. serializationObject.layerMask = mesh.layerMask;
  23530. return serializationObject;
  23531. };
  23532. var SceneSerializer = (function () {
  23533. function SceneSerializer() {
  23534. }
  23535. SceneSerializer.Serialize = function (scene) {
  23536. var serializationObject = {};
  23537. // Scene
  23538. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23539. serializationObject.autoClear = scene.autoClear;
  23540. serializationObject.clearColor = scene.clearColor.asArray();
  23541. serializationObject.ambientColor = scene.ambientColor.asArray();
  23542. serializationObject.gravity = scene.gravity.asArray();
  23543. // Fog
  23544. if (scene.fogMode && scene.fogMode !== 0) {
  23545. serializationObject.fogMode = scene.fogMode;
  23546. serializationObject.fogColor = scene.fogColor.asArray();
  23547. serializationObject.fogStart = scene.fogStart;
  23548. serializationObject.fogEnd = scene.fogEnd;
  23549. serializationObject.fogDensity = scene.fogDensity;
  23550. }
  23551. // Lights
  23552. serializationObject.lights = [];
  23553. for (var index = 0; index < scene.lights.length; index++) {
  23554. var light = scene.lights[index];
  23555. serializationObject.lights.push(serializeLight(light));
  23556. }
  23557. // Cameras
  23558. serializationObject.cameras = [];
  23559. for (index = 0; index < scene.cameras.length; index++) {
  23560. var camera = scene.cameras[index];
  23561. serializationObject.cameras.push(serializeCamera(camera));
  23562. }
  23563. if (scene.activeCamera) {
  23564. serializationObject.activeCameraID = scene.activeCamera.id;
  23565. }
  23566. // Materials
  23567. serializationObject.materials = [];
  23568. serializationObject.multiMaterials = [];
  23569. for (index = 0; index < scene.materials.length; index++) {
  23570. var material = scene.materials[index];
  23571. if (material instanceof BABYLON.StandardMaterial) {
  23572. serializationObject.materials.push(serializeMaterial(material));
  23573. }
  23574. else if (material instanceof BABYLON.MultiMaterial) {
  23575. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23576. }
  23577. }
  23578. // Skeletons
  23579. serializationObject.skeletons = [];
  23580. for (index = 0; index < scene.skeletons.length; index++) {
  23581. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23582. }
  23583. // Geometries
  23584. serializationObject.geometries = {};
  23585. serializationObject.geometries.boxes = [];
  23586. serializationObject.geometries.spheres = [];
  23587. serializationObject.geometries.cylinders = [];
  23588. serializationObject.geometries.toruses = [];
  23589. serializationObject.geometries.grounds = [];
  23590. serializationObject.geometries.planes = [];
  23591. serializationObject.geometries.torusKnots = [];
  23592. serializationObject.geometries.vertexData = [];
  23593. serializedGeometries = [];
  23594. var geometries = scene.getGeometries();
  23595. for (index = 0; index < geometries.length; index++) {
  23596. var geometry = geometries[index];
  23597. if (geometry.isReady()) {
  23598. serializeGeometry(geometry, serializationObject.geometries);
  23599. }
  23600. }
  23601. // Meshes
  23602. serializationObject.meshes = [];
  23603. for (index = 0; index < scene.meshes.length; index++) {
  23604. var abstractMesh = scene.meshes[index];
  23605. if (abstractMesh instanceof BABYLON.Mesh) {
  23606. var mesh = abstractMesh;
  23607. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23608. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23609. }
  23610. }
  23611. }
  23612. // Particles Systems
  23613. serializationObject.particleSystems = [];
  23614. for (index = 0; index < scene.particleSystems.length; index++) {
  23615. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23616. }
  23617. // Lens flares
  23618. serializationObject.lensFlareSystems = [];
  23619. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23620. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23621. }
  23622. // Shadows
  23623. serializationObject.shadowGenerators = [];
  23624. for (index = 0; index < scene.lights.length; index++) {
  23625. light = scene.lights[index];
  23626. if (light.getShadowGenerator()) {
  23627. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23628. }
  23629. }
  23630. return serializationObject;
  23631. };
  23632. return SceneSerializer;
  23633. })();
  23634. BABYLON.SceneSerializer = SceneSerializer;
  23635. })(BABYLON || (BABYLON = {}));
  23636. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23637. var BABYLON;
  23638. (function (BABYLON) {
  23639. // Unique ID when we import meshes from Babylon to CSG
  23640. var currentCSGMeshId = 0;
  23641. // # class Vertex
  23642. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23643. // one to provide additional features like texture coordinates and vertex
  23644. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23645. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23646. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23647. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23648. // is not used anywhere else.
  23649. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23650. var Vertex = (function () {
  23651. function Vertex(pos, normal, uv) {
  23652. this.pos = pos;
  23653. this.normal = normal;
  23654. this.uv = uv;
  23655. }
  23656. Vertex.prototype.clone = function () {
  23657. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23658. };
  23659. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23660. // orientation of a polygon is flipped.
  23661. Vertex.prototype.flip = function () {
  23662. this.normal = this.normal.scale(-1);
  23663. };
  23664. // Create a new vertex between this vertex and `other` by linearly
  23665. // interpolating all properties using a parameter of `t`. Subclasses should
  23666. // override this to interpolate additional properties.
  23667. Vertex.prototype.interpolate = function (other, t) {
  23668. 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));
  23669. };
  23670. return Vertex;
  23671. })();
  23672. // # class Plane
  23673. // Represents a plane in 3D space.
  23674. var Plane = (function () {
  23675. function Plane(normal, w) {
  23676. this.normal = normal;
  23677. this.w = w;
  23678. }
  23679. Plane.FromPoints = function (a, b, c) {
  23680. var v0 = c.subtract(a);
  23681. var v1 = b.subtract(a);
  23682. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23683. return null;
  23684. }
  23685. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23686. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23687. };
  23688. Plane.prototype.clone = function () {
  23689. return new Plane(this.normal.clone(), this.w);
  23690. };
  23691. Plane.prototype.flip = function () {
  23692. this.normal.scaleInPlace(-1);
  23693. this.w = -this.w;
  23694. };
  23695. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23696. // fragments in the appropriate lists. Coplanar polygons go into either
  23697. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23698. // respect to this plane. Polygons in front or in back of this plane go into
  23699. // either `front` or `back`.
  23700. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23701. var COPLANAR = 0;
  23702. var FRONT = 1;
  23703. var BACK = 2;
  23704. var SPANNING = 3;
  23705. // Classify each point as well as the entire polygon into one of the above
  23706. // four classes.
  23707. var polygonType = 0;
  23708. var types = [];
  23709. for (var i = 0; i < polygon.vertices.length; i++) {
  23710. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23711. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23712. polygonType |= type;
  23713. types.push(type);
  23714. }
  23715. // Put the polygon in the correct list, splitting it when necessary.
  23716. switch (polygonType) {
  23717. case COPLANAR:
  23718. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23719. break;
  23720. case FRONT:
  23721. front.push(polygon);
  23722. break;
  23723. case BACK:
  23724. back.push(polygon);
  23725. break;
  23726. case SPANNING:
  23727. var f = [], b = [];
  23728. for (i = 0; i < polygon.vertices.length; i++) {
  23729. var j = (i + 1) % polygon.vertices.length;
  23730. var ti = types[i], tj = types[j];
  23731. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23732. if (ti != BACK)
  23733. f.push(vi);
  23734. if (ti != FRONT)
  23735. b.push(ti != BACK ? vi.clone() : vi);
  23736. if ((ti | tj) == SPANNING) {
  23737. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23738. var v = vi.interpolate(vj, t);
  23739. f.push(v);
  23740. b.push(v.clone());
  23741. }
  23742. }
  23743. if (f.length >= 3) {
  23744. var poly = new Polygon(f, polygon.shared);
  23745. if (poly.plane)
  23746. front.push(poly);
  23747. }
  23748. if (b.length >= 3) {
  23749. poly = new Polygon(b, polygon.shared);
  23750. if (poly.plane)
  23751. back.push(poly);
  23752. }
  23753. break;
  23754. }
  23755. };
  23756. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23757. // point is on the plane.
  23758. Plane.EPSILON = 1e-5;
  23759. return Plane;
  23760. })();
  23761. // # class Polygon
  23762. // Represents a convex polygon. The vertices used to initialize a polygon must
  23763. // be coplanar and form a convex loop.
  23764. //
  23765. // Each convex polygon has a `shared` property, which is shared between all
  23766. // polygons that are clones of each other or were split from the same polygon.
  23767. // This can be used to define per-polygon properties (such as surface color).
  23768. var Polygon = (function () {
  23769. function Polygon(vertices, shared) {
  23770. this.vertices = vertices;
  23771. this.shared = shared;
  23772. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23773. }
  23774. Polygon.prototype.clone = function () {
  23775. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23776. return new Polygon(vertices, this.shared);
  23777. };
  23778. Polygon.prototype.flip = function () {
  23779. this.vertices.reverse().map(function (v) { v.flip(); });
  23780. this.plane.flip();
  23781. };
  23782. return Polygon;
  23783. })();
  23784. // # class Node
  23785. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23786. // by picking a polygon to split along. That polygon (and all other coplanar
  23787. // polygons) are added directly to that node and the other polygons are added to
  23788. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23789. // no distinction between internal and leaf nodes.
  23790. var Node = (function () {
  23791. function Node(polygons) {
  23792. this.plane = null;
  23793. this.front = null;
  23794. this.back = null;
  23795. this.polygons = [];
  23796. if (polygons) {
  23797. this.build(polygons);
  23798. }
  23799. }
  23800. Node.prototype.clone = function () {
  23801. var node = new Node();
  23802. node.plane = this.plane && this.plane.clone();
  23803. node.front = this.front && this.front.clone();
  23804. node.back = this.back && this.back.clone();
  23805. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23806. return node;
  23807. };
  23808. // Convert solid space to empty space and empty space to solid space.
  23809. Node.prototype.invert = function () {
  23810. for (var i = 0; i < this.polygons.length; i++) {
  23811. this.polygons[i].flip();
  23812. }
  23813. if (this.plane) {
  23814. this.plane.flip();
  23815. }
  23816. if (this.front) {
  23817. this.front.invert();
  23818. }
  23819. if (this.back) {
  23820. this.back.invert();
  23821. }
  23822. var temp = this.front;
  23823. this.front = this.back;
  23824. this.back = temp;
  23825. };
  23826. // Recursively remove all polygons in `polygons` that are inside this BSP
  23827. // tree.
  23828. Node.prototype.clipPolygons = function (polygons) {
  23829. if (!this.plane)
  23830. return polygons.slice();
  23831. var front = [], back = [];
  23832. for (var i = 0; i < polygons.length; i++) {
  23833. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23834. }
  23835. if (this.front) {
  23836. front = this.front.clipPolygons(front);
  23837. }
  23838. if (this.back) {
  23839. back = this.back.clipPolygons(back);
  23840. }
  23841. else {
  23842. back = [];
  23843. }
  23844. return front.concat(back);
  23845. };
  23846. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23847. // `bsp`.
  23848. Node.prototype.clipTo = function (bsp) {
  23849. this.polygons = bsp.clipPolygons(this.polygons);
  23850. if (this.front)
  23851. this.front.clipTo(bsp);
  23852. if (this.back)
  23853. this.back.clipTo(bsp);
  23854. };
  23855. // Return a list of all polygons in this BSP tree.
  23856. Node.prototype.allPolygons = function () {
  23857. var polygons = this.polygons.slice();
  23858. if (this.front)
  23859. polygons = polygons.concat(this.front.allPolygons());
  23860. if (this.back)
  23861. polygons = polygons.concat(this.back.allPolygons());
  23862. return polygons;
  23863. };
  23864. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23865. // new polygons are filtered down to the bottom of the tree and become new
  23866. // nodes there. Each set of polygons is partitioned using the first polygon
  23867. // (no heuristic is used to pick a good split).
  23868. Node.prototype.build = function (polygons) {
  23869. if (!polygons.length)
  23870. return;
  23871. if (!this.plane)
  23872. this.plane = polygons[0].plane.clone();
  23873. var front = [], back = [];
  23874. for (var i = 0; i < polygons.length; i++) {
  23875. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23876. }
  23877. if (front.length) {
  23878. if (!this.front)
  23879. this.front = new Node();
  23880. this.front.build(front);
  23881. }
  23882. if (back.length) {
  23883. if (!this.back)
  23884. this.back = new Node();
  23885. this.back.build(back);
  23886. }
  23887. };
  23888. return Node;
  23889. })();
  23890. var CSG = (function () {
  23891. function CSG() {
  23892. this.polygons = new Array();
  23893. }
  23894. // Convert BABYLON.Mesh to BABYLON.CSG
  23895. CSG.FromMesh = function (mesh) {
  23896. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  23897. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  23898. if (mesh instanceof BABYLON.Mesh) {
  23899. mesh.computeWorldMatrix(true);
  23900. matrix = mesh.getWorldMatrix();
  23901. meshPosition = mesh.position.clone();
  23902. meshRotation = mesh.rotation.clone();
  23903. if (mesh.rotationQuaternion) {
  23904. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  23905. }
  23906. meshScaling = mesh.scaling.clone();
  23907. }
  23908. else {
  23909. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  23910. }
  23911. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23912. var subMeshes = mesh.subMeshes;
  23913. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  23914. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  23915. vertices = [];
  23916. for (var j = 0; j < 3; j++) {
  23917. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  23918. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  23919. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  23920. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  23921. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  23922. vertex = new Vertex(position, normal, uv);
  23923. vertices.push(vertex);
  23924. }
  23925. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  23926. // To handle the case of degenerated triangle
  23927. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  23928. if (polygon.plane)
  23929. polygons.push(polygon);
  23930. }
  23931. }
  23932. var csg = CSG.FromPolygons(polygons);
  23933. csg.matrix = matrix;
  23934. csg.position = meshPosition;
  23935. csg.rotation = meshRotation;
  23936. csg.scaling = meshScaling;
  23937. csg.rotationQuaternion = meshRotationQuaternion;
  23938. currentCSGMeshId++;
  23939. return csg;
  23940. };
  23941. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  23942. CSG.FromPolygons = function (polygons) {
  23943. var csg = new BABYLON.CSG();
  23944. csg.polygons = polygons;
  23945. return csg;
  23946. };
  23947. CSG.prototype.clone = function () {
  23948. var csg = new BABYLON.CSG();
  23949. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  23950. csg.copyTransformAttributes(this);
  23951. return csg;
  23952. };
  23953. CSG.prototype.toPolygons = function () {
  23954. return this.polygons;
  23955. };
  23956. CSG.prototype.union = function (csg) {
  23957. var a = new Node(this.clone().polygons);
  23958. var b = new Node(csg.clone().polygons);
  23959. a.clipTo(b);
  23960. b.clipTo(a);
  23961. b.invert();
  23962. b.clipTo(a);
  23963. b.invert();
  23964. a.build(b.allPolygons());
  23965. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23966. };
  23967. CSG.prototype.unionInPlace = function (csg) {
  23968. var a = new Node(this.polygons);
  23969. var b = new Node(csg.polygons);
  23970. a.clipTo(b);
  23971. b.clipTo(a);
  23972. b.invert();
  23973. b.clipTo(a);
  23974. b.invert();
  23975. a.build(b.allPolygons());
  23976. this.polygons = a.allPolygons();
  23977. };
  23978. CSG.prototype.subtract = function (csg) {
  23979. var a = new Node(this.clone().polygons);
  23980. var b = new Node(csg.clone().polygons);
  23981. a.invert();
  23982. a.clipTo(b);
  23983. b.clipTo(a);
  23984. b.invert();
  23985. b.clipTo(a);
  23986. b.invert();
  23987. a.build(b.allPolygons());
  23988. a.invert();
  23989. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23990. };
  23991. CSG.prototype.subtractInPlace = function (csg) {
  23992. var a = new Node(this.polygons);
  23993. var b = new Node(csg.polygons);
  23994. a.invert();
  23995. a.clipTo(b);
  23996. b.clipTo(a);
  23997. b.invert();
  23998. b.clipTo(a);
  23999. b.invert();
  24000. a.build(b.allPolygons());
  24001. a.invert();
  24002. this.polygons = a.allPolygons();
  24003. };
  24004. CSG.prototype.intersect = function (csg) {
  24005. var a = new Node(this.clone().polygons);
  24006. var b = new Node(csg.clone().polygons);
  24007. a.invert();
  24008. b.clipTo(a);
  24009. b.invert();
  24010. a.clipTo(b);
  24011. b.clipTo(a);
  24012. a.build(b.allPolygons());
  24013. a.invert();
  24014. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24015. };
  24016. CSG.prototype.intersectInPlace = function (csg) {
  24017. var a = new Node(this.polygons);
  24018. var b = new Node(csg.polygons);
  24019. a.invert();
  24020. b.clipTo(a);
  24021. b.invert();
  24022. a.clipTo(b);
  24023. b.clipTo(a);
  24024. a.build(b.allPolygons());
  24025. a.invert();
  24026. this.polygons = a.allPolygons();
  24027. };
  24028. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24029. // not modified.
  24030. CSG.prototype.inverse = function () {
  24031. var csg = this.clone();
  24032. csg.inverseInPlace();
  24033. return csg;
  24034. };
  24035. CSG.prototype.inverseInPlace = function () {
  24036. this.polygons.map(function (p) { p.flip(); });
  24037. };
  24038. // This is used to keep meshes transformations so they can be restored
  24039. // when we build back a Babylon Mesh
  24040. // NB : All CSG operations are performed in world coordinates
  24041. CSG.prototype.copyTransformAttributes = function (csg) {
  24042. this.matrix = csg.matrix;
  24043. this.position = csg.position;
  24044. this.rotation = csg.rotation;
  24045. this.scaling = csg.scaling;
  24046. this.rotationQuaternion = csg.rotationQuaternion;
  24047. return this;
  24048. };
  24049. // Build Raw mesh from CSG
  24050. // Coordinates here are in world space
  24051. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24052. var matrix = this.matrix.clone();
  24053. matrix.invert();
  24054. 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;
  24055. if (keepSubMeshes) {
  24056. // Sort Polygons, since subMeshes are indices range
  24057. polygons.sort(function (a, b) {
  24058. if (a.shared.meshId === b.shared.meshId) {
  24059. return a.shared.subMeshId - b.shared.subMeshId;
  24060. }
  24061. else {
  24062. return a.shared.meshId - b.shared.meshId;
  24063. }
  24064. });
  24065. }
  24066. for (var i = 0, il = polygons.length; i < il; i++) {
  24067. polygon = polygons[i];
  24068. // Building SubMeshes
  24069. if (!subMesh_dict[polygon.shared.meshId]) {
  24070. subMesh_dict[polygon.shared.meshId] = {};
  24071. }
  24072. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24073. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24074. indexStart: +Infinity,
  24075. indexEnd: -Infinity,
  24076. materialIndex: polygon.shared.materialIndex
  24077. };
  24078. }
  24079. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24080. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24081. polygonIndices[0] = 0;
  24082. polygonIndices[1] = j - 1;
  24083. polygonIndices[2] = j;
  24084. for (var k = 0; k < 3; k++) {
  24085. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24086. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24087. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24088. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24089. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24090. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24091. // Check if 2 points can be merged
  24092. if (!(typeof vertex_idx !== 'undefined' &&
  24093. normals[vertex_idx * 3] === localNormal.x &&
  24094. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24095. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24096. uvs[vertex_idx * 2] === uv.x &&
  24097. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24098. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24099. uvs.push(uv.x, uv.y);
  24100. normals.push(normal.x, normal.y, normal.z);
  24101. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24102. }
  24103. indices.push(vertex_idx);
  24104. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24105. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24106. currentIndex++;
  24107. }
  24108. }
  24109. }
  24110. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24111. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24112. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24113. mesh.setIndices(indices);
  24114. if (keepSubMeshes) {
  24115. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24116. var materialIndexOffset = 0, materialMaxIndex;
  24117. mesh.subMeshes.length = 0;
  24118. for (var m in subMesh_dict) {
  24119. materialMaxIndex = -1;
  24120. for (var sm in subMesh_dict[m]) {
  24121. subMesh_obj = subMesh_dict[m][sm];
  24122. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24123. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24124. }
  24125. materialIndexOffset += ++materialMaxIndex;
  24126. }
  24127. }
  24128. return mesh;
  24129. };
  24130. // Build Mesh from CSG taking material and transforms into account
  24131. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24132. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24133. mesh.material = material;
  24134. mesh.position.copyFrom(this.position);
  24135. mesh.rotation.copyFrom(this.rotation);
  24136. if (this.rotationQuaternion) {
  24137. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24138. }
  24139. mesh.scaling.copyFrom(this.scaling);
  24140. mesh.computeWorldMatrix(true);
  24141. return mesh;
  24142. };
  24143. return CSG;
  24144. })();
  24145. BABYLON.CSG = CSG;
  24146. })(BABYLON || (BABYLON = {}));
  24147. //# sourceMappingURL=babylon.csg.js.map
  24148. var BABYLON;
  24149. (function (BABYLON) {
  24150. var VRDistortionCorrectionPostProcess = (function (_super) {
  24151. __extends(VRDistortionCorrectionPostProcess, _super);
  24152. //ANY
  24153. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24154. var _this = this;
  24155. _super.call(this, name, "vrDistortionCorrection", [
  24156. 'LensCenter',
  24157. 'Scale',
  24158. 'ScaleIn',
  24159. 'HmdWarpParam'
  24160. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24161. this._isRightEye = isRightEye;
  24162. this._distortionFactors = vrMetrics.distortionK;
  24163. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24164. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24165. this.onSizeChanged = function () {
  24166. _this.aspectRatio = _this.width * .5 / _this.height;
  24167. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24168. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24169. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24170. };
  24171. this.onApply = function (effect) {
  24172. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24173. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24174. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24175. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24176. };
  24177. }
  24178. return VRDistortionCorrectionPostProcess;
  24179. })(BABYLON.PostProcess);
  24180. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24181. })(BABYLON || (BABYLON = {}));
  24182. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24183. // Mainly based on these 2 articles :
  24184. // 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
  24185. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24186. var BABYLON;
  24187. (function (BABYLON) {
  24188. (function (JoystickAxis) {
  24189. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24190. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24191. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24192. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24193. var JoystickAxis = BABYLON.JoystickAxis;
  24194. var VirtualJoystick = (function () {
  24195. function VirtualJoystick(leftJoystick) {
  24196. var _this = this;
  24197. if (leftJoystick) {
  24198. this._leftJoystick = true;
  24199. }
  24200. else {
  24201. this._leftJoystick = false;
  24202. }
  24203. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24204. VirtualJoystick._globalJoystickIndex++;
  24205. // By default left & right arrow keys are moving the X
  24206. // and up & down keys are moving the Y
  24207. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24208. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24209. this.reverseLeftRight = false;
  24210. this.reverseUpDown = false;
  24211. // collections of pointers
  24212. this._touches = new BABYLON.SmartCollection();
  24213. this.deltaPosition = BABYLON.Vector3.Zero();
  24214. this._joystickSensibility = 25;
  24215. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24216. this._rotationSpeed = 25;
  24217. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24218. this._rotateOnAxisRelativeToMesh = false;
  24219. // injecting a canvas element on top of the canvas 3D game
  24220. if (!VirtualJoystick.vjCanvas) {
  24221. window.addEventListener("resize", function () {
  24222. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24223. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24224. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24225. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24226. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24227. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24228. }, false);
  24229. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24230. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24231. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24232. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24233. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24234. VirtualJoystick.vjCanvas.style.width = "100%";
  24235. VirtualJoystick.vjCanvas.style.height = "100%";
  24236. VirtualJoystick.vjCanvas.style.position = "absolute";
  24237. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24238. VirtualJoystick.vjCanvas.style.top = "0px";
  24239. VirtualJoystick.vjCanvas.style.left = "0px";
  24240. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24241. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24242. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24243. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24244. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24245. document.body.appendChild(VirtualJoystick.vjCanvas);
  24246. }
  24247. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24248. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24249. this.pressed = false;
  24250. // default joystick color
  24251. this._joystickColor = "cyan";
  24252. this._joystickPointerID = -1;
  24253. // current joystick position
  24254. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24255. // origin joystick position
  24256. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24257. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24258. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24259. _this._onPointerDown(evt);
  24260. }, false);
  24261. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24262. _this._onPointerMove(evt);
  24263. }, false);
  24264. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24265. _this._onPointerUp(evt);
  24266. }, false);
  24267. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24268. _this._onPointerUp(evt);
  24269. }, false);
  24270. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24271. evt.preventDefault(); // Disables system menu
  24272. }, false);
  24273. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24274. }
  24275. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24276. this._joystickSensibility = newJoystickSensibility;
  24277. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24278. };
  24279. VirtualJoystick.prototype._onPointerDown = function (e) {
  24280. var positionOnScreenCondition;
  24281. e.preventDefault();
  24282. if (this._leftJoystick === true) {
  24283. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24284. }
  24285. else {
  24286. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24287. }
  24288. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24289. // First contact will be dedicated to the virtual joystick
  24290. this._joystickPointerID = e.pointerId;
  24291. this._joystickPointerStartPos.x = e.clientX;
  24292. this._joystickPointerStartPos.y = e.clientY;
  24293. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24294. this._deltaJoystickVector.x = 0;
  24295. this._deltaJoystickVector.y = 0;
  24296. this.pressed = true;
  24297. this._touches.add(e.pointerId.toString(), e);
  24298. }
  24299. else {
  24300. // You can only trigger the action buttons with a joystick declared
  24301. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24302. this._action();
  24303. this._touches.add(e.pointerId.toString(), e);
  24304. }
  24305. }
  24306. };
  24307. VirtualJoystick.prototype._onPointerMove = function (e) {
  24308. // If the current pointer is the one associated to the joystick (first touch contact)
  24309. if (this._joystickPointerID == e.pointerId) {
  24310. this._joystickPointerPos.x = e.clientX;
  24311. this._joystickPointerPos.y = e.clientY;
  24312. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24313. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24314. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24315. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24316. switch (this._axisTargetedByLeftAndRight) {
  24317. case JoystickAxis.X:
  24318. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24319. break;
  24320. case JoystickAxis.Y:
  24321. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24322. break;
  24323. case JoystickAxis.Z:
  24324. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24325. break;
  24326. }
  24327. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24328. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24329. switch (this._axisTargetedByUpAndDown) {
  24330. case JoystickAxis.X:
  24331. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24332. break;
  24333. case JoystickAxis.Y:
  24334. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24335. break;
  24336. case JoystickAxis.Z:
  24337. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24338. break;
  24339. }
  24340. }
  24341. else {
  24342. if (this._touches.item(e.pointerId.toString())) {
  24343. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24344. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24345. }
  24346. }
  24347. };
  24348. VirtualJoystick.prototype._onPointerUp = function (e) {
  24349. this._clearCanvas();
  24350. if (this._joystickPointerID == e.pointerId) {
  24351. this._joystickPointerID = -1;
  24352. this.pressed = false;
  24353. }
  24354. this._deltaJoystickVector.x = 0;
  24355. this._deltaJoystickVector.y = 0;
  24356. this._touches.remove(e.pointerId.toString());
  24357. };
  24358. /**
  24359. * Change the color of the virtual joystick
  24360. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24361. */
  24362. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24363. this._joystickColor = newColor;
  24364. };
  24365. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24366. this._action = action;
  24367. };
  24368. // Define which axis you'd like to control for left & right
  24369. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24370. switch (axis) {
  24371. case JoystickAxis.X:
  24372. case JoystickAxis.Y:
  24373. case JoystickAxis.Z:
  24374. this._axisTargetedByLeftAndRight = axis;
  24375. break;
  24376. default:
  24377. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24378. break;
  24379. }
  24380. };
  24381. // Define which axis you'd like to control for up & down
  24382. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24383. switch (axis) {
  24384. case JoystickAxis.X:
  24385. case JoystickAxis.Y:
  24386. case JoystickAxis.Z:
  24387. this._axisTargetedByUpAndDown = axis;
  24388. break;
  24389. default:
  24390. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24391. break;
  24392. }
  24393. };
  24394. VirtualJoystick.prototype._clearCanvas = function () {
  24395. if (this._leftJoystick) {
  24396. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24397. }
  24398. else {
  24399. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24400. }
  24401. };
  24402. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24403. var _this = this;
  24404. if (this.pressed) {
  24405. this._clearCanvas();
  24406. this._touches.forEach(function (touch) {
  24407. if (touch.pointerId === _this._joystickPointerID) {
  24408. VirtualJoystick.vjCanvasContext.beginPath();
  24409. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24410. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24411. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24412. VirtualJoystick.vjCanvasContext.stroke();
  24413. VirtualJoystick.vjCanvasContext.beginPath();
  24414. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24415. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24416. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24417. VirtualJoystick.vjCanvasContext.stroke();
  24418. VirtualJoystick.vjCanvasContext.beginPath();
  24419. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24420. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24421. VirtualJoystick.vjCanvasContext.stroke();
  24422. }
  24423. else {
  24424. VirtualJoystick.vjCanvasContext.beginPath();
  24425. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24426. VirtualJoystick.vjCanvasContext.beginPath();
  24427. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24428. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24429. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24430. VirtualJoystick.vjCanvasContext.stroke();
  24431. }
  24432. ;
  24433. });
  24434. }
  24435. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24436. };
  24437. VirtualJoystick.prototype.releaseCanvas = function () {
  24438. if (VirtualJoystick.vjCanvas) {
  24439. document.body.removeChild(VirtualJoystick.vjCanvas);
  24440. VirtualJoystick.vjCanvas = null;
  24441. }
  24442. };
  24443. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24444. VirtualJoystick._globalJoystickIndex = 0;
  24445. return VirtualJoystick;
  24446. })();
  24447. BABYLON.VirtualJoystick = VirtualJoystick;
  24448. })(BABYLON || (BABYLON = {}));
  24449. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24450. var BABYLON;
  24451. (function (BABYLON) {
  24452. // We're mainly based on the logic defined into the FreeCamera code
  24453. var VirtualJoysticksCamera = (function (_super) {
  24454. __extends(VirtualJoysticksCamera, _super);
  24455. function VirtualJoysticksCamera(name, position, scene) {
  24456. _super.call(this, name, position, scene);
  24457. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24458. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24459. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24460. this._leftjoystick.setJoystickSensibility(0.15);
  24461. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24462. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24463. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24464. this._rightjoystick.reverseUpDown = true;
  24465. this._rightjoystick.setJoystickSensibility(0.05);
  24466. this._rightjoystick.setJoystickColor("yellow");
  24467. }
  24468. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24469. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24470. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24471. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24472. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24473. if (!this._leftjoystick.pressed) {
  24474. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24475. }
  24476. if (!this._rightjoystick.pressed) {
  24477. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24478. }
  24479. _super.prototype._checkInputs.call(this);
  24480. };
  24481. VirtualJoysticksCamera.prototype.dispose = function () {
  24482. this._leftjoystick.releaseCanvas();
  24483. _super.prototype.dispose.call(this);
  24484. };
  24485. return VirtualJoysticksCamera;
  24486. })(BABYLON.FreeCamera);
  24487. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24488. })(BABYLON || (BABYLON = {}));
  24489. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24490. var BABYLON;
  24491. (function (BABYLON) {
  24492. var ShaderMaterial = (function (_super) {
  24493. __extends(ShaderMaterial, _super);
  24494. function ShaderMaterial(name, scene, shaderPath, options) {
  24495. _super.call(this, name, scene);
  24496. this._textures = new Array();
  24497. this._floats = new Array();
  24498. this._floatsArrays = {};
  24499. this._colors3 = new Array();
  24500. this._colors4 = new Array();
  24501. this._vectors2 = new Array();
  24502. this._vectors3 = new Array();
  24503. this._matrices = new Array();
  24504. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24505. this._shaderPath = shaderPath;
  24506. options.needAlphaBlending = options.needAlphaBlending || false;
  24507. options.needAlphaTesting = options.needAlphaTesting || false;
  24508. options.attributes = options.attributes || ["position", "normal", "uv"];
  24509. options.uniforms = options.uniforms || ["worldViewProjection"];
  24510. options.samplers = options.samplers || [];
  24511. this._options = options;
  24512. }
  24513. ShaderMaterial.prototype.needAlphaBlending = function () {
  24514. return this._options.needAlphaBlending;
  24515. };
  24516. ShaderMaterial.prototype.needAlphaTesting = function () {
  24517. return this._options.needAlphaTesting;
  24518. };
  24519. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24520. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24521. this._options.uniforms.push(uniformName);
  24522. }
  24523. };
  24524. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24525. if (this._options.samplers.indexOf(name) === -1) {
  24526. this._options.samplers.push(name);
  24527. }
  24528. this._textures[name] = texture;
  24529. return this;
  24530. };
  24531. ShaderMaterial.prototype.setFloat = function (name, value) {
  24532. this._checkUniform(name);
  24533. this._floats[name] = value;
  24534. return this;
  24535. };
  24536. ShaderMaterial.prototype.setFloats = function (name, value) {
  24537. this._checkUniform(name);
  24538. this._floatsArrays[name] = value;
  24539. return this;
  24540. };
  24541. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24542. this._checkUniform(name);
  24543. this._colors3[name] = value;
  24544. return this;
  24545. };
  24546. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24547. this._checkUniform(name);
  24548. this._colors4[name] = value;
  24549. return this;
  24550. };
  24551. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24552. this._checkUniform(name);
  24553. this._vectors2[name] = value;
  24554. return this;
  24555. };
  24556. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24557. this._checkUniform(name);
  24558. this._vectors3[name] = value;
  24559. return this;
  24560. };
  24561. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24562. this._checkUniform(name);
  24563. this._matrices[name] = value;
  24564. return this;
  24565. };
  24566. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24567. var scene = this.getScene();
  24568. var engine = scene.getEngine();
  24569. if (!this.checkReadyOnEveryCall) {
  24570. if (this._renderId === scene.getRenderId()) {
  24571. return true;
  24572. }
  24573. }
  24574. // Instances
  24575. var defines = [];
  24576. var fallbacks = new BABYLON.EffectFallbacks();
  24577. if (useInstances) {
  24578. defines.push("#define INSTANCES");
  24579. }
  24580. // Bones
  24581. if (mesh && mesh.useBones) {
  24582. defines.push("#define BONES");
  24583. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24584. defines.push("#define BONES4");
  24585. fallbacks.addFallback(0, "BONES4");
  24586. }
  24587. // Alpha test
  24588. if (engine.getAlphaTesting()) {
  24589. defines.push("#define ALPHATEST");
  24590. }
  24591. var previousEffect = this._effect;
  24592. var join = defines.join("\n");
  24593. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24594. if (!this._effect.isReady()) {
  24595. return false;
  24596. }
  24597. if (previousEffect !== this._effect) {
  24598. scene.resetCachedMaterial();
  24599. }
  24600. this._renderId = scene.getRenderId();
  24601. return true;
  24602. };
  24603. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24604. var scene = this.getScene();
  24605. if (this._options.uniforms.indexOf("world") !== -1) {
  24606. this._effect.setMatrix("world", world);
  24607. }
  24608. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24609. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24610. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24611. }
  24612. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24613. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24614. }
  24615. };
  24616. ShaderMaterial.prototype.bind = function (world, mesh) {
  24617. // Std values
  24618. this.bindOnlyWorldMatrix(world);
  24619. if (this.getScene().getCachedMaterial() !== this) {
  24620. if (this._options.uniforms.indexOf("view") !== -1) {
  24621. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24622. }
  24623. if (this._options.uniforms.indexOf("projection") !== -1) {
  24624. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24625. }
  24626. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24627. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24628. }
  24629. // Bones
  24630. if (mesh && mesh.useBones) {
  24631. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24632. }
  24633. // Texture
  24634. for (var name in this._textures) {
  24635. this._effect.setTexture(name, this._textures[name]);
  24636. }
  24637. // Float
  24638. for (name in this._floats) {
  24639. this._effect.setFloat(name, this._floats[name]);
  24640. }
  24641. // Float s
  24642. for (name in this._floatsArrays) {
  24643. this._effect.setArray(name, this._floatsArrays[name]);
  24644. }
  24645. // Color3
  24646. for (name in this._colors3) {
  24647. this._effect.setColor3(name, this._colors3[name]);
  24648. }
  24649. // Color4
  24650. for (name in this._colors4) {
  24651. var color = this._colors4[name];
  24652. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24653. }
  24654. // Vector2
  24655. for (name in this._vectors2) {
  24656. this._effect.setVector2(name, this._vectors2[name]);
  24657. }
  24658. // Vector3
  24659. for (name in this._vectors3) {
  24660. this._effect.setVector3(name, this._vectors3[name]);
  24661. }
  24662. // Matrix
  24663. for (name in this._matrices) {
  24664. this._effect.setMatrix(name, this._matrices[name]);
  24665. }
  24666. }
  24667. _super.prototype.bind.call(this, world, mesh);
  24668. };
  24669. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24670. for (var name in this._textures) {
  24671. this._textures[name].dispose();
  24672. }
  24673. this._textures = [];
  24674. _super.prototype.dispose.call(this, forceDisposeEffect);
  24675. };
  24676. return ShaderMaterial;
  24677. })(BABYLON.Material);
  24678. BABYLON.ShaderMaterial = ShaderMaterial;
  24679. })(BABYLON || (BABYLON = {}));
  24680. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24681. var BABYLON;
  24682. (function (BABYLON) {
  24683. var VertexData = (function () {
  24684. function VertexData() {
  24685. }
  24686. VertexData.prototype.set = function (data, kind) {
  24687. switch (kind) {
  24688. case BABYLON.VertexBuffer.PositionKind:
  24689. this.positions = data;
  24690. break;
  24691. case BABYLON.VertexBuffer.NormalKind:
  24692. this.normals = data;
  24693. break;
  24694. case BABYLON.VertexBuffer.UVKind:
  24695. this.uvs = data;
  24696. break;
  24697. case BABYLON.VertexBuffer.UV2Kind:
  24698. this.uv2s = data;
  24699. break;
  24700. case BABYLON.VertexBuffer.ColorKind:
  24701. this.colors = data;
  24702. break;
  24703. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24704. this.matricesIndices = data;
  24705. break;
  24706. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24707. this.matricesWeights = data;
  24708. break;
  24709. }
  24710. };
  24711. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24712. this._applyTo(mesh, updatable);
  24713. };
  24714. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24715. this._applyTo(geometry, updatable);
  24716. };
  24717. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24718. this._update(mesh);
  24719. };
  24720. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24721. this._update(geometry);
  24722. };
  24723. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24724. if (this.positions) {
  24725. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24726. }
  24727. if (this.normals) {
  24728. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24729. }
  24730. if (this.uvs) {
  24731. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24732. }
  24733. if (this.uv2s) {
  24734. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24735. }
  24736. if (this.colors) {
  24737. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24738. }
  24739. if (this.matricesIndices) {
  24740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24741. }
  24742. if (this.matricesWeights) {
  24743. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24744. }
  24745. if (this.indices) {
  24746. meshOrGeometry.setIndices(this.indices);
  24747. }
  24748. };
  24749. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24750. if (this.positions) {
  24751. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24752. }
  24753. if (this.normals) {
  24754. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24755. }
  24756. if (this.uvs) {
  24757. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24758. }
  24759. if (this.uv2s) {
  24760. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24761. }
  24762. if (this.colors) {
  24763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24764. }
  24765. if (this.matricesIndices) {
  24766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24767. }
  24768. if (this.matricesWeights) {
  24769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24770. }
  24771. if (this.indices) {
  24772. meshOrGeometry.setIndices(this.indices);
  24773. }
  24774. };
  24775. VertexData.prototype.transform = function (matrix) {
  24776. var transformed = BABYLON.Vector3.Zero();
  24777. if (this.positions) {
  24778. var position = BABYLON.Vector3.Zero();
  24779. for (var index = 0; index < this.positions.length; index += 3) {
  24780. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24781. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24782. this.positions[index] = transformed.x;
  24783. this.positions[index + 1] = transformed.y;
  24784. this.positions[index + 2] = transformed.z;
  24785. }
  24786. }
  24787. if (this.normals) {
  24788. var normal = BABYLON.Vector3.Zero();
  24789. for (index = 0; index < this.normals.length; index += 3) {
  24790. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24791. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24792. this.normals[index] = transformed.x;
  24793. this.normals[index + 1] = transformed.y;
  24794. this.normals[index + 2] = transformed.z;
  24795. }
  24796. }
  24797. };
  24798. VertexData.prototype.merge = function (other) {
  24799. if (other.indices) {
  24800. if (!this.indices) {
  24801. this.indices = [];
  24802. }
  24803. var offset = this.positions ? this.positions.length / 3 : 0;
  24804. for (var index = 0; index < other.indices.length; index++) {
  24805. this.indices.push(other.indices[index] + offset);
  24806. }
  24807. }
  24808. if (other.positions) {
  24809. if (!this.positions) {
  24810. this.positions = [];
  24811. }
  24812. for (index = 0; index < other.positions.length; index++) {
  24813. this.positions.push(other.positions[index]);
  24814. }
  24815. }
  24816. if (other.normals) {
  24817. if (!this.normals) {
  24818. this.normals = [];
  24819. }
  24820. for (index = 0; index < other.normals.length; index++) {
  24821. this.normals.push(other.normals[index]);
  24822. }
  24823. }
  24824. if (other.uvs) {
  24825. if (!this.uvs) {
  24826. this.uvs = [];
  24827. }
  24828. for (index = 0; index < other.uvs.length; index++) {
  24829. this.uvs.push(other.uvs[index]);
  24830. }
  24831. }
  24832. if (other.uv2s) {
  24833. if (!this.uv2s) {
  24834. this.uv2s = [];
  24835. }
  24836. for (index = 0; index < other.uv2s.length; index++) {
  24837. this.uv2s.push(other.uv2s[index]);
  24838. }
  24839. }
  24840. if (other.matricesIndices) {
  24841. if (!this.matricesIndices) {
  24842. this.matricesIndices = [];
  24843. }
  24844. for (index = 0; index < other.matricesIndices.length; index++) {
  24845. this.matricesIndices.push(other.matricesIndices[index]);
  24846. }
  24847. }
  24848. if (other.matricesWeights) {
  24849. if (!this.matricesWeights) {
  24850. this.matricesWeights = [];
  24851. }
  24852. for (index = 0; index < other.matricesWeights.length; index++) {
  24853. this.matricesWeights.push(other.matricesWeights[index]);
  24854. }
  24855. }
  24856. if (other.colors) {
  24857. if (!this.colors) {
  24858. this.colors = [];
  24859. }
  24860. for (index = 0; index < other.colors.length; index++) {
  24861. this.colors.push(other.colors[index]);
  24862. }
  24863. }
  24864. };
  24865. // Statics
  24866. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24867. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24868. };
  24869. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24870. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24871. };
  24872. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24873. var result = new VertexData();
  24874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24875. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24876. }
  24877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24878. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24879. }
  24880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24881. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24882. }
  24883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24884. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24885. }
  24886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24887. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24888. }
  24889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24890. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24891. }
  24892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24893. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24894. }
  24895. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24896. return result;
  24897. };
  24898. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24899. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24900. closeArray = closeArray || false;
  24901. closePath = closePath || false;
  24902. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24903. offset = offset || defaultOffset;
  24904. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24905. var positions = [];
  24906. var indices = [];
  24907. var normals = [];
  24908. var uvs = [];
  24909. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24910. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24911. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24912. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24913. var minlg; // minimal length among all paths from pathArray
  24914. var lg = []; // array of path lengths : nb of vertex per path
  24915. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24916. var p; // path iterator
  24917. var i; // point iterator
  24918. var j; // point iterator
  24919. // if single path in pathArray
  24920. if (pathArray.length < 2) {
  24921. var ar1 = [];
  24922. var ar2 = [];
  24923. for (i = 0; i < pathArray[0].length - offset; i++) {
  24924. ar1.push(pathArray[0][i]);
  24925. ar2.push(pathArray[0][i + offset]);
  24926. }
  24927. pathArray = [ar1, ar2];
  24928. }
  24929. // positions and horizontal distances (u)
  24930. var idc = 0;
  24931. minlg = pathArray[0].length;
  24932. for (p = 0; p < pathArray.length; p++) {
  24933. uTotalDistance[p] = 0;
  24934. us[p] = [0];
  24935. var path = pathArray[p];
  24936. var l = path.length;
  24937. minlg = (minlg < l) ? minlg : l;
  24938. lg[p] = l;
  24939. idx[p] = idc;
  24940. j = 0;
  24941. while (j < l) {
  24942. positions.push(path[j].x, path[j].y, path[j].z);
  24943. if (j > 0) {
  24944. var vectlg = path[j].subtract(path[j - 1]).length();
  24945. var dist = vectlg + uTotalDistance[p];
  24946. us[p].push(dist);
  24947. uTotalDistance[p] = dist;
  24948. }
  24949. j++;
  24950. }
  24951. if (closePath) {
  24952. vectlg = path[0].subtract(path[j - 1]).length();
  24953. dist = vectlg + uTotalDistance[p];
  24954. uTotalDistance[p] = dist;
  24955. }
  24956. idc += l;
  24957. }
  24958. // vertical distances (v)
  24959. for (i = 0; i < minlg; i++) {
  24960. vTotalDistance[i] = 0;
  24961. vs[i] = [0];
  24962. var path1;
  24963. var path2;
  24964. for (p = 0; p < pathArray.length - 1; p++) {
  24965. path1 = pathArray[p];
  24966. path2 = pathArray[p + 1];
  24967. vectlg = path2[i].subtract(path1[i]).length();
  24968. dist = vectlg + vTotalDistance[i];
  24969. vs[i].push(dist);
  24970. vTotalDistance[i] = dist;
  24971. }
  24972. if (closeArray) {
  24973. path1 = pathArray[p];
  24974. path2 = pathArray[0];
  24975. vectlg = path2[i].subtract(path1[i]).length();
  24976. dist = vectlg + vTotalDistance[i];
  24977. vTotalDistance[i] = dist;
  24978. }
  24979. }
  24980. // uvs
  24981. var u;
  24982. var v;
  24983. for (p = 0; p < pathArray.length; p++) {
  24984. for (i = 0; i < minlg; i++) {
  24985. u = us[p][i] / uTotalDistance[p];
  24986. v = vs[i][p] / vTotalDistance[i];
  24987. uvs.push(u, v);
  24988. }
  24989. }
  24990. // indices
  24991. p = 0; // path index
  24992. var pi = 0; // positions array index
  24993. var l1 = lg[p] - 1; // path1 length
  24994. var l2 = lg[p + 1] - 1; // path2 length
  24995. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24996. var shft = idx[1] - idx[0]; // shift
  24997. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24998. var t1; // two consecutive triangles, so 4 points : point1
  24999. var t2; // point2
  25000. var t3; // point3
  25001. var t4; // point4
  25002. while (pi <= min && p < path1nb) {
  25003. // 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
  25004. t1 = pi;
  25005. t2 = pi + shft;
  25006. t3 = pi + 1;
  25007. t4 = pi + shft + 1;
  25008. indices.push(pi, pi + shft, pi + 1);
  25009. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25010. pi += 1;
  25011. if (pi === min) {
  25012. if (closePath) {
  25013. indices.push(pi, pi + shft, idx[p]);
  25014. indices.push(idx[p] + shft, idx[p], pi + shft);
  25015. t3 = idx[p];
  25016. t4 = idx[p] + shft;
  25017. }
  25018. p++;
  25019. if (p === lg.length - 1) {
  25020. shft = idx[0] - idx[p];
  25021. l1 = lg[p] - 1;
  25022. l2 = lg[0] - 1;
  25023. }
  25024. else {
  25025. shft = idx[p + 1] - idx[p];
  25026. l1 = lg[p] - 1;
  25027. l2 = lg[p + 1] - 1;
  25028. }
  25029. pi = idx[p];
  25030. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25031. }
  25032. }
  25033. // normals
  25034. VertexData.ComputeNormals(positions, indices, normals);
  25035. // sides
  25036. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25037. // Result
  25038. var vertexData = new VertexData();
  25039. vertexData.indices = indices;
  25040. vertexData.positions = positions;
  25041. vertexData.normals = normals;
  25042. vertexData.uvs = uvs;
  25043. return vertexData;
  25044. };
  25045. VertexData.CreateBox = function (size, sideOrientation) {
  25046. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25047. var normalsSource = [
  25048. new BABYLON.Vector3(0, 0, 1),
  25049. new BABYLON.Vector3(0, 0, -1),
  25050. new BABYLON.Vector3(1, 0, 0),
  25051. new BABYLON.Vector3(-1, 0, 0),
  25052. new BABYLON.Vector3(0, 1, 0),
  25053. new BABYLON.Vector3(0, -1, 0)
  25054. ];
  25055. var indices = [];
  25056. var positions = [];
  25057. var normals = [];
  25058. var uvs = [];
  25059. size = size || 1;
  25060. // Create each face in turn.
  25061. for (var index = 0; index < normalsSource.length; index++) {
  25062. var normal = normalsSource[index];
  25063. // Get two vectors perpendicular to the face normal and to each other.
  25064. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25065. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25066. // Six indices (two triangles) per face.
  25067. var verticesLength = positions.length / 3;
  25068. indices.push(verticesLength);
  25069. indices.push(verticesLength + 1);
  25070. indices.push(verticesLength + 2);
  25071. indices.push(verticesLength);
  25072. indices.push(verticesLength + 2);
  25073. indices.push(verticesLength + 3);
  25074. // Four vertices per face.
  25075. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25076. positions.push(vertex.x, vertex.y, vertex.z);
  25077. normals.push(normal.x, normal.y, normal.z);
  25078. uvs.push(1.0, 1.0);
  25079. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25080. positions.push(vertex.x, vertex.y, vertex.z);
  25081. normals.push(normal.x, normal.y, normal.z);
  25082. uvs.push(0.0, 1.0);
  25083. vertex = normal.add(side1).add(side2).scale(size / 2);
  25084. positions.push(vertex.x, vertex.y, vertex.z);
  25085. normals.push(normal.x, normal.y, normal.z);
  25086. uvs.push(0.0, 0.0);
  25087. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25088. positions.push(vertex.x, vertex.y, vertex.z);
  25089. normals.push(normal.x, normal.y, normal.z);
  25090. uvs.push(1.0, 0.0);
  25091. }
  25092. // sides
  25093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25094. // Result
  25095. var vertexData = new VertexData();
  25096. vertexData.indices = indices;
  25097. vertexData.positions = positions;
  25098. vertexData.normals = normals;
  25099. vertexData.uvs = uvs;
  25100. return vertexData;
  25101. };
  25102. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25103. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25104. segments = segments || 32;
  25105. diameter = diameter || 1;
  25106. var radius = diameter / 2;
  25107. var totalZRotationSteps = 2 + segments;
  25108. var totalYRotationSteps = 2 * totalZRotationSteps;
  25109. var indices = [];
  25110. var positions = [];
  25111. var normals = [];
  25112. var uvs = [];
  25113. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25114. var normalizedZ = zRotationStep / totalZRotationSteps;
  25115. var angleZ = (normalizedZ * Math.PI);
  25116. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25117. var normalizedY = yRotationStep / totalYRotationSteps;
  25118. var angleY = normalizedY * Math.PI * 2;
  25119. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25120. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25121. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25122. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25123. var vertex = complete.scale(radius);
  25124. var normal = BABYLON.Vector3.Normalize(vertex);
  25125. positions.push(vertex.x, vertex.y, vertex.z);
  25126. normals.push(normal.x, normal.y, normal.z);
  25127. uvs.push(normalizedZ, normalizedY);
  25128. }
  25129. if (zRotationStep > 0) {
  25130. var verticesCount = positions.length / 3;
  25131. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25132. indices.push((firstIndex));
  25133. indices.push((firstIndex + 1));
  25134. indices.push(firstIndex + totalYRotationSteps + 1);
  25135. indices.push((firstIndex + totalYRotationSteps + 1));
  25136. indices.push((firstIndex + 1));
  25137. indices.push((firstIndex + totalYRotationSteps + 2));
  25138. }
  25139. }
  25140. }
  25141. // Sides
  25142. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25143. // Result
  25144. var vertexData = new VertexData();
  25145. vertexData.indices = indices;
  25146. vertexData.positions = positions;
  25147. vertexData.normals = normals;
  25148. vertexData.uvs = uvs;
  25149. return vertexData;
  25150. };
  25151. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25152. if (subdivisions === void 0) { subdivisions = 1; }
  25153. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25154. var radiusTop = diameterTop / 2;
  25155. var radiusBottom = diameterBottom / 2;
  25156. var indices = [];
  25157. var positions = [];
  25158. var normals = [];
  25159. var uvs = [];
  25160. height = height || 1;
  25161. diameterTop = diameterTop || 0.5;
  25162. diameterBottom = diameterBottom || 1;
  25163. tessellation = tessellation || 16;
  25164. subdivisions = subdivisions || 1;
  25165. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25166. var getCircleVector = function (i) {
  25167. var angle = (i * 2.0 * Math.PI / tessellation);
  25168. var dx = Math.cos(angle);
  25169. var dz = Math.sin(angle);
  25170. return new BABYLON.Vector3(dx, 0, dz);
  25171. };
  25172. var createCylinderCap = function (isTop) {
  25173. var radius = isTop ? radiusTop : radiusBottom;
  25174. if (radius === 0) {
  25175. return;
  25176. }
  25177. var vbase = positions.length / 3;
  25178. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25179. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25180. if (!isTop) {
  25181. offset.scaleInPlace(-1);
  25182. textureScale.x = -textureScale.x;
  25183. }
  25184. // Positions, normals & uvs
  25185. for (var i = 0; i < tessellation; i++) {
  25186. var circleVector = getCircleVector(i);
  25187. var position = circleVector.scale(radius).add(offset);
  25188. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25189. positions.push(position.x, position.y, position.z);
  25190. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25191. }
  25192. // Indices
  25193. for (i = 0; i < tessellation - 2; i++) {
  25194. if (!isTop) {
  25195. indices.push(vbase);
  25196. indices.push(vbase + (i + 2) % tessellation);
  25197. indices.push(vbase + (i + 1) % tessellation);
  25198. }
  25199. else {
  25200. indices.push(vbase);
  25201. indices.push(vbase + (i + 1) % tessellation);
  25202. indices.push(vbase + (i + 2) % tessellation);
  25203. }
  25204. }
  25205. };
  25206. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25207. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25208. var stride = tessellation + 1;
  25209. // Positions, normals & uvs
  25210. for (var i = 0; i <= tessellation; i++) {
  25211. var circleVector = getCircleVector(i);
  25212. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25213. var position, radius = radiusBottom;
  25214. for (var s = 0; s <= subdivisions; s++) {
  25215. // Update variables
  25216. position = circleVector.scale(radius);
  25217. position.addInPlace(base.add(offset.scale(s)));
  25218. textureCoordinate.y += 1 / subdivisions;
  25219. radius += (radiusTop - radiusBottom) / subdivisions;
  25220. // Push in arrays
  25221. positions.push(position.x, position.y, position.z);
  25222. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25223. }
  25224. }
  25225. subdivisions += 1;
  25226. // Indices
  25227. for (s = 0; s < subdivisions - 1; s++) {
  25228. for (i = 0; i <= tessellation; i++) {
  25229. indices.push(i * subdivisions + s);
  25230. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25231. indices.push(i * subdivisions + (s + 1));
  25232. indices.push(i * subdivisions + (s + 1));
  25233. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25234. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25235. }
  25236. }
  25237. // Create flat triangle fan caps to seal the top and bottom.
  25238. createCylinderCap(true);
  25239. createCylinderCap(false);
  25240. // Normals
  25241. VertexData.ComputeNormals(positions, indices, normals);
  25242. // Sides
  25243. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25244. // Result
  25245. var vertexData = new VertexData();
  25246. vertexData.indices = indices;
  25247. vertexData.positions = positions;
  25248. vertexData.normals = normals;
  25249. vertexData.uvs = uvs;
  25250. return vertexData;
  25251. };
  25252. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25253. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25254. var indices = [];
  25255. var positions = [];
  25256. var normals = [];
  25257. var uvs = [];
  25258. diameter = diameter || 1;
  25259. thickness = thickness || 0.5;
  25260. tessellation = tessellation || 16;
  25261. var stride = tessellation + 1;
  25262. for (var i = 0; i <= tessellation; i++) {
  25263. var u = i / tessellation;
  25264. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25265. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25266. for (var j = 0; j <= tessellation; j++) {
  25267. var v = 1 - j / tessellation;
  25268. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25269. var dx = Math.cos(innerAngle);
  25270. var dy = Math.sin(innerAngle);
  25271. // Create a vertex.
  25272. var normal = new BABYLON.Vector3(dx, dy, 0);
  25273. var position = normal.scale(thickness / 2);
  25274. var textureCoordinate = new BABYLON.Vector2(u, v);
  25275. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25276. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25277. positions.push(position.x, position.y, position.z);
  25278. normals.push(normal.x, normal.y, normal.z);
  25279. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25280. // And create indices for two triangles.
  25281. var nextI = (i + 1) % stride;
  25282. var nextJ = (j + 1) % stride;
  25283. indices.push(i * stride + j);
  25284. indices.push(i * stride + nextJ);
  25285. indices.push(nextI * stride + j);
  25286. indices.push(i * stride + nextJ);
  25287. indices.push(nextI * stride + nextJ);
  25288. indices.push(nextI * stride + j);
  25289. }
  25290. }
  25291. // Sides
  25292. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25293. // Result
  25294. var vertexData = new VertexData();
  25295. vertexData.indices = indices;
  25296. vertexData.positions = positions;
  25297. vertexData.normals = normals;
  25298. vertexData.uvs = uvs;
  25299. return vertexData;
  25300. };
  25301. VertexData.CreateLines = function (points) {
  25302. var indices = [];
  25303. var positions = [];
  25304. for (var index = 0; index < points.length; index++) {
  25305. positions.push(points[index].x, points[index].y, points[index].z);
  25306. if (index > 0) {
  25307. indices.push(index - 1);
  25308. indices.push(index);
  25309. }
  25310. }
  25311. // Result
  25312. var vertexData = new VertexData();
  25313. vertexData.indices = indices;
  25314. vertexData.positions = positions;
  25315. return vertexData;
  25316. };
  25317. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25318. dashSize = dashSize || 3;
  25319. gapSize = gapSize || 1;
  25320. dashNb = dashNb || 200;
  25321. var positions = new Array();
  25322. var indices = new Array();
  25323. var curvect = BABYLON.Vector3.Zero();
  25324. var lg = 0;
  25325. var nb = 0;
  25326. var shft = 0;
  25327. var dashshft = 0;
  25328. var curshft = 0;
  25329. var idx = 0;
  25330. var i = 0;
  25331. for (i = 0; i < points.length - 1; i++) {
  25332. points[i + 1].subtractToRef(points[i], curvect);
  25333. lg += curvect.length();
  25334. }
  25335. shft = lg / dashNb;
  25336. dashshft = dashSize * shft / (dashSize + gapSize);
  25337. for (i = 0; i < points.length - 1; i++) {
  25338. points[i + 1].subtractToRef(points[i], curvect);
  25339. nb = Math.floor(curvect.length() / shft);
  25340. curvect.normalize();
  25341. for (var j = 0; j < nb; j++) {
  25342. curshft = shft * j;
  25343. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25344. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25345. indices.push(idx, idx + 1);
  25346. idx += 2;
  25347. }
  25348. }
  25349. // Result
  25350. var vertexData = new VertexData();
  25351. vertexData.positions = positions;
  25352. vertexData.indices = indices;
  25353. return vertexData;
  25354. };
  25355. VertexData.CreateGround = function (width, height, subdivisions) {
  25356. var indices = [];
  25357. var positions = [];
  25358. var normals = [];
  25359. var uvs = [];
  25360. var row, col;
  25361. width = width || 1;
  25362. height = height || 1;
  25363. subdivisions = subdivisions || 1;
  25364. for (row = 0; row <= subdivisions; row++) {
  25365. for (col = 0; col <= subdivisions; col++) {
  25366. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25367. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25368. positions.push(position.x, position.y, position.z);
  25369. normals.push(normal.x, normal.y, normal.z);
  25370. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25371. }
  25372. }
  25373. for (row = 0; row < subdivisions; row++) {
  25374. for (col = 0; col < subdivisions; col++) {
  25375. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25376. indices.push(col + 1 + row * (subdivisions + 1));
  25377. indices.push(col + row * (subdivisions + 1));
  25378. indices.push(col + (row + 1) * (subdivisions + 1));
  25379. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25380. indices.push(col + row * (subdivisions + 1));
  25381. }
  25382. }
  25383. // Result
  25384. var vertexData = new VertexData();
  25385. vertexData.indices = indices;
  25386. vertexData.positions = positions;
  25387. vertexData.normals = normals;
  25388. vertexData.uvs = uvs;
  25389. return vertexData;
  25390. };
  25391. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25392. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25393. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25394. var indices = [];
  25395. var positions = [];
  25396. var normals = [];
  25397. var uvs = [];
  25398. var row, col, tileRow, tileCol;
  25399. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25400. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25401. precision.w = (precision.w < 1) ? 1 : precision.w;
  25402. precision.h = (precision.h < 1) ? 1 : precision.h;
  25403. var tileSize = {
  25404. 'w': (xmax - xmin) / subdivisions.w,
  25405. 'h': (zmax - zmin) / subdivisions.h
  25406. };
  25407. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25408. // Indices
  25409. var base = positions.length / 3;
  25410. var rowLength = precision.w + 1;
  25411. for (row = 0; row < precision.h; row++) {
  25412. for (col = 0; col < precision.w; col++) {
  25413. var square = [
  25414. base + col + row * rowLength,
  25415. base + (col + 1) + row * rowLength,
  25416. base + (col + 1) + (row + 1) * rowLength,
  25417. base + col + (row + 1) * rowLength
  25418. ];
  25419. indices.push(square[1]);
  25420. indices.push(square[2]);
  25421. indices.push(square[3]);
  25422. indices.push(square[0]);
  25423. indices.push(square[1]);
  25424. indices.push(square[3]);
  25425. }
  25426. }
  25427. // Position, normals and uvs
  25428. var position = BABYLON.Vector3.Zero();
  25429. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25430. for (row = 0; row <= precision.h; row++) {
  25431. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25432. for (col = 0; col <= precision.w; col++) {
  25433. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25434. position.y = 0;
  25435. positions.push(position.x, position.y, position.z);
  25436. normals.push(normal.x, normal.y, normal.z);
  25437. uvs.push(col / precision.w, row / precision.h);
  25438. }
  25439. }
  25440. }
  25441. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25442. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25443. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25444. }
  25445. }
  25446. // Result
  25447. var vertexData = new VertexData();
  25448. vertexData.indices = indices;
  25449. vertexData.positions = positions;
  25450. vertexData.normals = normals;
  25451. vertexData.uvs = uvs;
  25452. return vertexData;
  25453. };
  25454. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25455. var indices = [];
  25456. var positions = [];
  25457. var normals = [];
  25458. var uvs = [];
  25459. var row, col;
  25460. // Vertices
  25461. for (row = 0; row <= subdivisions; row++) {
  25462. for (col = 0; col <= subdivisions; col++) {
  25463. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25464. // Compute height
  25465. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25466. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25467. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25468. var r = buffer[pos] / 255.0;
  25469. var g = buffer[pos + 1] / 255.0;
  25470. var b = buffer[pos + 2] / 255.0;
  25471. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25472. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25473. // Add vertex
  25474. positions.push(position.x, position.y, position.z);
  25475. normals.push(0, 0, 0);
  25476. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25477. }
  25478. }
  25479. // Indices
  25480. for (row = 0; row < subdivisions; row++) {
  25481. for (col = 0; col < subdivisions; col++) {
  25482. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25483. indices.push(col + 1 + row * (subdivisions + 1));
  25484. indices.push(col + row * (subdivisions + 1));
  25485. indices.push(col + (row + 1) * (subdivisions + 1));
  25486. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25487. indices.push(col + row * (subdivisions + 1));
  25488. }
  25489. }
  25490. // Normals
  25491. VertexData.ComputeNormals(positions, indices, normals);
  25492. // Result
  25493. var vertexData = new VertexData();
  25494. vertexData.indices = indices;
  25495. vertexData.positions = positions;
  25496. vertexData.normals = normals;
  25497. vertexData.uvs = uvs;
  25498. return vertexData;
  25499. };
  25500. VertexData.CreatePlane = function (size, sideOrientation) {
  25501. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25502. var indices = [];
  25503. var positions = [];
  25504. var normals = [];
  25505. var uvs = [];
  25506. size = size || 1;
  25507. // Vertices
  25508. var halfSize = size / 2.0;
  25509. positions.push(-halfSize, -halfSize, 0);
  25510. normals.push(0, 0, -1.0);
  25511. uvs.push(0.0, 0.0);
  25512. positions.push(halfSize, -halfSize, 0);
  25513. normals.push(0, 0, -1.0);
  25514. uvs.push(1.0, 0.0);
  25515. positions.push(halfSize, halfSize, 0);
  25516. normals.push(0, 0, -1.0);
  25517. uvs.push(1.0, 1.0);
  25518. positions.push(-halfSize, halfSize, 0);
  25519. normals.push(0, 0, -1.0);
  25520. uvs.push(0.0, 1.0);
  25521. // Indices
  25522. indices.push(0);
  25523. indices.push(1);
  25524. indices.push(2);
  25525. indices.push(0);
  25526. indices.push(2);
  25527. indices.push(3);
  25528. // Sides
  25529. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25530. // Result
  25531. var vertexData = new VertexData();
  25532. vertexData.indices = indices;
  25533. vertexData.positions = positions;
  25534. vertexData.normals = normals;
  25535. vertexData.uvs = uvs;
  25536. return vertexData;
  25537. };
  25538. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25539. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25540. var positions = [];
  25541. var indices = [];
  25542. var normals = [];
  25543. var uvs = [];
  25544. // positions and uvs
  25545. positions.push(0, 0, 0); // disc center first
  25546. uvs.push(0.5, 0.5);
  25547. var step = Math.PI * 2 / tessellation;
  25548. for (var a = 0; a < Math.PI * 2; a += step) {
  25549. var x = Math.cos(a);
  25550. var y = Math.sin(a);
  25551. var u = (x + 1) / 2;
  25552. var v = (1 - y) / 2;
  25553. positions.push(radius * x, radius * y, 0);
  25554. uvs.push(u, v);
  25555. }
  25556. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25557. uvs.push(uvs[2], uvs[3]);
  25558. //indices
  25559. var vertexNb = positions.length / 3;
  25560. for (var i = 1; i < vertexNb - 1; i++) {
  25561. indices.push(i + 1, 0, i);
  25562. }
  25563. // result
  25564. VertexData.ComputeNormals(positions, indices, normals);
  25565. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25566. var vertexData = new VertexData();
  25567. vertexData.indices = indices;
  25568. vertexData.positions = positions;
  25569. vertexData.normals = normals;
  25570. vertexData.uvs = uvs;
  25571. return vertexData;
  25572. };
  25573. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25574. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25575. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25576. var indices = [];
  25577. var positions = [];
  25578. var normals = [];
  25579. var uvs = [];
  25580. radius = radius || 2;
  25581. tube = tube || 0.5;
  25582. radialSegments = radialSegments || 32;
  25583. tubularSegments = tubularSegments || 32;
  25584. p = p || 2;
  25585. q = q || 3;
  25586. // Helper
  25587. var getPos = function (angle) {
  25588. var cu = Math.cos(angle);
  25589. var su = Math.sin(angle);
  25590. var quOverP = q / p * angle;
  25591. var cs = Math.cos(quOverP);
  25592. var tx = radius * (2 + cs) * 0.5 * cu;
  25593. var ty = radius * (2 + cs) * su * 0.5;
  25594. var tz = radius * Math.sin(quOverP) * 0.5;
  25595. return new BABYLON.Vector3(tx, ty, tz);
  25596. };
  25597. // Vertices
  25598. for (var i = 0; i <= radialSegments; i++) {
  25599. var modI = i % radialSegments;
  25600. var u = modI / radialSegments * 2 * p * Math.PI;
  25601. var p1 = getPos(u);
  25602. var p2 = getPos(u + 0.01);
  25603. var tang = p2.subtract(p1);
  25604. var n = p2.add(p1);
  25605. var bitan = BABYLON.Vector3.Cross(tang, n);
  25606. n = BABYLON.Vector3.Cross(bitan, tang);
  25607. bitan.normalize();
  25608. n.normalize();
  25609. for (var j = 0; j < tubularSegments; j++) {
  25610. var modJ = j % tubularSegments;
  25611. var v = modJ / tubularSegments * 2 * Math.PI;
  25612. var cx = -tube * Math.cos(v);
  25613. var cy = tube * Math.sin(v);
  25614. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25615. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25616. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25617. uvs.push(i / radialSegments);
  25618. uvs.push(j / tubularSegments);
  25619. }
  25620. }
  25621. for (i = 0; i < radialSegments; i++) {
  25622. for (j = 0; j < tubularSegments; j++) {
  25623. var jNext = (j + 1) % tubularSegments;
  25624. var a = i * tubularSegments + j;
  25625. var b = (i + 1) * tubularSegments + j;
  25626. var c = (i + 1) * tubularSegments + jNext;
  25627. var d = i * tubularSegments + jNext;
  25628. indices.push(d);
  25629. indices.push(b);
  25630. indices.push(a);
  25631. indices.push(d);
  25632. indices.push(c);
  25633. indices.push(b);
  25634. }
  25635. }
  25636. // Normals
  25637. VertexData.ComputeNormals(positions, indices, normals);
  25638. // Sides
  25639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25640. // Result
  25641. var vertexData = new VertexData();
  25642. vertexData.indices = indices;
  25643. vertexData.positions = positions;
  25644. vertexData.normals = normals;
  25645. vertexData.uvs = uvs;
  25646. return vertexData;
  25647. };
  25648. // Tools
  25649. /**
  25650. * @param {any} - positions (number[] or Float32Array)
  25651. * @param {any} - indices (number[] or Uint16Array)
  25652. * @param {any} - normals (number[] or Float32Array)
  25653. */
  25654. VertexData.ComputeNormals = function (positions, indices, normals) {
  25655. var index = 0;
  25656. // temp Vector3
  25657. var p1 = BABYLON.Vector3.Zero();
  25658. var p2 = BABYLON.Vector3.Zero();
  25659. var p3 = BABYLON.Vector3.Zero();
  25660. var p1p2 = BABYLON.Vector3.Zero();
  25661. var p3p2 = BABYLON.Vector3.Zero();
  25662. var faceNormal = BABYLON.Vector3.Zero();
  25663. var vertexNormali1 = BABYLON.Vector3.Zero();
  25664. var vertexNormali2 = BABYLON.Vector3.Zero();
  25665. var vertexNormali3 = BABYLON.Vector3.Zero();
  25666. // indice triplet = 1 face
  25667. var nbFaces = indices.length / 3;
  25668. for (index = 0; index < nbFaces; index++) {
  25669. var i1 = indices[index * 3];
  25670. var i2 = indices[index * 3 + 1];
  25671. var i3 = indices[index * 3 + 2];
  25672. // setting the temp V3
  25673. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25674. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25675. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25676. p1.subtractToRef(p2, p1p2);
  25677. p3.subtractToRef(p2, p3p2);
  25678. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25679. faceNormal.normalize();
  25680. // All intermediate results are stored in the normals array :
  25681. // get the normals at i1, i2 and i3 indexes
  25682. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25683. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25684. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25685. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25686. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25687. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25688. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25689. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25690. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25691. // make intermediate vectors3 from normals values
  25692. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25693. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25694. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25695. // add the current face normals to these intermediate vectors3
  25696. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25697. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25698. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25699. // store back intermediate vectors3 into the normals array
  25700. normals[i1 * 3] = vertexNormali1.x;
  25701. normals[i1 * 3 + 1] = vertexNormali1.y;
  25702. normals[i1 * 3 + 2] = vertexNormali1.z;
  25703. normals[i2 * 3] = vertexNormali2.x;
  25704. normals[i2 * 3 + 1] = vertexNormali2.y;
  25705. normals[i2 * 3 + 2] = vertexNormali2.z;
  25706. normals[i3 * 3] = vertexNormali3.x;
  25707. normals[i3 * 3 + 1] = vertexNormali3.y;
  25708. normals[i3 * 3 + 2] = vertexNormali3.z;
  25709. }
  25710. // last normalization
  25711. for (index = 0; index < normals.length / 3; index++) {
  25712. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25713. vertexNormali1.normalize();
  25714. normals[index * 3] = vertexNormali1.x;
  25715. normals[index * 3 + 1] = vertexNormali1.y;
  25716. normals[index * 3 + 2] = vertexNormali1.z;
  25717. }
  25718. };
  25719. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25720. var li = indices.length;
  25721. var ln = normals.length;
  25722. var i;
  25723. var n;
  25724. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25725. switch (sideOrientation) {
  25726. case BABYLON.Mesh.FRONTSIDE:
  25727. // nothing changed
  25728. break;
  25729. case BABYLON.Mesh.BACKSIDE:
  25730. var tmp;
  25731. // indices
  25732. for (i = 0; i < li; i += 3) {
  25733. tmp = indices[i];
  25734. indices[i] = indices[i + 2];
  25735. indices[i + 2] = tmp;
  25736. }
  25737. // normals
  25738. for (n = 0; n < ln; n++) {
  25739. normals[n] = -normals[n];
  25740. }
  25741. break;
  25742. case BABYLON.Mesh.DOUBLESIDE:
  25743. // positions
  25744. var lp = positions.length;
  25745. var l = lp / 3;
  25746. for (var p = 0; p < lp; p++) {
  25747. positions[lp + p] = positions[p];
  25748. }
  25749. // indices
  25750. for (i = 0; i < li; i += 3) {
  25751. indices[i + li] = indices[i + 2] + l;
  25752. indices[i + 1 + li] = indices[i + 1] + l;
  25753. indices[i + 2 + li] = indices[i] + l;
  25754. }
  25755. // normals
  25756. for (n = 0; n < ln; n++) {
  25757. normals[ln + n] = -normals[n];
  25758. }
  25759. // uvs
  25760. var lu = uvs.length;
  25761. for (var u = 0; u < lu; u++) {
  25762. uvs[u + lu] = uvs[u];
  25763. }
  25764. break;
  25765. }
  25766. };
  25767. return VertexData;
  25768. })();
  25769. BABYLON.VertexData = VertexData;
  25770. })(BABYLON || (BABYLON = {}));
  25771. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25772. var BABYLON;
  25773. (function (BABYLON) {
  25774. var AnaglyphFreeCamera = (function (_super) {
  25775. __extends(AnaglyphFreeCamera, _super);
  25776. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25777. _super.call(this, name, position, scene);
  25778. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25779. }
  25780. return AnaglyphFreeCamera;
  25781. })(BABYLON.FreeCamera);
  25782. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25783. var AnaglyphArcRotateCamera = (function (_super) {
  25784. __extends(AnaglyphArcRotateCamera, _super);
  25785. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25786. _super.call(this, name, alpha, beta, radius, target, scene);
  25787. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25788. }
  25789. return AnaglyphArcRotateCamera;
  25790. })(BABYLON.ArcRotateCamera);
  25791. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25792. var AnaglyphGamepadCamera = (function (_super) {
  25793. __extends(AnaglyphGamepadCamera, _super);
  25794. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  25795. _super.call(this, name, position, scene);
  25796. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25797. }
  25798. return AnaglyphGamepadCamera;
  25799. })(BABYLON.GamepadCamera);
  25800. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  25801. })(BABYLON || (BABYLON = {}));
  25802. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25803. var BABYLON;
  25804. (function (BABYLON) {
  25805. var AnaglyphPostProcess = (function (_super) {
  25806. __extends(AnaglyphPostProcess, _super);
  25807. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25808. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25809. }
  25810. return AnaglyphPostProcess;
  25811. })(BABYLON.PostProcess);
  25812. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25813. })(BABYLON || (BABYLON = {}));
  25814. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25815. var BABYLON;
  25816. (function (BABYLON) {
  25817. var Tags = (function () {
  25818. function Tags() {
  25819. }
  25820. Tags.EnableFor = function (obj) {
  25821. obj._tags = obj._tags || {};
  25822. obj.hasTags = function () {
  25823. return Tags.HasTags(obj);
  25824. };
  25825. obj.addTags = function (tagsString) {
  25826. return Tags.AddTagsTo(obj, tagsString);
  25827. };
  25828. obj.removeTags = function (tagsString) {
  25829. return Tags.RemoveTagsFrom(obj, tagsString);
  25830. };
  25831. obj.matchesTagsQuery = function (tagsQuery) {
  25832. return Tags.MatchesQuery(obj, tagsQuery);
  25833. };
  25834. };
  25835. Tags.DisableFor = function (obj) {
  25836. delete obj._tags;
  25837. delete obj.hasTags;
  25838. delete obj.addTags;
  25839. delete obj.removeTags;
  25840. delete obj.matchesTagsQuery;
  25841. };
  25842. Tags.HasTags = function (obj) {
  25843. if (!obj._tags) {
  25844. return false;
  25845. }
  25846. return !BABYLON.Tools.IsEmpty(obj._tags);
  25847. };
  25848. Tags.GetTags = function (obj) {
  25849. if (!obj._tags) {
  25850. return null;
  25851. }
  25852. return obj._tags;
  25853. };
  25854. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25855. // a tag cannot start with '||', '&&', and '!'
  25856. // it cannot contain whitespaces
  25857. Tags.AddTagsTo = function (obj, tagsString) {
  25858. if (!tagsString) {
  25859. return;
  25860. }
  25861. var tags = tagsString.split(" ");
  25862. for (var t in tags) {
  25863. Tags._AddTagTo(obj, tags[t]);
  25864. }
  25865. };
  25866. Tags._AddTagTo = function (obj, tag) {
  25867. tag = tag.trim();
  25868. if (tag === "" || tag === "true" || tag === "false") {
  25869. return;
  25870. }
  25871. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25872. return;
  25873. }
  25874. Tags.EnableFor(obj);
  25875. obj._tags[tag] = true;
  25876. };
  25877. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25878. if (!Tags.HasTags(obj)) {
  25879. return;
  25880. }
  25881. var tags = tagsString.split(" ");
  25882. for (var t in tags) {
  25883. Tags._RemoveTagFrom(obj, tags[t]);
  25884. }
  25885. };
  25886. Tags._RemoveTagFrom = function (obj, tag) {
  25887. delete obj._tags[tag];
  25888. };
  25889. Tags.MatchesQuery = function (obj, tagsQuery) {
  25890. if (tagsQuery === undefined) {
  25891. return true;
  25892. }
  25893. if (tagsQuery === "") {
  25894. return Tags.HasTags(obj);
  25895. }
  25896. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25897. };
  25898. return Tags;
  25899. })();
  25900. BABYLON.Tags = Tags;
  25901. })(BABYLON || (BABYLON = {}));
  25902. //# sourceMappingURL=babylon.tags.js.map
  25903. var BABYLON;
  25904. (function (BABYLON) {
  25905. var Internals;
  25906. (function (Internals) {
  25907. var AndOrNotEvaluator = (function () {
  25908. function AndOrNotEvaluator() {
  25909. }
  25910. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25911. if (!query.match(/\([^\(\)]*\)/g)) {
  25912. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25913. }
  25914. else {
  25915. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25916. // remove parenthesis
  25917. r = r.slice(1, r.length - 1);
  25918. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25919. });
  25920. }
  25921. if (query === "true") {
  25922. return true;
  25923. }
  25924. if (query === "false") {
  25925. return false;
  25926. }
  25927. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25928. };
  25929. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25930. evaluateCallback = evaluateCallback || (function (r) {
  25931. return r === "true" ? true : false;
  25932. });
  25933. var result;
  25934. var or = parenthesisContent.split("||");
  25935. for (var i in or) {
  25936. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25937. var and = ori.split("&&");
  25938. if (and.length > 1) {
  25939. for (var j = 0; j < and.length; ++j) {
  25940. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25941. if (andj !== "true" && andj !== "false") {
  25942. if (andj[0] === "!") {
  25943. result = !evaluateCallback(andj.substring(1));
  25944. }
  25945. else {
  25946. result = evaluateCallback(andj);
  25947. }
  25948. }
  25949. else {
  25950. result = andj === "true" ? true : false;
  25951. }
  25952. if (!result) {
  25953. ori = "false";
  25954. break;
  25955. }
  25956. }
  25957. }
  25958. if (result || ori === "true") {
  25959. result = true;
  25960. break;
  25961. }
  25962. // result equals false (or undefined)
  25963. if (ori !== "true" && ori !== "false") {
  25964. if (ori[0] === "!") {
  25965. result = !evaluateCallback(ori.substring(1));
  25966. }
  25967. else {
  25968. result = evaluateCallback(ori);
  25969. }
  25970. }
  25971. else {
  25972. result = ori === "true" ? true : false;
  25973. }
  25974. }
  25975. // the whole parenthesis scope is replaced by 'true' or 'false'
  25976. return result ? "true" : "false";
  25977. };
  25978. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25979. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25980. // remove whitespaces
  25981. r = r.replace(/[\s]/g, function () { return ""; });
  25982. return r.length % 2 ? "!" : "";
  25983. });
  25984. booleanString = booleanString.trim();
  25985. if (booleanString === "!true") {
  25986. booleanString = "false";
  25987. }
  25988. else if (booleanString === "!false") {
  25989. booleanString = "true";
  25990. }
  25991. return booleanString;
  25992. };
  25993. return AndOrNotEvaluator;
  25994. })();
  25995. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25996. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25997. })(BABYLON || (BABYLON = {}));
  25998. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25999. var BABYLON;
  26000. (function (BABYLON) {
  26001. var PostProcessRenderPass = (function () {
  26002. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26003. this._enabled = true;
  26004. this._refCount = 0;
  26005. this._name = name;
  26006. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26007. this.setRenderList(renderList);
  26008. this._renderTexture.onBeforeRender = beforeRender;
  26009. this._renderTexture.onAfterRender = afterRender;
  26010. this._scene = scene;
  26011. this._renderList = renderList;
  26012. }
  26013. // private
  26014. PostProcessRenderPass.prototype._incRefCount = function () {
  26015. if (this._refCount === 0) {
  26016. this._scene.customRenderTargets.push(this._renderTexture);
  26017. }
  26018. return ++this._refCount;
  26019. };
  26020. PostProcessRenderPass.prototype._decRefCount = function () {
  26021. this._refCount--;
  26022. if (this._refCount <= 0) {
  26023. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26024. }
  26025. return this._refCount;
  26026. };
  26027. PostProcessRenderPass.prototype._update = function () {
  26028. this.setRenderList(this._renderList);
  26029. };
  26030. // public
  26031. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26032. this._renderTexture.renderList = renderList;
  26033. };
  26034. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26035. return this._renderTexture;
  26036. };
  26037. return PostProcessRenderPass;
  26038. })();
  26039. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26040. })(BABYLON || (BABYLON = {}));
  26041. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26042. var BABYLON;
  26043. (function (BABYLON) {
  26044. var PostProcessRenderEffect = (function () {
  26045. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26046. this._engine = engine;
  26047. this._name = name;
  26048. this._singleInstance = singleInstance || true;
  26049. this._getPostProcess = getPostProcess;
  26050. this._cameras = [];
  26051. this._indicesForCamera = [];
  26052. this._postProcesses = {};
  26053. this._renderPasses = {};
  26054. this._renderEffectAsPasses = {};
  26055. }
  26056. PostProcessRenderEffect.prototype._update = function () {
  26057. for (var renderPassName in this._renderPasses) {
  26058. this._renderPasses[renderPassName]._update();
  26059. }
  26060. };
  26061. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26062. this._renderPasses[renderPass._name] = renderPass;
  26063. this._linkParameters();
  26064. };
  26065. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26066. delete this._renderPasses[renderPass._name];
  26067. this._linkParameters();
  26068. };
  26069. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26070. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26071. this._linkParameters();
  26072. };
  26073. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26074. for (var renderPassName in this._renderPasses) {
  26075. if (renderPassName === passName) {
  26076. return this._renderPasses[passName];
  26077. }
  26078. }
  26079. };
  26080. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26081. this._renderPasses = {};
  26082. this._linkParameters();
  26083. };
  26084. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26085. var cameraKey;
  26086. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26087. for (var i = 0; i < _cam.length; i++) {
  26088. var camera = _cam[i];
  26089. var cameraName = camera.name;
  26090. if (this._singleInstance) {
  26091. cameraKey = 0;
  26092. }
  26093. else {
  26094. cameraKey = cameraName;
  26095. }
  26096. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26097. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26098. if (!this._indicesForCamera[cameraName]) {
  26099. this._indicesForCamera[cameraName] = [];
  26100. }
  26101. this._indicesForCamera[cameraName].push(index);
  26102. if (this._cameras.indexOf(camera) === -1) {
  26103. this._cameras[cameraName] = camera;
  26104. }
  26105. for (var passName in this._renderPasses) {
  26106. this._renderPasses[passName]._incRefCount();
  26107. }
  26108. }
  26109. this._linkParameters();
  26110. };
  26111. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26112. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26113. for (var i = 0; i < _cam.length; i++) {
  26114. var camera = _cam[i];
  26115. var cameraName = camera.name;
  26116. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26117. var index = this._cameras.indexOf(cameraName);
  26118. this._indicesForCamera.splice(index, 1);
  26119. this._cameras.splice(index, 1);
  26120. for (var passName in this._renderPasses) {
  26121. this._renderPasses[passName]._decRefCount();
  26122. }
  26123. }
  26124. };
  26125. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26127. for (var i = 0; i < _cam.length; i++) {
  26128. var camera = _cam[i];
  26129. var cameraName = camera.name;
  26130. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26131. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26132. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26133. }
  26134. }
  26135. for (var passName in this._renderPasses) {
  26136. this._renderPasses[passName]._incRefCount();
  26137. }
  26138. }
  26139. };
  26140. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26141. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26142. for (var i = 0; i < _cam.length; i++) {
  26143. var camera = _cam[i];
  26144. var cameraName = camera.Name;
  26145. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26146. for (var passName in this._renderPasses) {
  26147. this._renderPasses[passName]._decRefCount();
  26148. }
  26149. }
  26150. };
  26151. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26152. if (this._singleInstance) {
  26153. return this._postProcesses[0];
  26154. }
  26155. else {
  26156. return this._postProcesses[camera.name];
  26157. }
  26158. };
  26159. PostProcessRenderEffect.prototype._linkParameters = function () {
  26160. var _this = this;
  26161. for (var index in this._postProcesses) {
  26162. if (this.applyParameters) {
  26163. this.applyParameters(this._postProcesses[index]);
  26164. }
  26165. this._postProcesses[index].onBeforeRender = function (effect) {
  26166. _this._linkTextures(effect);
  26167. };
  26168. }
  26169. };
  26170. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26171. for (var renderPassName in this._renderPasses) {
  26172. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26173. }
  26174. for (var renderEffectName in this._renderEffectAsPasses) {
  26175. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26176. }
  26177. };
  26178. return PostProcessRenderEffect;
  26179. })();
  26180. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26181. })(BABYLON || (BABYLON = {}));
  26182. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26183. var BABYLON;
  26184. (function (BABYLON) {
  26185. var PostProcessRenderPipeline = (function () {
  26186. function PostProcessRenderPipeline(engine, name) {
  26187. this._engine = engine;
  26188. this._name = name;
  26189. this._renderEffects = {};
  26190. this._renderEffectsForIsolatedPass = {};
  26191. this._cameras = [];
  26192. }
  26193. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26194. this._renderEffects[renderEffect._name] = renderEffect;
  26195. };
  26196. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26197. var renderEffects = this._renderEffects[renderEffectName];
  26198. if (!renderEffects) {
  26199. return;
  26200. }
  26201. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26202. };
  26203. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26204. var renderEffects = this._renderEffects[renderEffectName];
  26205. if (!renderEffects) {
  26206. return;
  26207. }
  26208. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26209. };
  26210. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26211. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26212. var indicesToDelete = [];
  26213. for (var i = 0; i < _cam.length; i++) {
  26214. var camera = _cam[i];
  26215. var cameraName = camera.name;
  26216. if (this._cameras.indexOf(camera) === -1) {
  26217. this._cameras[cameraName] = camera;
  26218. }
  26219. else if (unique) {
  26220. indicesToDelete.push(i);
  26221. }
  26222. }
  26223. for (var i = 0; i < indicesToDelete.length; i++) {
  26224. cameras.splice(indicesToDelete[i], 1);
  26225. }
  26226. for (var renderEffectName in this._renderEffects) {
  26227. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26228. }
  26229. };
  26230. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26231. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26232. for (var renderEffectName in this._renderEffects) {
  26233. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26234. }
  26235. for (var i = 0; i < _cam.length; i++) {
  26236. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26237. }
  26238. };
  26239. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26240. var _this = this;
  26241. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26242. var pass = null;
  26243. for (var renderEffectName in this._renderEffects) {
  26244. pass = this._renderEffects[renderEffectName].getPass(passName);
  26245. if (pass != null) {
  26246. break;
  26247. }
  26248. }
  26249. if (pass === null) {
  26250. return;
  26251. }
  26252. for (var renderEffectName in this._renderEffects) {
  26253. this._renderEffects[renderEffectName]._disable(_cam);
  26254. }
  26255. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26256. for (var i = 0; i < _cam.length; i++) {
  26257. var camera = _cam[i];
  26258. var cameraName = camera.name;
  26259. 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); });
  26260. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26261. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26262. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26263. }
  26264. };
  26265. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26266. var _this = this;
  26267. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26268. for (var i = 0; i < _cam.length; i++) {
  26269. var camera = _cam[i];
  26270. var cameraName = camera.name;
  26271. 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); });
  26272. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26273. }
  26274. for (var renderEffectName in this._renderEffects) {
  26275. this._renderEffects[renderEffectName]._enable(_cam);
  26276. }
  26277. };
  26278. PostProcessRenderPipeline.prototype._update = function () {
  26279. for (var renderEffectName in this._renderEffects) {
  26280. this._renderEffects[renderEffectName]._update();
  26281. }
  26282. for (var i = 0; i < this._cameras.length; i++) {
  26283. var cameraName = this._cameras[i].name;
  26284. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26285. this._renderEffectsForIsolatedPass[cameraName]._update();
  26286. }
  26287. }
  26288. };
  26289. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26290. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26291. return PostProcessRenderPipeline;
  26292. })();
  26293. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26294. })(BABYLON || (BABYLON = {}));
  26295. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26296. var BABYLON;
  26297. (function (BABYLON) {
  26298. var PostProcessRenderPipelineManager = (function () {
  26299. function PostProcessRenderPipelineManager() {
  26300. this._renderPipelines = {};
  26301. }
  26302. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26303. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26304. };
  26305. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26306. var renderPipeline = this._renderPipelines[renderPipelineName];
  26307. if (!renderPipeline) {
  26308. return;
  26309. }
  26310. renderPipeline._attachCameras(cameras, unique);
  26311. };
  26312. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26313. var renderPipeline = this._renderPipelines[renderPipelineName];
  26314. if (!renderPipeline) {
  26315. return;
  26316. }
  26317. renderPipeline._detachCameras(cameras);
  26318. };
  26319. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26320. var renderPipeline = this._renderPipelines[renderPipelineName];
  26321. if (!renderPipeline) {
  26322. return;
  26323. }
  26324. renderPipeline._enableEffect(renderEffectName, cameras);
  26325. };
  26326. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26327. var renderPipeline = this._renderPipelines[renderPipelineName];
  26328. if (!renderPipeline) {
  26329. return;
  26330. }
  26331. renderPipeline._disableEffect(renderEffectName, cameras);
  26332. };
  26333. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26334. var renderPipeline = this._renderPipelines[renderPipelineName];
  26335. if (!renderPipeline) {
  26336. return;
  26337. }
  26338. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26339. };
  26340. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26341. var renderPipeline = this._renderPipelines[renderPipelineName];
  26342. if (!renderPipeline) {
  26343. return;
  26344. }
  26345. renderPipeline._disableDisplayOnlyPass(cameras);
  26346. };
  26347. PostProcessRenderPipelineManager.prototype.update = function () {
  26348. for (var renderPipelineName in this._renderPipelines) {
  26349. this._renderPipelines[renderPipelineName]._update();
  26350. }
  26351. };
  26352. return PostProcessRenderPipelineManager;
  26353. })();
  26354. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26355. })(BABYLON || (BABYLON = {}));
  26356. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26357. var BABYLON;
  26358. (function (BABYLON) {
  26359. var DisplayPassPostProcess = (function (_super) {
  26360. __extends(DisplayPassPostProcess, _super);
  26361. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26362. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26363. }
  26364. return DisplayPassPostProcess;
  26365. })(BABYLON.PostProcess);
  26366. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26367. })(BABYLON || (BABYLON = {}));
  26368. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26369. var BABYLON;
  26370. (function (BABYLON) {
  26371. var BoundingBoxRenderer = (function () {
  26372. function BoundingBoxRenderer(scene) {
  26373. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26374. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26375. this.showBackLines = true;
  26376. this.renderList = new BABYLON.SmartArray(32);
  26377. this._scene = scene;
  26378. }
  26379. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26380. if (this._colorShader) {
  26381. return;
  26382. }
  26383. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26384. attributes: ["position"],
  26385. uniforms: ["worldViewProjection", "color"]
  26386. });
  26387. var engine = this._scene.getEngine();
  26388. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26389. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26390. this._ib = 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]);
  26391. };
  26392. BoundingBoxRenderer.prototype.reset = function () {
  26393. this.renderList.reset();
  26394. };
  26395. BoundingBoxRenderer.prototype.render = function () {
  26396. if (this.renderList.length === 0) {
  26397. return;
  26398. }
  26399. this._prepareRessources();
  26400. if (!this._colorShader.isReady()) {
  26401. return;
  26402. }
  26403. var engine = this._scene.getEngine();
  26404. engine.setDepthWrite(false);
  26405. this._colorShader._preBind();
  26406. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26407. var boundingBox = this.renderList.data[boundingBoxIndex];
  26408. var min = boundingBox.minimum;
  26409. var max = boundingBox.maximum;
  26410. var diff = max.subtract(min);
  26411. var median = min.add(diff.scale(0.5));
  26412. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26413. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26414. .multiply(boundingBox.getWorldMatrix());
  26415. // VBOs
  26416. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26417. if (this.showBackLines) {
  26418. // Back
  26419. engine.setDepthFunctionToGreaterOrEqual();
  26420. this._scene.resetCachedMaterial();
  26421. this._colorShader.setColor4("color", this.backColor.toColor4());
  26422. this._colorShader.bind(worldMatrix);
  26423. // Draw order
  26424. engine.draw(false, 0, 24);
  26425. }
  26426. // Front
  26427. engine.setDepthFunctionToLess();
  26428. this._scene.resetCachedMaterial();
  26429. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26430. this._colorShader.bind(worldMatrix);
  26431. // Draw order
  26432. engine.draw(false, 0, 24);
  26433. }
  26434. this._colorShader.unbind();
  26435. engine.setDepthFunctionToLessOrEqual();
  26436. engine.setDepthWrite(true);
  26437. };
  26438. BoundingBoxRenderer.prototype.dispose = function () {
  26439. if (!this._colorShader) {
  26440. return;
  26441. }
  26442. this._colorShader.dispose();
  26443. this._vb.dispose();
  26444. this._scene.getEngine()._releaseBuffer(this._ib);
  26445. };
  26446. return BoundingBoxRenderer;
  26447. })();
  26448. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26449. })(BABYLON || (BABYLON = {}));
  26450. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26451. var BABYLON;
  26452. (function (BABYLON) {
  26453. var Condition = (function () {
  26454. function Condition(actionManager) {
  26455. this._actionManager = actionManager;
  26456. }
  26457. Condition.prototype.isValid = function () {
  26458. return true;
  26459. };
  26460. Condition.prototype._getProperty = function (propertyPath) {
  26461. return this._actionManager._getProperty(propertyPath);
  26462. };
  26463. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26464. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26465. };
  26466. return Condition;
  26467. })();
  26468. BABYLON.Condition = Condition;
  26469. var ValueCondition = (function (_super) {
  26470. __extends(ValueCondition, _super);
  26471. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26472. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26473. _super.call(this, actionManager);
  26474. this.propertyPath = propertyPath;
  26475. this.value = value;
  26476. this.operator = operator;
  26477. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26478. this._property = this._getProperty(this.propertyPath);
  26479. }
  26480. Object.defineProperty(ValueCondition, "IsEqual", {
  26481. get: function () {
  26482. return ValueCondition._IsEqual;
  26483. },
  26484. enumerable: true,
  26485. configurable: true
  26486. });
  26487. Object.defineProperty(ValueCondition, "IsDifferent", {
  26488. get: function () {
  26489. return ValueCondition._IsDifferent;
  26490. },
  26491. enumerable: true,
  26492. configurable: true
  26493. });
  26494. Object.defineProperty(ValueCondition, "IsGreater", {
  26495. get: function () {
  26496. return ValueCondition._IsGreater;
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. Object.defineProperty(ValueCondition, "IsLesser", {
  26502. get: function () {
  26503. return ValueCondition._IsLesser;
  26504. },
  26505. enumerable: true,
  26506. configurable: true
  26507. });
  26508. // Methods
  26509. ValueCondition.prototype.isValid = function () {
  26510. switch (this.operator) {
  26511. case ValueCondition.IsGreater:
  26512. return this._target[this._property] > this.value;
  26513. case ValueCondition.IsLesser:
  26514. return this._target[this._property] < this.value;
  26515. case ValueCondition.IsEqual:
  26516. case ValueCondition.IsDifferent:
  26517. var check;
  26518. if (this.value.equals) {
  26519. check = this.value.equals(this._target[this._property]);
  26520. }
  26521. else {
  26522. check = this.value === this._target[this._property];
  26523. }
  26524. return this.operator === ValueCondition.IsEqual ? check : !check;
  26525. }
  26526. return false;
  26527. };
  26528. // Statics
  26529. ValueCondition._IsEqual = 0;
  26530. ValueCondition._IsDifferent = 1;
  26531. ValueCondition._IsGreater = 2;
  26532. ValueCondition._IsLesser = 3;
  26533. return ValueCondition;
  26534. })(Condition);
  26535. BABYLON.ValueCondition = ValueCondition;
  26536. var PredicateCondition = (function (_super) {
  26537. __extends(PredicateCondition, _super);
  26538. function PredicateCondition(actionManager, predicate) {
  26539. _super.call(this, actionManager);
  26540. this.predicate = predicate;
  26541. }
  26542. PredicateCondition.prototype.isValid = function () {
  26543. return this.predicate();
  26544. };
  26545. return PredicateCondition;
  26546. })(Condition);
  26547. BABYLON.PredicateCondition = PredicateCondition;
  26548. var StateCondition = (function (_super) {
  26549. __extends(StateCondition, _super);
  26550. function StateCondition(actionManager, target, value) {
  26551. _super.call(this, actionManager);
  26552. this.value = value;
  26553. this._target = target;
  26554. }
  26555. // Methods
  26556. StateCondition.prototype.isValid = function () {
  26557. return this._target.state === this.value;
  26558. };
  26559. return StateCondition;
  26560. })(Condition);
  26561. BABYLON.StateCondition = StateCondition;
  26562. })(BABYLON || (BABYLON = {}));
  26563. //# sourceMappingURL=babylon.condition.js.map
  26564. var BABYLON;
  26565. (function (BABYLON) {
  26566. var Action = (function () {
  26567. function Action(triggerOptions, condition) {
  26568. this.triggerOptions = triggerOptions;
  26569. if (triggerOptions.parameter) {
  26570. this.trigger = triggerOptions.trigger;
  26571. this._triggerParameter = triggerOptions.parameter;
  26572. }
  26573. else {
  26574. this.trigger = triggerOptions;
  26575. }
  26576. this._nextActiveAction = this;
  26577. this._condition = condition;
  26578. }
  26579. // Methods
  26580. Action.prototype._prepare = function () {
  26581. };
  26582. Action.prototype.getTriggerParameter = function () {
  26583. return this._triggerParameter;
  26584. };
  26585. Action.prototype._executeCurrent = function (evt) {
  26586. if (this._nextActiveAction._condition) {
  26587. var condition = this._nextActiveAction._condition;
  26588. var currentRenderId = this._actionManager.getScene().getRenderId();
  26589. // We cache the current evaluation for the current frame
  26590. if (condition._evaluationId === currentRenderId) {
  26591. if (!condition._currentResult) {
  26592. return;
  26593. }
  26594. }
  26595. else {
  26596. condition._evaluationId = currentRenderId;
  26597. if (!condition.isValid()) {
  26598. condition._currentResult = false;
  26599. return;
  26600. }
  26601. condition._currentResult = true;
  26602. }
  26603. }
  26604. this._nextActiveAction.execute(evt);
  26605. if (this._nextActiveAction._child) {
  26606. if (!this._nextActiveAction._child._actionManager) {
  26607. this._nextActiveAction._child._actionManager = this._actionManager;
  26608. }
  26609. this._nextActiveAction = this._nextActiveAction._child;
  26610. }
  26611. else {
  26612. this._nextActiveAction = this;
  26613. }
  26614. };
  26615. Action.prototype.execute = function (evt) {
  26616. };
  26617. Action.prototype.then = function (action) {
  26618. this._child = action;
  26619. action._actionManager = this._actionManager;
  26620. action._prepare();
  26621. return action;
  26622. };
  26623. Action.prototype._getProperty = function (propertyPath) {
  26624. return this._actionManager._getProperty(propertyPath);
  26625. };
  26626. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26627. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26628. };
  26629. return Action;
  26630. })();
  26631. BABYLON.Action = Action;
  26632. })(BABYLON || (BABYLON = {}));
  26633. //# sourceMappingURL=babylon.action.js.map
  26634. var BABYLON;
  26635. (function (BABYLON) {
  26636. /**
  26637. * ActionEvent is the event beint sent when an action is triggered.
  26638. */
  26639. var ActionEvent = (function () {
  26640. /**
  26641. * @constructor
  26642. * @param source The mesh that triggered the action.
  26643. * @param pointerX the X mouse cursor position at the time of the event
  26644. * @param pointerY the Y mouse cursor position at the time of the event
  26645. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26646. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26647. */
  26648. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26649. this.source = source;
  26650. this.pointerX = pointerX;
  26651. this.pointerY = pointerY;
  26652. this.meshUnderPointer = meshUnderPointer;
  26653. this.sourceEvent = sourceEvent;
  26654. }
  26655. /**
  26656. * Helper function to auto-create an ActionEvent from a source mesh.
  26657. * @param source the source mesh that triggered the event
  26658. * @param evt {Event} The original (browser) event
  26659. */
  26660. ActionEvent.CreateNew = function (source, evt) {
  26661. var scene = source.getScene();
  26662. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26663. };
  26664. /**
  26665. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26666. * @param scene the scene where the event occurred
  26667. * @param evt {Event} The original (browser) event
  26668. */
  26669. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26670. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26671. };
  26672. return ActionEvent;
  26673. })();
  26674. BABYLON.ActionEvent = ActionEvent;
  26675. /**
  26676. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26677. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26678. */
  26679. var ActionManager = (function () {
  26680. function ActionManager(scene) {
  26681. // Members
  26682. this.actions = new Array();
  26683. this._scene = scene;
  26684. scene._actionManagers.push(this);
  26685. }
  26686. Object.defineProperty(ActionManager, "NothingTrigger", {
  26687. get: function () {
  26688. return ActionManager._NothingTrigger;
  26689. },
  26690. enumerable: true,
  26691. configurable: true
  26692. });
  26693. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26694. get: function () {
  26695. return ActionManager._OnPickTrigger;
  26696. },
  26697. enumerable: true,
  26698. configurable: true
  26699. });
  26700. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26701. get: function () {
  26702. return ActionManager._OnLeftPickTrigger;
  26703. },
  26704. enumerable: true,
  26705. configurable: true
  26706. });
  26707. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26708. get: function () {
  26709. return ActionManager._OnRightPickTrigger;
  26710. },
  26711. enumerable: true,
  26712. configurable: true
  26713. });
  26714. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26715. get: function () {
  26716. return ActionManager._OnCenterPickTrigger;
  26717. },
  26718. enumerable: true,
  26719. configurable: true
  26720. });
  26721. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26722. get: function () {
  26723. return ActionManager._OnPointerOverTrigger;
  26724. },
  26725. enumerable: true,
  26726. configurable: true
  26727. });
  26728. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26729. get: function () {
  26730. return ActionManager._OnPointerOutTrigger;
  26731. },
  26732. enumerable: true,
  26733. configurable: true
  26734. });
  26735. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26736. get: function () {
  26737. return ActionManager._OnEveryFrameTrigger;
  26738. },
  26739. enumerable: true,
  26740. configurable: true
  26741. });
  26742. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26743. get: function () {
  26744. return ActionManager._OnIntersectionEnterTrigger;
  26745. },
  26746. enumerable: true,
  26747. configurable: true
  26748. });
  26749. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26750. get: function () {
  26751. return ActionManager._OnIntersectionExitTrigger;
  26752. },
  26753. enumerable: true,
  26754. configurable: true
  26755. });
  26756. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26757. get: function () {
  26758. return ActionManager._OnKeyDownTrigger;
  26759. },
  26760. enumerable: true,
  26761. configurable: true
  26762. });
  26763. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26764. get: function () {
  26765. return ActionManager._OnKeyUpTrigger;
  26766. },
  26767. enumerable: true,
  26768. configurable: true
  26769. });
  26770. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26771. get: function () {
  26772. return ActionManager._OnPickUpTrigger;
  26773. },
  26774. enumerable: true,
  26775. configurable: true
  26776. });
  26777. // Methods
  26778. ActionManager.prototype.dispose = function () {
  26779. var index = this._scene._actionManagers.indexOf(this);
  26780. if (index > -1) {
  26781. this._scene._actionManagers.splice(index, 1);
  26782. }
  26783. };
  26784. ActionManager.prototype.getScene = function () {
  26785. return this._scene;
  26786. };
  26787. /**
  26788. * Does this action manager handles actions of any of the given triggers
  26789. * @param {number[]} triggers - the triggers to be tested
  26790. * @return {boolean} whether one (or more) of the triggers is handeled
  26791. */
  26792. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26793. for (var index = 0; index < this.actions.length; index++) {
  26794. var action = this.actions[index];
  26795. if (triggers.indexOf(action.trigger) > -1) {
  26796. return true;
  26797. }
  26798. }
  26799. return false;
  26800. };
  26801. /**
  26802. * Does this action manager handles actions of a given trigger
  26803. * @param {number} trigger - the trigger to be tested
  26804. * @return {boolean} whether the trigger is handeled
  26805. */
  26806. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26807. for (var index = 0; index < this.actions.length; index++) {
  26808. var action = this.actions[index];
  26809. if (action.trigger === trigger) {
  26810. return true;
  26811. }
  26812. }
  26813. return false;
  26814. };
  26815. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26816. /**
  26817. * Does this action manager has pointer triggers
  26818. * @return {boolean} whether or not it has pointer triggers
  26819. */
  26820. get: function () {
  26821. for (var index = 0; index < this.actions.length; index++) {
  26822. var action = this.actions[index];
  26823. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26824. return true;
  26825. }
  26826. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26827. return true;
  26828. }
  26829. }
  26830. return false;
  26831. },
  26832. enumerable: true,
  26833. configurable: true
  26834. });
  26835. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26836. /**
  26837. * Does this action manager has pick triggers
  26838. * @return {boolean} whether or not it has pick triggers
  26839. */
  26840. get: function () {
  26841. for (var index = 0; index < this.actions.length; index++) {
  26842. var action = this.actions[index];
  26843. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26844. return true;
  26845. }
  26846. }
  26847. return false;
  26848. },
  26849. enumerable: true,
  26850. configurable: true
  26851. });
  26852. /**
  26853. * Registers an action to this action manager
  26854. * @param {BABYLON.Action} action - the action to be registered
  26855. * @return {BABYLON.Action} the action amended (prepared) after registration
  26856. */
  26857. ActionManager.prototype.registerAction = function (action) {
  26858. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26859. if (this.getScene().actionManager !== this) {
  26860. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26861. return null;
  26862. }
  26863. }
  26864. this.actions.push(action);
  26865. action._actionManager = this;
  26866. action._prepare();
  26867. return action;
  26868. };
  26869. /**
  26870. * Process a specific trigger
  26871. * @param {number} trigger - the trigger to process
  26872. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26873. */
  26874. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26875. for (var index = 0; index < this.actions.length; index++) {
  26876. var action = this.actions[index];
  26877. if (action.trigger === trigger) {
  26878. if (trigger === ActionManager.OnKeyUpTrigger
  26879. || trigger === ActionManager.OnKeyDownTrigger) {
  26880. var parameter = action.getTriggerParameter();
  26881. if (parameter) {
  26882. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26883. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26884. if (actualkey !== parameter.toLowerCase()) {
  26885. continue;
  26886. }
  26887. }
  26888. }
  26889. action._executeCurrent(evt);
  26890. }
  26891. }
  26892. };
  26893. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26894. var properties = propertyPath.split(".");
  26895. for (var index = 0; index < properties.length - 1; index++) {
  26896. target = target[properties[index]];
  26897. }
  26898. return target;
  26899. };
  26900. ActionManager.prototype._getProperty = function (propertyPath) {
  26901. var properties = propertyPath.split(".");
  26902. return properties[properties.length - 1];
  26903. };
  26904. // Statics
  26905. ActionManager._NothingTrigger = 0;
  26906. ActionManager._OnPickTrigger = 1;
  26907. ActionManager._OnLeftPickTrigger = 2;
  26908. ActionManager._OnRightPickTrigger = 3;
  26909. ActionManager._OnCenterPickTrigger = 4;
  26910. ActionManager._OnPointerOverTrigger = 5;
  26911. ActionManager._OnPointerOutTrigger = 6;
  26912. ActionManager._OnEveryFrameTrigger = 7;
  26913. ActionManager._OnIntersectionEnterTrigger = 8;
  26914. ActionManager._OnIntersectionExitTrigger = 9;
  26915. ActionManager._OnKeyDownTrigger = 10;
  26916. ActionManager._OnKeyUpTrigger = 11;
  26917. ActionManager._OnPickUpTrigger = 12;
  26918. return ActionManager;
  26919. })();
  26920. BABYLON.ActionManager = ActionManager;
  26921. })(BABYLON || (BABYLON = {}));
  26922. //# sourceMappingURL=babylon.actionManager.js.map
  26923. var BABYLON;
  26924. (function (BABYLON) {
  26925. var InterpolateValueAction = (function (_super) {
  26926. __extends(InterpolateValueAction, _super);
  26927. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26928. if (duration === void 0) { duration = 1000; }
  26929. _super.call(this, triggerOptions, condition);
  26930. this.propertyPath = propertyPath;
  26931. this.value = value;
  26932. this.duration = duration;
  26933. this.stopOtherAnimations = stopOtherAnimations;
  26934. this._target = target;
  26935. }
  26936. InterpolateValueAction.prototype._prepare = function () {
  26937. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26938. this._property = this._getProperty(this.propertyPath);
  26939. };
  26940. InterpolateValueAction.prototype.execute = function () {
  26941. var scene = this._actionManager.getScene();
  26942. var keys = [
  26943. {
  26944. frame: 0,
  26945. value: this._target[this._property]
  26946. }, {
  26947. frame: 100,
  26948. value: this.value
  26949. }
  26950. ];
  26951. var dataType;
  26952. if (typeof this.value === "number") {
  26953. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26954. }
  26955. else if (this.value instanceof BABYLON.Color3) {
  26956. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26957. }
  26958. else if (this.value instanceof BABYLON.Vector3) {
  26959. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26960. }
  26961. else if (this.value instanceof BABYLON.Matrix) {
  26962. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26963. }
  26964. else if (this.value instanceof BABYLON.Quaternion) {
  26965. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26966. }
  26967. else {
  26968. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26969. return;
  26970. }
  26971. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26972. animation.setKeys(keys);
  26973. if (this.stopOtherAnimations) {
  26974. scene.stopAnimation(this._target);
  26975. }
  26976. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26977. };
  26978. return InterpolateValueAction;
  26979. })(BABYLON.Action);
  26980. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26981. })(BABYLON || (BABYLON = {}));
  26982. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26983. var BABYLON;
  26984. (function (BABYLON) {
  26985. var SwitchBooleanAction = (function (_super) {
  26986. __extends(SwitchBooleanAction, _super);
  26987. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26988. _super.call(this, triggerOptions, condition);
  26989. this.propertyPath = propertyPath;
  26990. this._target = target;
  26991. }
  26992. SwitchBooleanAction.prototype._prepare = function () {
  26993. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26994. this._property = this._getProperty(this.propertyPath);
  26995. };
  26996. SwitchBooleanAction.prototype.execute = function () {
  26997. this._target[this._property] = !this._target[this._property];
  26998. };
  26999. return SwitchBooleanAction;
  27000. })(BABYLON.Action);
  27001. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27002. var SetStateAction = (function (_super) {
  27003. __extends(SetStateAction, _super);
  27004. function SetStateAction(triggerOptions, target, value, condition) {
  27005. _super.call(this, triggerOptions, condition);
  27006. this.value = value;
  27007. this._target = target;
  27008. }
  27009. SetStateAction.prototype.execute = function () {
  27010. this._target.state = this.value;
  27011. };
  27012. return SetStateAction;
  27013. })(BABYLON.Action);
  27014. BABYLON.SetStateAction = SetStateAction;
  27015. var SetValueAction = (function (_super) {
  27016. __extends(SetValueAction, _super);
  27017. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27018. _super.call(this, triggerOptions, condition);
  27019. this.propertyPath = propertyPath;
  27020. this.value = value;
  27021. this._target = target;
  27022. }
  27023. SetValueAction.prototype._prepare = function () {
  27024. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27025. this._property = this._getProperty(this.propertyPath);
  27026. };
  27027. SetValueAction.prototype.execute = function () {
  27028. this._target[this._property] = this.value;
  27029. };
  27030. return SetValueAction;
  27031. })(BABYLON.Action);
  27032. BABYLON.SetValueAction = SetValueAction;
  27033. var IncrementValueAction = (function (_super) {
  27034. __extends(IncrementValueAction, _super);
  27035. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27036. _super.call(this, triggerOptions, condition);
  27037. this.propertyPath = propertyPath;
  27038. this.value = value;
  27039. this._target = target;
  27040. }
  27041. IncrementValueAction.prototype._prepare = function () {
  27042. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27043. this._property = this._getProperty(this.propertyPath);
  27044. if (typeof this._target[this._property] !== "number") {
  27045. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27046. }
  27047. };
  27048. IncrementValueAction.prototype.execute = function () {
  27049. this._target[this._property] += this.value;
  27050. };
  27051. return IncrementValueAction;
  27052. })(BABYLON.Action);
  27053. BABYLON.IncrementValueAction = IncrementValueAction;
  27054. var PlayAnimationAction = (function (_super) {
  27055. __extends(PlayAnimationAction, _super);
  27056. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27057. _super.call(this, triggerOptions, condition);
  27058. this.from = from;
  27059. this.to = to;
  27060. this.loop = loop;
  27061. this._target = target;
  27062. }
  27063. PlayAnimationAction.prototype._prepare = function () {
  27064. };
  27065. PlayAnimationAction.prototype.execute = function () {
  27066. var scene = this._actionManager.getScene();
  27067. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27068. };
  27069. return PlayAnimationAction;
  27070. })(BABYLON.Action);
  27071. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27072. var StopAnimationAction = (function (_super) {
  27073. __extends(StopAnimationAction, _super);
  27074. function StopAnimationAction(triggerOptions, target, condition) {
  27075. _super.call(this, triggerOptions, condition);
  27076. this._target = target;
  27077. }
  27078. StopAnimationAction.prototype._prepare = function () {
  27079. };
  27080. StopAnimationAction.prototype.execute = function () {
  27081. var scene = this._actionManager.getScene();
  27082. scene.stopAnimation(this._target);
  27083. };
  27084. return StopAnimationAction;
  27085. })(BABYLON.Action);
  27086. BABYLON.StopAnimationAction = StopAnimationAction;
  27087. var DoNothingAction = (function (_super) {
  27088. __extends(DoNothingAction, _super);
  27089. function DoNothingAction(triggerOptions, condition) {
  27090. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27091. _super.call(this, triggerOptions, condition);
  27092. }
  27093. DoNothingAction.prototype.execute = function () {
  27094. };
  27095. return DoNothingAction;
  27096. })(BABYLON.Action);
  27097. BABYLON.DoNothingAction = DoNothingAction;
  27098. var CombineAction = (function (_super) {
  27099. __extends(CombineAction, _super);
  27100. function CombineAction(triggerOptions, children, condition) {
  27101. _super.call(this, triggerOptions, condition);
  27102. this.children = children;
  27103. }
  27104. CombineAction.prototype._prepare = function () {
  27105. for (var index = 0; index < this.children.length; index++) {
  27106. this.children[index]._actionManager = this._actionManager;
  27107. this.children[index]._prepare();
  27108. }
  27109. };
  27110. CombineAction.prototype.execute = function (evt) {
  27111. for (var index = 0; index < this.children.length; index++) {
  27112. this.children[index].execute(evt);
  27113. }
  27114. };
  27115. return CombineAction;
  27116. })(BABYLON.Action);
  27117. BABYLON.CombineAction = CombineAction;
  27118. var ExecuteCodeAction = (function (_super) {
  27119. __extends(ExecuteCodeAction, _super);
  27120. function ExecuteCodeAction(triggerOptions, func, condition) {
  27121. _super.call(this, triggerOptions, condition);
  27122. this.func = func;
  27123. }
  27124. ExecuteCodeAction.prototype.execute = function (evt) {
  27125. this.func(evt);
  27126. };
  27127. return ExecuteCodeAction;
  27128. })(BABYLON.Action);
  27129. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27130. var SetParentAction = (function (_super) {
  27131. __extends(SetParentAction, _super);
  27132. function SetParentAction(triggerOptions, target, parent, condition) {
  27133. _super.call(this, triggerOptions, condition);
  27134. this._target = target;
  27135. this._parent = parent;
  27136. }
  27137. SetParentAction.prototype._prepare = function () {
  27138. };
  27139. SetParentAction.prototype.execute = function () {
  27140. if (this._target.parent === this._parent) {
  27141. return;
  27142. }
  27143. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27144. invertParentWorldMatrix.invert();
  27145. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27146. this._target.parent = this._parent;
  27147. };
  27148. return SetParentAction;
  27149. })(BABYLON.Action);
  27150. BABYLON.SetParentAction = SetParentAction;
  27151. var PlaySoundAction = (function (_super) {
  27152. __extends(PlaySoundAction, _super);
  27153. function PlaySoundAction(triggerOptions, sound, condition) {
  27154. _super.call(this, triggerOptions, condition);
  27155. this._sound = sound;
  27156. }
  27157. PlaySoundAction.prototype._prepare = function () {
  27158. };
  27159. PlaySoundAction.prototype.execute = function () {
  27160. if (this._sound !== undefined)
  27161. this._sound.play();
  27162. };
  27163. return PlaySoundAction;
  27164. })(BABYLON.Action);
  27165. BABYLON.PlaySoundAction = PlaySoundAction;
  27166. var StopSoundAction = (function (_super) {
  27167. __extends(StopSoundAction, _super);
  27168. function StopSoundAction(triggerOptions, sound, condition) {
  27169. _super.call(this, triggerOptions, condition);
  27170. this._sound = sound;
  27171. }
  27172. StopSoundAction.prototype._prepare = function () {
  27173. };
  27174. StopSoundAction.prototype.execute = function () {
  27175. if (this._sound !== undefined)
  27176. this._sound.stop();
  27177. };
  27178. return StopSoundAction;
  27179. })(BABYLON.Action);
  27180. BABYLON.StopSoundAction = StopSoundAction;
  27181. })(BABYLON || (BABYLON = {}));
  27182. //# sourceMappingURL=babylon.directActions.js.map
  27183. var BABYLON;
  27184. (function (BABYLON) {
  27185. var Geometry = (function () {
  27186. function Geometry(id, scene, vertexData, updatable, mesh) {
  27187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27188. this._totalVertices = 0;
  27189. this._indices = [];
  27190. this._isDisposed = false;
  27191. this.id = id;
  27192. this._engine = scene.getEngine();
  27193. this._meshes = [];
  27194. this._scene = scene;
  27195. // vertexData
  27196. if (vertexData) {
  27197. this.setAllVerticesData(vertexData, updatable);
  27198. }
  27199. else {
  27200. this._totalVertices = 0;
  27201. this._indices = [];
  27202. }
  27203. // applyToMesh
  27204. if (mesh) {
  27205. this.applyToMesh(mesh);
  27206. mesh.computeWorldMatrix(true);
  27207. }
  27208. }
  27209. Geometry.prototype.getScene = function () {
  27210. return this._scene;
  27211. };
  27212. Geometry.prototype.getEngine = function () {
  27213. return this._engine;
  27214. };
  27215. Geometry.prototype.isReady = function () {
  27216. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27217. };
  27218. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27219. vertexData.applyToGeometry(this, updatable);
  27220. this.notifyUpdate();
  27221. };
  27222. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27223. this._vertexBuffers = this._vertexBuffers || {};
  27224. if (this._vertexBuffers[kind]) {
  27225. this._vertexBuffers[kind].dispose();
  27226. }
  27227. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27228. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27229. stride = this._vertexBuffers[kind].getStrideSize();
  27230. this._totalVertices = data.length / stride;
  27231. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27232. var meshes = this._meshes;
  27233. var numOfMeshes = meshes.length;
  27234. for (var index = 0; index < numOfMeshes; index++) {
  27235. var mesh = meshes[index];
  27236. mesh._resetPointsArrayCache();
  27237. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27238. mesh._createGlobalSubMesh();
  27239. mesh.computeWorldMatrix(true);
  27240. }
  27241. }
  27242. this.notifyUpdate(kind);
  27243. };
  27244. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27245. var vertexBuffer = this.getVertexBuffer(kind);
  27246. if (!vertexBuffer) {
  27247. return;
  27248. }
  27249. vertexBuffer.updateDirectly(data, offset);
  27250. this.notifyUpdate(kind);
  27251. };
  27252. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27253. var vertexBuffer = this.getVertexBuffer(kind);
  27254. if (!vertexBuffer) {
  27255. return;
  27256. }
  27257. vertexBuffer.update(data);
  27258. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27259. var extend;
  27260. var stride = vertexBuffer.getStrideSize();
  27261. this._totalVertices = data.length / stride;
  27262. if (updateExtends) {
  27263. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27264. }
  27265. var meshes = this._meshes;
  27266. var numOfMeshes = meshes.length;
  27267. for (var index = 0; index < numOfMeshes; index++) {
  27268. var mesh = meshes[index];
  27269. mesh._resetPointsArrayCache();
  27270. if (updateExtends) {
  27271. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27272. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27273. var subMesh = mesh.subMeshes[subIndex];
  27274. subMesh.refreshBoundingInfo();
  27275. }
  27276. }
  27277. }
  27278. }
  27279. this.notifyUpdate(kind);
  27280. };
  27281. Geometry.prototype.getTotalVertices = function () {
  27282. if (!this.isReady()) {
  27283. return 0;
  27284. }
  27285. return this._totalVertices;
  27286. };
  27287. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27288. var vertexBuffer = this.getVertexBuffer(kind);
  27289. if (!vertexBuffer) {
  27290. return null;
  27291. }
  27292. var orig = vertexBuffer.getData();
  27293. if (!copyWhenShared || this._meshes.length === 1) {
  27294. return orig;
  27295. }
  27296. else {
  27297. var len = orig.length;
  27298. var copy = [];
  27299. for (var i = 0; i < len; i++) {
  27300. copy.push(orig[i]);
  27301. }
  27302. return copy;
  27303. }
  27304. };
  27305. Geometry.prototype.getVertexBuffer = function (kind) {
  27306. if (!this.isReady()) {
  27307. return null;
  27308. }
  27309. return this._vertexBuffers[kind];
  27310. };
  27311. Geometry.prototype.getVertexBuffers = function () {
  27312. if (!this.isReady()) {
  27313. return null;
  27314. }
  27315. return this._vertexBuffers;
  27316. };
  27317. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27318. if (!this._vertexBuffers) {
  27319. if (this._delayInfo) {
  27320. return this._delayInfo.indexOf(kind) !== -1;
  27321. }
  27322. return false;
  27323. }
  27324. return this._vertexBuffers[kind] !== undefined;
  27325. };
  27326. Geometry.prototype.getVerticesDataKinds = function () {
  27327. var result = [];
  27328. if (!this._vertexBuffers && this._delayInfo) {
  27329. for (var kind in this._delayInfo) {
  27330. result.push(kind);
  27331. }
  27332. }
  27333. else {
  27334. for (kind in this._vertexBuffers) {
  27335. result.push(kind);
  27336. }
  27337. }
  27338. return result;
  27339. };
  27340. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27341. if (this._indexBuffer) {
  27342. this._engine._releaseBuffer(this._indexBuffer);
  27343. }
  27344. this._indices = indices;
  27345. if (this._meshes.length !== 0 && this._indices) {
  27346. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27347. }
  27348. if (totalVertices !== undefined) {
  27349. this._totalVertices = totalVertices;
  27350. }
  27351. var meshes = this._meshes;
  27352. var numOfMeshes = meshes.length;
  27353. for (var index = 0; index < numOfMeshes; index++) {
  27354. meshes[index]._createGlobalSubMesh();
  27355. }
  27356. this.notifyUpdate();
  27357. };
  27358. Geometry.prototype.getTotalIndices = function () {
  27359. if (!this.isReady()) {
  27360. return 0;
  27361. }
  27362. return this._indices.length;
  27363. };
  27364. Geometry.prototype.getIndices = function (copyWhenShared) {
  27365. if (!this.isReady()) {
  27366. return null;
  27367. }
  27368. var orig = this._indices;
  27369. if (!copyWhenShared || this._meshes.length === 1) {
  27370. return orig;
  27371. }
  27372. else {
  27373. var len = orig.length;
  27374. var copy = [];
  27375. for (var i = 0; i < len; i++) {
  27376. copy.push(orig[i]);
  27377. }
  27378. return copy;
  27379. }
  27380. };
  27381. Geometry.prototype.getIndexBuffer = function () {
  27382. if (!this.isReady()) {
  27383. return null;
  27384. }
  27385. return this._indexBuffer;
  27386. };
  27387. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27388. var meshes = this._meshes;
  27389. var index = meshes.indexOf(mesh);
  27390. if (index === -1) {
  27391. return;
  27392. }
  27393. for (var kind in this._vertexBuffers) {
  27394. this._vertexBuffers[kind].dispose();
  27395. }
  27396. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27397. this._indexBuffer = null;
  27398. }
  27399. meshes.splice(index, 1);
  27400. mesh._geometry = null;
  27401. if (meshes.length === 0 && shouldDispose) {
  27402. this.dispose();
  27403. }
  27404. };
  27405. Geometry.prototype.applyToMesh = function (mesh) {
  27406. if (mesh._geometry === this) {
  27407. return;
  27408. }
  27409. var previousGeometry = mesh._geometry;
  27410. if (previousGeometry) {
  27411. previousGeometry.releaseForMesh(mesh);
  27412. }
  27413. var meshes = this._meshes;
  27414. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27415. mesh._geometry = this;
  27416. this._scene.pushGeometry(this);
  27417. meshes.push(mesh);
  27418. if (this.isReady()) {
  27419. this._applyToMesh(mesh);
  27420. }
  27421. else {
  27422. mesh._boundingInfo = this._boundingInfo;
  27423. }
  27424. };
  27425. Geometry.prototype._applyToMesh = function (mesh) {
  27426. var numOfMeshes = this._meshes.length;
  27427. // vertexBuffers
  27428. for (var kind in this._vertexBuffers) {
  27429. if (numOfMeshes === 1) {
  27430. this._vertexBuffers[kind].create();
  27431. }
  27432. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27434. mesh._resetPointsArrayCache();
  27435. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27436. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27437. mesh._createGlobalSubMesh();
  27438. //bounding info was just created again, world matrix should be applied again.
  27439. mesh._updateBoundingInfo();
  27440. }
  27441. }
  27442. // indexBuffer
  27443. if (numOfMeshes === 1 && this._indices) {
  27444. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27445. }
  27446. if (this._indexBuffer) {
  27447. this._indexBuffer.references = numOfMeshes;
  27448. }
  27449. };
  27450. Geometry.prototype.notifyUpdate = function (kind) {
  27451. if (this.onGeometryUpdated) {
  27452. this.onGeometryUpdated(this, kind);
  27453. }
  27454. };
  27455. Geometry.prototype.load = function (scene, onLoaded) {
  27456. var _this = this;
  27457. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27458. return;
  27459. }
  27460. if (this.isReady()) {
  27461. if (onLoaded) {
  27462. onLoaded();
  27463. }
  27464. return;
  27465. }
  27466. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27467. scene._addPendingData(this);
  27468. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27469. _this._delayLoadingFunction(JSON.parse(data), _this);
  27470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27471. _this._delayInfo = [];
  27472. scene._removePendingData(_this);
  27473. var meshes = _this._meshes;
  27474. var numOfMeshes = meshes.length;
  27475. for (var index = 0; index < numOfMeshes; index++) {
  27476. _this._applyToMesh(meshes[index]);
  27477. }
  27478. if (onLoaded) {
  27479. onLoaded();
  27480. }
  27481. }, function () { }, scene.database);
  27482. };
  27483. Geometry.prototype.isDisposed = function () {
  27484. return this._isDisposed;
  27485. };
  27486. Geometry.prototype.dispose = function () {
  27487. var meshes = this._meshes;
  27488. var numOfMeshes = meshes.length;
  27489. var index;
  27490. for (index = 0; index < numOfMeshes; index++) {
  27491. this.releaseForMesh(meshes[index]);
  27492. }
  27493. this._meshes = [];
  27494. for (var kind in this._vertexBuffers) {
  27495. this._vertexBuffers[kind].dispose();
  27496. }
  27497. this._vertexBuffers = [];
  27498. this._totalVertices = 0;
  27499. if (this._indexBuffer) {
  27500. this._engine._releaseBuffer(this._indexBuffer);
  27501. }
  27502. this._indexBuffer = null;
  27503. this._indices = [];
  27504. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27505. this.delayLoadingFile = null;
  27506. this._delayLoadingFunction = null;
  27507. this._delayInfo = [];
  27508. this._boundingInfo = null; // todo: .dispose()
  27509. this._scene.removeGeometry(this);
  27510. this._isDisposed = true;
  27511. };
  27512. Geometry.prototype.copy = function (id) {
  27513. var vertexData = new BABYLON.VertexData();
  27514. vertexData.indices = [];
  27515. var indices = this.getIndices();
  27516. for (var index = 0; index < indices.length; index++) {
  27517. vertexData.indices.push(indices[index]);
  27518. }
  27519. var updatable = false;
  27520. var stopChecking = false;
  27521. for (var kind in this._vertexBuffers) {
  27522. // using slice() to make a copy of the array and not just reference it
  27523. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27524. if (!stopChecking) {
  27525. updatable = this.getVertexBuffer(kind).isUpdatable();
  27526. stopChecking = !updatable;
  27527. }
  27528. }
  27529. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27530. geometry.delayLoadState = this.delayLoadState;
  27531. geometry.delayLoadingFile = this.delayLoadingFile;
  27532. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27533. for (kind in this._delayInfo) {
  27534. geometry._delayInfo = geometry._delayInfo || [];
  27535. geometry._delayInfo.push(kind);
  27536. }
  27537. // Bounding info
  27538. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27539. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27540. return geometry;
  27541. };
  27542. // Statics
  27543. Geometry.ExtractFromMesh = function (mesh, id) {
  27544. var geometry = mesh._geometry;
  27545. if (!geometry) {
  27546. return null;
  27547. }
  27548. return geometry.copy(id);
  27549. };
  27550. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27551. // be aware Math.random() could cause collisions
  27552. Geometry.RandomId = function () {
  27553. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27554. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27555. return v.toString(16);
  27556. });
  27557. };
  27558. return Geometry;
  27559. })();
  27560. BABYLON.Geometry = Geometry;
  27561. /////// Primitives //////////////////////////////////////////////
  27562. var Geometry;
  27563. (function (Geometry) {
  27564. var Primitives;
  27565. (function (Primitives) {
  27566. /// Abstract class
  27567. var _Primitive = (function (_super) {
  27568. __extends(_Primitive, _super);
  27569. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27570. this._beingRegenerated = true;
  27571. this._canBeRegenerated = canBeRegenerated;
  27572. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27573. this._beingRegenerated = false;
  27574. }
  27575. _Primitive.prototype.canBeRegenerated = function () {
  27576. return this._canBeRegenerated;
  27577. };
  27578. _Primitive.prototype.regenerate = function () {
  27579. if (!this._canBeRegenerated) {
  27580. return;
  27581. }
  27582. this._beingRegenerated = true;
  27583. this.setAllVerticesData(this._regenerateVertexData(), false);
  27584. this._beingRegenerated = false;
  27585. };
  27586. _Primitive.prototype.asNewGeometry = function (id) {
  27587. return _super.prototype.copy.call(this, id);
  27588. };
  27589. // overrides
  27590. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27591. if (!this._beingRegenerated) {
  27592. return;
  27593. }
  27594. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27595. };
  27596. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27597. if (!this._beingRegenerated) {
  27598. return;
  27599. }
  27600. _super.prototype.setVerticesData.call(this, kind, data, false);
  27601. };
  27602. // to override
  27603. // protected
  27604. _Primitive.prototype._regenerateVertexData = function () {
  27605. throw new Error("Abstract method");
  27606. };
  27607. _Primitive.prototype.copy = function (id) {
  27608. throw new Error("Must be overriden in sub-classes.");
  27609. };
  27610. return _Primitive;
  27611. })(Geometry);
  27612. Primitives._Primitive = _Primitive;
  27613. var Ribbon = (function (_super) {
  27614. __extends(Ribbon, _super);
  27615. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27617. this.pathArray = pathArray;
  27618. this.closeArray = closeArray;
  27619. this.closePath = closePath;
  27620. this.offset = offset;
  27621. this.side = side;
  27622. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27623. }
  27624. Ribbon.prototype._regenerateVertexData = function () {
  27625. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27626. };
  27627. Ribbon.prototype.copy = function (id) {
  27628. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27629. };
  27630. return Ribbon;
  27631. })(_Primitive);
  27632. Primitives.Ribbon = Ribbon;
  27633. var Box = (function (_super) {
  27634. __extends(Box, _super);
  27635. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27636. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27637. this.size = size;
  27638. this.side = side;
  27639. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27640. }
  27641. Box.prototype._regenerateVertexData = function () {
  27642. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27643. };
  27644. Box.prototype.copy = function (id) {
  27645. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27646. };
  27647. return Box;
  27648. })(_Primitive);
  27649. Primitives.Box = Box;
  27650. var Sphere = (function (_super) {
  27651. __extends(Sphere, _super);
  27652. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27653. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27654. this.segments = segments;
  27655. this.diameter = diameter;
  27656. this.side = side;
  27657. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27658. }
  27659. Sphere.prototype._regenerateVertexData = function () {
  27660. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27661. };
  27662. Sphere.prototype.copy = function (id) {
  27663. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27664. };
  27665. return Sphere;
  27666. })(_Primitive);
  27667. Primitives.Sphere = Sphere;
  27668. var Cylinder = (function (_super) {
  27669. __extends(Cylinder, _super);
  27670. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27671. if (subdivisions === void 0) { subdivisions = 1; }
  27672. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27673. this.height = height;
  27674. this.diameterTop = diameterTop;
  27675. this.diameterBottom = diameterBottom;
  27676. this.tessellation = tessellation;
  27677. this.subdivisions = subdivisions;
  27678. this.side = side;
  27679. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27680. }
  27681. Cylinder.prototype._regenerateVertexData = function () {
  27682. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27683. };
  27684. Cylinder.prototype.copy = function (id) {
  27685. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27686. };
  27687. return Cylinder;
  27688. })(_Primitive);
  27689. Primitives.Cylinder = Cylinder;
  27690. var Torus = (function (_super) {
  27691. __extends(Torus, _super);
  27692. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27693. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27694. this.diameter = diameter;
  27695. this.thickness = thickness;
  27696. this.tessellation = tessellation;
  27697. this.side = side;
  27698. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27699. }
  27700. Torus.prototype._regenerateVertexData = function () {
  27701. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27702. };
  27703. Torus.prototype.copy = function (id) {
  27704. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27705. };
  27706. return Torus;
  27707. })(_Primitive);
  27708. Primitives.Torus = Torus;
  27709. var Ground = (function (_super) {
  27710. __extends(Ground, _super);
  27711. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27712. this.width = width;
  27713. this.height = height;
  27714. this.subdivisions = subdivisions;
  27715. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27716. }
  27717. Ground.prototype._regenerateVertexData = function () {
  27718. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27719. };
  27720. Ground.prototype.copy = function (id) {
  27721. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27722. };
  27723. return Ground;
  27724. })(_Primitive);
  27725. Primitives.Ground = Ground;
  27726. var TiledGround = (function (_super) {
  27727. __extends(TiledGround, _super);
  27728. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27729. this.xmin = xmin;
  27730. this.zmin = zmin;
  27731. this.xmax = xmax;
  27732. this.zmax = zmax;
  27733. this.subdivisions = subdivisions;
  27734. this.precision = precision;
  27735. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27736. }
  27737. TiledGround.prototype._regenerateVertexData = function () {
  27738. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27739. };
  27740. TiledGround.prototype.copy = function (id) {
  27741. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27742. };
  27743. return TiledGround;
  27744. })(_Primitive);
  27745. Primitives.TiledGround = TiledGround;
  27746. var Plane = (function (_super) {
  27747. __extends(Plane, _super);
  27748. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27749. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27750. this.size = size;
  27751. this.side = side;
  27752. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27753. }
  27754. Plane.prototype._regenerateVertexData = function () {
  27755. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27756. };
  27757. Plane.prototype.copy = function (id) {
  27758. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27759. };
  27760. return Plane;
  27761. })(_Primitive);
  27762. Primitives.Plane = Plane;
  27763. var TorusKnot = (function (_super) {
  27764. __extends(TorusKnot, _super);
  27765. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27766. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27767. this.radius = radius;
  27768. this.tube = tube;
  27769. this.radialSegments = radialSegments;
  27770. this.tubularSegments = tubularSegments;
  27771. this.p = p;
  27772. this.q = q;
  27773. this.side = side;
  27774. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27775. }
  27776. TorusKnot.prototype._regenerateVertexData = function () {
  27777. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27778. };
  27779. TorusKnot.prototype.copy = function (id) {
  27780. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27781. };
  27782. return TorusKnot;
  27783. })(_Primitive);
  27784. Primitives.TorusKnot = TorusKnot;
  27785. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27786. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27787. })(BABYLON || (BABYLON = {}));
  27788. //# sourceMappingURL=babylon.geometry.js.map
  27789. var BABYLON;
  27790. (function (BABYLON) {
  27791. var GroundMesh = (function (_super) {
  27792. __extends(GroundMesh, _super);
  27793. function GroundMesh(name, scene) {
  27794. _super.call(this, name, scene);
  27795. this.generateOctree = false;
  27796. this._worldInverse = new BABYLON.Matrix();
  27797. }
  27798. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27799. get: function () {
  27800. return this._subdivisions;
  27801. },
  27802. enumerable: true,
  27803. configurable: true
  27804. });
  27805. GroundMesh.prototype.optimize = function (chunksCount) {
  27806. this.subdivide(this._subdivisions);
  27807. this.createOrUpdateSubmeshesOctree(32);
  27808. };
  27809. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27810. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27811. this.getWorldMatrix().invertToRef(this._worldInverse);
  27812. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27813. var pickInfo = this.intersects(ray);
  27814. if (pickInfo.hit) {
  27815. return pickInfo.pickedPoint.y;
  27816. }
  27817. return 0;
  27818. };
  27819. return GroundMesh;
  27820. })(BABYLON.Mesh);
  27821. BABYLON.GroundMesh = GroundMesh;
  27822. })(BABYLON || (BABYLON = {}));
  27823. //# sourceMappingURL=babylon.groundMesh.js.map
  27824. var BABYLON;
  27825. (function (BABYLON) {
  27826. var LinesMesh = (function (_super) {
  27827. __extends(LinesMesh, _super);
  27828. function LinesMesh(name, scene, updatable) {
  27829. if (updatable === void 0) { updatable = false; }
  27830. _super.call(this, name, scene);
  27831. this.color = new BABYLON.Color3(1, 1, 1);
  27832. this.alpha = 1;
  27833. this._indices = new Array();
  27834. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27835. attributes: ["position"],
  27836. uniforms: ["worldViewProjection", "color"],
  27837. needAlphaBlending: true
  27838. });
  27839. }
  27840. Object.defineProperty(LinesMesh.prototype, "material", {
  27841. get: function () {
  27842. return this._colorShader;
  27843. },
  27844. enumerable: true,
  27845. configurable: true
  27846. });
  27847. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27848. get: function () {
  27849. return false;
  27850. },
  27851. enumerable: true,
  27852. configurable: true
  27853. });
  27854. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27855. get: function () {
  27856. return false;
  27857. },
  27858. enumerable: true,
  27859. configurable: true
  27860. });
  27861. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27862. var engine = this.getScene().getEngine();
  27863. var indexToBind = this._geometry.getIndexBuffer();
  27864. // VBOs
  27865. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27866. // Color
  27867. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27868. };
  27869. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27870. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27871. return;
  27872. }
  27873. var engine = this.getScene().getEngine();
  27874. // Draw order
  27875. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27876. };
  27877. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27878. return null;
  27879. };
  27880. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27881. this._colorShader.dispose();
  27882. _super.prototype.dispose.call(this, doNotRecurse);
  27883. };
  27884. return LinesMesh;
  27885. })(BABYLON.Mesh);
  27886. BABYLON.LinesMesh = LinesMesh;
  27887. })(BABYLON || (BABYLON = {}));
  27888. //# sourceMappingURL=babylon.linesMesh.js.map
  27889. var BABYLON;
  27890. (function (BABYLON) {
  27891. var OutlineRenderer = (function () {
  27892. function OutlineRenderer(scene) {
  27893. this._scene = scene;
  27894. }
  27895. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27896. var _this = this;
  27897. if (useOverlay === void 0) { useOverlay = false; }
  27898. var scene = this._scene;
  27899. var engine = this._scene.getEngine();
  27900. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27901. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27902. return;
  27903. }
  27904. var mesh = subMesh.getRenderingMesh();
  27905. var material = subMesh.getMaterial();
  27906. engine.enableEffect(this._effect);
  27907. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27908. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27909. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27910. // Bones
  27911. if (mesh.useBones) {
  27912. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27913. }
  27914. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27915. // Alpha test
  27916. if (material && material.needAlphaTesting()) {
  27917. var alphaTexture = material.getAlphaTestTexture();
  27918. this._effect.setTexture("diffuseSampler", alphaTexture);
  27919. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27920. }
  27921. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  27922. };
  27923. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27924. var defines = [];
  27925. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27926. var mesh = subMesh.getMesh();
  27927. var material = subMesh.getMaterial();
  27928. // Alpha test
  27929. if (material && material.needAlphaTesting()) {
  27930. defines.push("#define ALPHATEST");
  27931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27932. attribs.push(BABYLON.VertexBuffer.UVKind);
  27933. defines.push("#define UV1");
  27934. }
  27935. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27937. defines.push("#define UV2");
  27938. }
  27939. }
  27940. // Bones
  27941. if (mesh.useBones) {
  27942. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27943. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27944. defines.push("#define BONES");
  27945. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27946. }
  27947. // Instances
  27948. if (useInstances) {
  27949. defines.push("#define INSTANCES");
  27950. attribs.push("world0");
  27951. attribs.push("world1");
  27952. attribs.push("world2");
  27953. attribs.push("world3");
  27954. }
  27955. // Get correct effect
  27956. var join = defines.join("\n");
  27957. if (this._cachedDefines !== join) {
  27958. this._cachedDefines = join;
  27959. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27960. }
  27961. return this._effect.isReady();
  27962. };
  27963. return OutlineRenderer;
  27964. })();
  27965. BABYLON.OutlineRenderer = OutlineRenderer;
  27966. })(BABYLON || (BABYLON = {}));
  27967. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27968. var BABYLON;
  27969. (function (BABYLON) {
  27970. var MeshAssetTask = (function () {
  27971. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27972. this.name = name;
  27973. this.meshesNames = meshesNames;
  27974. this.rootUrl = rootUrl;
  27975. this.sceneFilename = sceneFilename;
  27976. this.isCompleted = false;
  27977. }
  27978. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27979. var _this = this;
  27980. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27981. _this.loadedMeshes = meshes;
  27982. _this.loadedParticleSystems = particleSystems;
  27983. _this.loadedSkeletons = skeletons;
  27984. _this.isCompleted = true;
  27985. if (_this.onSuccess) {
  27986. _this.onSuccess(_this);
  27987. }
  27988. onSuccess();
  27989. }, null, function () {
  27990. if (_this.onError) {
  27991. _this.onError(_this);
  27992. }
  27993. onError();
  27994. });
  27995. };
  27996. return MeshAssetTask;
  27997. })();
  27998. BABYLON.MeshAssetTask = MeshAssetTask;
  27999. var TextFileAssetTask = (function () {
  28000. function TextFileAssetTask(name, url) {
  28001. this.name = name;
  28002. this.url = url;
  28003. this.isCompleted = false;
  28004. }
  28005. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28006. var _this = this;
  28007. BABYLON.Tools.LoadFile(this.url, function (data) {
  28008. _this.text = data;
  28009. _this.isCompleted = true;
  28010. if (_this.onSuccess) {
  28011. _this.onSuccess(_this);
  28012. }
  28013. onSuccess();
  28014. }, null, scene.database, false, function () {
  28015. if (_this.onError) {
  28016. _this.onError(_this);
  28017. }
  28018. onError();
  28019. });
  28020. };
  28021. return TextFileAssetTask;
  28022. })();
  28023. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28024. var BinaryFileAssetTask = (function () {
  28025. function BinaryFileAssetTask(name, url) {
  28026. this.name = name;
  28027. this.url = url;
  28028. this.isCompleted = false;
  28029. }
  28030. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28031. var _this = this;
  28032. BABYLON.Tools.LoadFile(this.url, function (data) {
  28033. _this.data = data;
  28034. _this.isCompleted = true;
  28035. if (_this.onSuccess) {
  28036. _this.onSuccess(_this);
  28037. }
  28038. onSuccess();
  28039. }, null, scene.database, true, function () {
  28040. if (_this.onError) {
  28041. _this.onError(_this);
  28042. }
  28043. onError();
  28044. });
  28045. };
  28046. return BinaryFileAssetTask;
  28047. })();
  28048. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28049. var ImageAssetTask = (function () {
  28050. function ImageAssetTask(name, url) {
  28051. this.name = name;
  28052. this.url = url;
  28053. this.isCompleted = false;
  28054. }
  28055. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28056. var _this = this;
  28057. var img = new Image();
  28058. img.onload = function () {
  28059. _this.image = img;
  28060. _this.isCompleted = true;
  28061. if (_this.onSuccess) {
  28062. _this.onSuccess(_this);
  28063. }
  28064. onSuccess();
  28065. };
  28066. img.onerror = function () {
  28067. if (_this.onError) {
  28068. _this.onError(_this);
  28069. }
  28070. onError();
  28071. };
  28072. img.src = this.url;
  28073. };
  28074. return ImageAssetTask;
  28075. })();
  28076. BABYLON.ImageAssetTask = ImageAssetTask;
  28077. var TextureAssetTask = (function () {
  28078. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28080. this.name = name;
  28081. this.url = url;
  28082. this.noMipmap = noMipmap;
  28083. this.invertY = invertY;
  28084. this.samplingMode = samplingMode;
  28085. this.isCompleted = false;
  28086. }
  28087. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28088. var _this = this;
  28089. var onload = function () {
  28090. _this.isCompleted = true;
  28091. if (_this.onSuccess) {
  28092. _this.onSuccess(_this);
  28093. }
  28094. onSuccess();
  28095. };
  28096. var onerror = function () {
  28097. if (_this.onError) {
  28098. _this.onError(_this);
  28099. }
  28100. onError();
  28101. };
  28102. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28103. };
  28104. return TextureAssetTask;
  28105. })();
  28106. BABYLON.TextureAssetTask = TextureAssetTask;
  28107. var AssetsManager = (function () {
  28108. function AssetsManager(scene) {
  28109. this._tasks = new Array();
  28110. this._waitingTasksCount = 0;
  28111. this.useDefaultLoadingScreen = true;
  28112. this._scene = scene;
  28113. }
  28114. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28115. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28116. this._tasks.push(task);
  28117. return task;
  28118. };
  28119. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28120. var task = new TextFileAssetTask(taskName, url);
  28121. this._tasks.push(task);
  28122. return task;
  28123. };
  28124. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28125. var task = new BinaryFileAssetTask(taskName, url);
  28126. this._tasks.push(task);
  28127. return task;
  28128. };
  28129. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28130. var task = new ImageAssetTask(taskName, url);
  28131. this._tasks.push(task);
  28132. return task;
  28133. };
  28134. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28136. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28137. this._tasks.push(task);
  28138. return task;
  28139. };
  28140. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28141. this._waitingTasksCount--;
  28142. if (this._waitingTasksCount === 0) {
  28143. if (this.onFinish) {
  28144. this.onFinish(this._tasks);
  28145. }
  28146. this._scene.getEngine().hideLoadingUI();
  28147. }
  28148. };
  28149. AssetsManager.prototype._runTask = function (task) {
  28150. var _this = this;
  28151. task.run(this._scene, function () {
  28152. if (_this.onTaskSuccess) {
  28153. _this.onTaskSuccess(task);
  28154. }
  28155. _this._decreaseWaitingTasksCount();
  28156. }, function () {
  28157. if (_this.onTaskError) {
  28158. _this.onTaskError(task);
  28159. }
  28160. _this._decreaseWaitingTasksCount();
  28161. });
  28162. };
  28163. AssetsManager.prototype.reset = function () {
  28164. this._tasks = new Array();
  28165. return this;
  28166. };
  28167. AssetsManager.prototype.load = function () {
  28168. this._waitingTasksCount = this._tasks.length;
  28169. if (this._waitingTasksCount === 0) {
  28170. if (this.onFinish) {
  28171. this.onFinish(this._tasks);
  28172. }
  28173. return this;
  28174. }
  28175. if (this.useDefaultLoadingScreen) {
  28176. this._scene.getEngine().displayLoadingUI();
  28177. }
  28178. for (var index = 0; index < this._tasks.length; index++) {
  28179. var task = this._tasks[index];
  28180. this._runTask(task);
  28181. }
  28182. return this;
  28183. };
  28184. return AssetsManager;
  28185. })();
  28186. BABYLON.AssetsManager = AssetsManager;
  28187. })(BABYLON || (BABYLON = {}));
  28188. //# sourceMappingURL=babylon.assetsManager.js.map
  28189. var BABYLON;
  28190. (function (BABYLON) {
  28191. var VRDeviceOrientationFreeCamera = (function (_super) {
  28192. __extends(VRDeviceOrientationFreeCamera, _super);
  28193. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28194. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28195. _super.call(this, name, position, scene);
  28196. this._alpha = 0;
  28197. this._beta = 0;
  28198. this._gamma = 0;
  28199. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28200. metrics.compensateDistorsion = compensateDistorsion;
  28201. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28202. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28203. }
  28204. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28205. this._alpha = +evt.alpha | 0;
  28206. this._beta = +evt.beta | 0;
  28207. this._gamma = +evt.gamma | 0;
  28208. if (this._gamma < 0) {
  28209. this._gamma = 90 + this._gamma;
  28210. }
  28211. else {
  28212. // Incline it in the correct angle.
  28213. this._gamma = 270 - this._gamma;
  28214. }
  28215. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28216. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28217. this.rotation.z = this._beta / 180.0 * Math.PI;
  28218. };
  28219. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28220. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28221. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28222. };
  28223. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28224. _super.prototype.detachControl.call(this, element);
  28225. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28226. };
  28227. return VRDeviceOrientationFreeCamera;
  28228. })(BABYLON.FreeCamera);
  28229. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28230. })(BABYLON || (BABYLON = {}));
  28231. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28232. var BABYLON;
  28233. (function (BABYLON) {
  28234. var WebVRFreeCamera = (function (_super) {
  28235. __extends(WebVRFreeCamera, _super);
  28236. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28237. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28238. _super.call(this, name, position, scene);
  28239. this._hmdDevice = null;
  28240. this._sensorDevice = null;
  28241. this._cacheState = null;
  28242. this._cacheQuaternion = new BABYLON.Quaternion();
  28243. this._cacheRotation = BABYLON.Vector3.Zero();
  28244. this._vrEnabled = false;
  28245. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28246. metrics.compensateDistorsion = compensateDistorsion;
  28247. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28248. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28249. }
  28250. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28251. var size = devices.length;
  28252. var i = 0;
  28253. // Reset devices.
  28254. this._sensorDevice = null;
  28255. this._hmdDevice = null;
  28256. // Search for a HmdDevice.
  28257. while (i < size && this._hmdDevice === null) {
  28258. if (devices[i] instanceof HMDVRDevice) {
  28259. this._hmdDevice = devices[i];
  28260. }
  28261. i++;
  28262. }
  28263. i = 0;
  28264. while (i < size && this._sensorDevice === null) {
  28265. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28266. this._sensorDevice = devices[i];
  28267. }
  28268. i++;
  28269. }
  28270. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28271. };
  28272. WebVRFreeCamera.prototype._checkInputs = function () {
  28273. if (this._vrEnabled) {
  28274. this._cacheState = this._sensorDevice.getState();
  28275. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28276. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28277. this.rotation.x = -this._cacheRotation.z;
  28278. this.rotation.y = -this._cacheRotation.y;
  28279. this.rotation.z = this._cacheRotation.x;
  28280. }
  28281. _super.prototype._checkInputs.call(this);
  28282. };
  28283. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28284. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28285. if (navigator.getVRDevices) {
  28286. navigator.getVRDevices().then(this._getWebVRDevices);
  28287. }
  28288. else if (navigator.mozGetVRDevices) {
  28289. navigator.mozGetVRDevices(this._getWebVRDevices);
  28290. }
  28291. };
  28292. WebVRFreeCamera.prototype.detachControl = function (element) {
  28293. _super.prototype.detachControl.call(this, element);
  28294. this._vrEnabled = false;
  28295. };
  28296. return WebVRFreeCamera;
  28297. })(BABYLON.FreeCamera);
  28298. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28299. })(BABYLON || (BABYLON = {}));
  28300. //# sourceMappingURL=babylon.webVRCamera.js.map
  28301. var BABYLON;
  28302. (function (BABYLON) {
  28303. // Standard optimizations
  28304. var SceneOptimization = (function () {
  28305. function SceneOptimization(priority) {
  28306. if (priority === void 0) { priority = 0; }
  28307. this.priority = priority;
  28308. this.apply = function (scene) {
  28309. return true; // Return true if everything that can be done was applied
  28310. };
  28311. }
  28312. return SceneOptimization;
  28313. })();
  28314. BABYLON.SceneOptimization = SceneOptimization;
  28315. var TextureOptimization = (function (_super) {
  28316. __extends(TextureOptimization, _super);
  28317. function TextureOptimization(priority, maximumSize) {
  28318. var _this = this;
  28319. if (priority === void 0) { priority = 0; }
  28320. if (maximumSize === void 0) { maximumSize = 1024; }
  28321. _super.call(this, priority);
  28322. this.priority = priority;
  28323. this.maximumSize = maximumSize;
  28324. this.apply = function (scene) {
  28325. var allDone = true;
  28326. for (var index = 0; index < scene.textures.length; index++) {
  28327. var texture = scene.textures[index];
  28328. if (!texture.canRescale) {
  28329. continue;
  28330. }
  28331. var currentSize = texture.getSize();
  28332. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28333. if (maxDimension > _this.maximumSize) {
  28334. texture.scale(0.5);
  28335. allDone = false;
  28336. }
  28337. }
  28338. return allDone;
  28339. };
  28340. }
  28341. return TextureOptimization;
  28342. })(SceneOptimization);
  28343. BABYLON.TextureOptimization = TextureOptimization;
  28344. var HardwareScalingOptimization = (function (_super) {
  28345. __extends(HardwareScalingOptimization, _super);
  28346. function HardwareScalingOptimization(priority, maximumScale) {
  28347. var _this = this;
  28348. if (priority === void 0) { priority = 0; }
  28349. if (maximumScale === void 0) { maximumScale = 2; }
  28350. _super.call(this, priority);
  28351. this.priority = priority;
  28352. this.maximumScale = maximumScale;
  28353. this._currentScale = 1;
  28354. this.apply = function (scene) {
  28355. _this._currentScale++;
  28356. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28357. return _this._currentScale >= _this.maximumScale;
  28358. };
  28359. }
  28360. return HardwareScalingOptimization;
  28361. })(SceneOptimization);
  28362. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28363. var ShadowsOptimization = (function (_super) {
  28364. __extends(ShadowsOptimization, _super);
  28365. function ShadowsOptimization() {
  28366. _super.apply(this, arguments);
  28367. this.apply = function (scene) {
  28368. scene.shadowsEnabled = false;
  28369. return true;
  28370. };
  28371. }
  28372. return ShadowsOptimization;
  28373. })(SceneOptimization);
  28374. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28375. var PostProcessesOptimization = (function (_super) {
  28376. __extends(PostProcessesOptimization, _super);
  28377. function PostProcessesOptimization() {
  28378. _super.apply(this, arguments);
  28379. this.apply = function (scene) {
  28380. scene.postProcessesEnabled = false;
  28381. return true;
  28382. };
  28383. }
  28384. return PostProcessesOptimization;
  28385. })(SceneOptimization);
  28386. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28387. var LensFlaresOptimization = (function (_super) {
  28388. __extends(LensFlaresOptimization, _super);
  28389. function LensFlaresOptimization() {
  28390. _super.apply(this, arguments);
  28391. this.apply = function (scene) {
  28392. scene.lensFlaresEnabled = false;
  28393. return true;
  28394. };
  28395. }
  28396. return LensFlaresOptimization;
  28397. })(SceneOptimization);
  28398. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28399. var ParticlesOptimization = (function (_super) {
  28400. __extends(ParticlesOptimization, _super);
  28401. function ParticlesOptimization() {
  28402. _super.apply(this, arguments);
  28403. this.apply = function (scene) {
  28404. scene.particlesEnabled = false;
  28405. return true;
  28406. };
  28407. }
  28408. return ParticlesOptimization;
  28409. })(SceneOptimization);
  28410. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28411. var RenderTargetsOptimization = (function (_super) {
  28412. __extends(RenderTargetsOptimization, _super);
  28413. function RenderTargetsOptimization() {
  28414. _super.apply(this, arguments);
  28415. this.apply = function (scene) {
  28416. scene.renderTargetsEnabled = false;
  28417. return true;
  28418. };
  28419. }
  28420. return RenderTargetsOptimization;
  28421. })(SceneOptimization);
  28422. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28423. var MergeMeshesOptimization = (function (_super) {
  28424. __extends(MergeMeshesOptimization, _super);
  28425. function MergeMeshesOptimization() {
  28426. var _this = this;
  28427. _super.apply(this, arguments);
  28428. this._canBeMerged = function (abstractMesh) {
  28429. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28430. return false;
  28431. }
  28432. var mesh = abstractMesh;
  28433. if (!mesh.isVisible || !mesh.isEnabled()) {
  28434. return false;
  28435. }
  28436. if (mesh.instances.length > 0) {
  28437. return false;
  28438. }
  28439. if (mesh.skeleton || mesh.hasLODLevels) {
  28440. return false;
  28441. }
  28442. return true;
  28443. };
  28444. this.apply = function (scene) {
  28445. var globalPool = scene.meshes.slice(0);
  28446. var globalLength = globalPool.length;
  28447. for (var index = 0; index < globalLength; index++) {
  28448. var currentPool = new Array();
  28449. var current = globalPool[index];
  28450. // Checks
  28451. if (!_this._canBeMerged(current)) {
  28452. continue;
  28453. }
  28454. currentPool.push(current);
  28455. // Find compatible meshes
  28456. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28457. var otherMesh = globalPool[subIndex];
  28458. if (!_this._canBeMerged(otherMesh)) {
  28459. continue;
  28460. }
  28461. if (otherMesh.material !== current.material) {
  28462. continue;
  28463. }
  28464. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28465. continue;
  28466. }
  28467. currentPool.push(otherMesh);
  28468. globalLength--;
  28469. globalPool.splice(subIndex, 1);
  28470. subIndex--;
  28471. }
  28472. if (currentPool.length < 2) {
  28473. continue;
  28474. }
  28475. // Merge meshes
  28476. BABYLON.Mesh.MergeMeshes(currentPool);
  28477. }
  28478. return true;
  28479. };
  28480. }
  28481. return MergeMeshesOptimization;
  28482. })(SceneOptimization);
  28483. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28484. // Options
  28485. var SceneOptimizerOptions = (function () {
  28486. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28487. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28488. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28489. this.targetFrameRate = targetFrameRate;
  28490. this.trackerDuration = trackerDuration;
  28491. this.optimizations = new Array();
  28492. }
  28493. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28494. var result = new SceneOptimizerOptions(targetFrameRate);
  28495. var priority = 0;
  28496. result.optimizations.push(new MergeMeshesOptimization(priority));
  28497. result.optimizations.push(new ShadowsOptimization(priority));
  28498. result.optimizations.push(new LensFlaresOptimization(priority));
  28499. // Next priority
  28500. priority++;
  28501. result.optimizations.push(new PostProcessesOptimization(priority));
  28502. result.optimizations.push(new ParticlesOptimization(priority));
  28503. // Next priority
  28504. priority++;
  28505. result.optimizations.push(new TextureOptimization(priority, 1024));
  28506. return result;
  28507. };
  28508. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28509. var result = new SceneOptimizerOptions(targetFrameRate);
  28510. var priority = 0;
  28511. result.optimizations.push(new MergeMeshesOptimization(priority));
  28512. result.optimizations.push(new ShadowsOptimization(priority));
  28513. result.optimizations.push(new LensFlaresOptimization(priority));
  28514. // Next priority
  28515. priority++;
  28516. result.optimizations.push(new PostProcessesOptimization(priority));
  28517. result.optimizations.push(new ParticlesOptimization(priority));
  28518. // Next priority
  28519. priority++;
  28520. result.optimizations.push(new TextureOptimization(priority, 512));
  28521. // Next priority
  28522. priority++;
  28523. result.optimizations.push(new RenderTargetsOptimization(priority));
  28524. // Next priority
  28525. priority++;
  28526. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28527. return result;
  28528. };
  28529. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28530. var result = new SceneOptimizerOptions(targetFrameRate);
  28531. var priority = 0;
  28532. result.optimizations.push(new MergeMeshesOptimization(priority));
  28533. result.optimizations.push(new ShadowsOptimization(priority));
  28534. result.optimizations.push(new LensFlaresOptimization(priority));
  28535. // Next priority
  28536. priority++;
  28537. result.optimizations.push(new PostProcessesOptimization(priority));
  28538. result.optimizations.push(new ParticlesOptimization(priority));
  28539. // Next priority
  28540. priority++;
  28541. result.optimizations.push(new TextureOptimization(priority, 256));
  28542. // Next priority
  28543. priority++;
  28544. result.optimizations.push(new RenderTargetsOptimization(priority));
  28545. // Next priority
  28546. priority++;
  28547. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28548. return result;
  28549. };
  28550. return SceneOptimizerOptions;
  28551. })();
  28552. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28553. // Scene optimizer tool
  28554. var SceneOptimizer = (function () {
  28555. function SceneOptimizer() {
  28556. }
  28557. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28558. // TODO: add an epsilon
  28559. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28560. if (onSuccess) {
  28561. onSuccess();
  28562. }
  28563. return;
  28564. }
  28565. // Apply current level of optimizations
  28566. var allDone = true;
  28567. var noOptimizationApplied = true;
  28568. for (var index = 0; index < options.optimizations.length; index++) {
  28569. var optimization = options.optimizations[index];
  28570. if (optimization.priority === currentPriorityLevel) {
  28571. noOptimizationApplied = false;
  28572. allDone = allDone && optimization.apply(scene);
  28573. }
  28574. }
  28575. // If no optimization was applied, this is a failure :(
  28576. if (noOptimizationApplied) {
  28577. if (onFailure) {
  28578. onFailure();
  28579. }
  28580. return;
  28581. }
  28582. // If all optimizations were done, move to next level
  28583. if (allDone) {
  28584. currentPriorityLevel++;
  28585. }
  28586. // Let's the system running for a specific amount of time before checking FPS
  28587. scene.executeWhenReady(function () {
  28588. setTimeout(function () {
  28589. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28590. }, options.trackerDuration);
  28591. });
  28592. };
  28593. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28594. if (!options) {
  28595. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28596. }
  28597. // Let's the system running for a specific amount of time before checking FPS
  28598. scene.executeWhenReady(function () {
  28599. setTimeout(function () {
  28600. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28601. }, options.trackerDuration);
  28602. });
  28603. };
  28604. return SceneOptimizer;
  28605. })();
  28606. BABYLON.SceneOptimizer = SceneOptimizer;
  28607. })(BABYLON || (BABYLON = {}));
  28608. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28609. var BABYLON;
  28610. (function (BABYLON) {
  28611. var Internals;
  28612. (function (Internals) {
  28613. var MeshLODLevel = (function () {
  28614. function MeshLODLevel(distance, mesh) {
  28615. this.distance = distance;
  28616. this.mesh = mesh;
  28617. }
  28618. return MeshLODLevel;
  28619. })();
  28620. Internals.MeshLODLevel = MeshLODLevel;
  28621. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28622. })(BABYLON || (BABYLON = {}));
  28623. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28624. var BABYLON;
  28625. (function (BABYLON) {
  28626. var AudioEngine = (function () {
  28627. function AudioEngine() {
  28628. this._audioContext = null;
  28629. this._audioContextInitialized = false;
  28630. this.canUseWebAudio = false;
  28631. this.WarnedWebAudioUnsupported = false;
  28632. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28633. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28634. this.canUseWebAudio = true;
  28635. }
  28636. }
  28637. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28638. get: function () {
  28639. if (!this._audioContextInitialized) {
  28640. this._initializeAudioContext();
  28641. }
  28642. return this._audioContext;
  28643. },
  28644. enumerable: true,
  28645. configurable: true
  28646. });
  28647. AudioEngine.prototype._initializeAudioContext = function () {
  28648. try {
  28649. if (this.canUseWebAudio) {
  28650. this._audioContext = new AudioContext();
  28651. // create a global volume gain node
  28652. this.masterGain = this._audioContext.createGain();
  28653. this.masterGain.gain.value = 1;
  28654. this.masterGain.connect(this._audioContext.destination);
  28655. this._audioContextInitialized = true;
  28656. }
  28657. }
  28658. catch (e) {
  28659. this.canUseWebAudio = false;
  28660. BABYLON.Tools.Error("Web Audio: " + e.message);
  28661. }
  28662. };
  28663. AudioEngine.prototype.dispose = function () {
  28664. if (this.canUseWebAudio && this._audioContextInitialized) {
  28665. if (this._connectedAnalyser) {
  28666. this._connectedAnalyser.stopDebugCanvas();
  28667. this._connectedAnalyser.dispose();
  28668. this.masterGain.disconnect();
  28669. this.masterGain.connect(this._audioContext.destination);
  28670. this._connectedAnalyser = null;
  28671. }
  28672. this.masterGain.gain.value = 1;
  28673. }
  28674. this.WarnedWebAudioUnsupported = false;
  28675. };
  28676. AudioEngine.prototype.getGlobalVolume = function () {
  28677. if (this.canUseWebAudio && this._audioContextInitialized) {
  28678. return this.masterGain.gain.value;
  28679. }
  28680. else {
  28681. return -1;
  28682. }
  28683. };
  28684. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28685. if (this.canUseWebAudio && this._audioContextInitialized) {
  28686. this.masterGain.gain.value = newVolume;
  28687. }
  28688. };
  28689. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28690. if (this._connectedAnalyser) {
  28691. this._connectedAnalyser.stopDebugCanvas();
  28692. }
  28693. if (this.canUseWebAudio && this._audioContextInitialized) {
  28694. this._connectedAnalyser = analyser;
  28695. this.masterGain.disconnect();
  28696. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28697. }
  28698. };
  28699. return AudioEngine;
  28700. })();
  28701. BABYLON.AudioEngine = AudioEngine;
  28702. })(BABYLON || (BABYLON = {}));
  28703. //# sourceMappingURL=babylon.audioEngine.js.map
  28704. var BABYLON;
  28705. (function (BABYLON) {
  28706. var Sound = (function () {
  28707. /**
  28708. * Create a sound and attach it to a scene
  28709. * @param name Name of your sound
  28710. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28711. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28712. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28713. */
  28714. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28715. var _this = this;
  28716. this.autoplay = false;
  28717. this.loop = false;
  28718. this.useCustomAttenuation = false;
  28719. this.spatialSound = false;
  28720. this.refDistance = 1;
  28721. this.rolloffFactor = 1;
  28722. this.maxDistance = 100;
  28723. this.distanceModel = "linear";
  28724. this._panningModel = "equalpower";
  28725. this._playbackRate = 1;
  28726. this._startTime = 0;
  28727. this._startOffset = 0;
  28728. this._position = BABYLON.Vector3.Zero();
  28729. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28730. this._volume = 1;
  28731. this._isLoaded = false;
  28732. this._isReadyToPlay = false;
  28733. this.isPlaying = false;
  28734. this.isPaused = false;
  28735. this._isDirectional = false;
  28736. // Used if you'd like to create a directional sound.
  28737. // If not set, the sound will be omnidirectional
  28738. this._coneInnerAngle = 360;
  28739. this._coneOuterAngle = 360;
  28740. this._coneOuterGain = 0;
  28741. this.name = name;
  28742. this._scene = scene;
  28743. this._readyToPlayCallback = readyToPlayCallback;
  28744. // Default custom attenuation function is a linear attenuation
  28745. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28746. if (currentDistance < maxDistance) {
  28747. return currentVolume * (1 - currentDistance / maxDistance);
  28748. }
  28749. else {
  28750. return 0;
  28751. }
  28752. };
  28753. if (options) {
  28754. this.autoplay = options.autoplay || false;
  28755. this.loop = options.loop || false;
  28756. // if volume === 0, we need another way to check this option
  28757. if (options.volume !== undefined) {
  28758. this._volume = options.volume;
  28759. }
  28760. this.spatialSound = options.spatialSound || false;
  28761. this.maxDistance = options.maxDistance || 100;
  28762. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28763. this.rolloffFactor = options.rolloffFactor || 1;
  28764. this.refDistance = options.refDistance || 1;
  28765. this.distanceModel = options.distanceModel || "linear";
  28766. this._playbackRate = options.playbackRate || 1;
  28767. }
  28768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28769. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28770. this._soundGain.gain.value = this._volume;
  28771. this._inputAudioNode = this._soundGain;
  28772. this._ouputAudioNode = this._soundGain;
  28773. if (this.spatialSound) {
  28774. this._createSpatialParameters();
  28775. }
  28776. this._scene.mainSoundTrack.AddSound(this);
  28777. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28778. if (urlOrArrayBuffer) {
  28779. // If it's an URL
  28780. if (typeof (urlOrArrayBuffer) === "string") {
  28781. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  28782. }
  28783. else {
  28784. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28785. this._soundLoaded(urlOrArrayBuffer);
  28786. }
  28787. else {
  28788. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28789. }
  28790. }
  28791. }
  28792. }
  28793. else {
  28794. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28795. this._scene.mainSoundTrack.AddSound(this);
  28796. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28797. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28798. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28799. }
  28800. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28801. if (this._readyToPlayCallback) {
  28802. window.setTimeout(function () {
  28803. _this._readyToPlayCallback();
  28804. }, 1000);
  28805. }
  28806. }
  28807. }
  28808. Sound.prototype.dispose = function () {
  28809. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28810. if (this.isPlaying) {
  28811. this.stop();
  28812. }
  28813. this._isReadyToPlay = false;
  28814. if (this.soundTrackId === -1) {
  28815. this._scene.mainSoundTrack.RemoveSound(this);
  28816. }
  28817. else {
  28818. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28819. }
  28820. if (this._soundGain) {
  28821. this._soundGain.disconnect();
  28822. this._soundGain = null;
  28823. }
  28824. if (this._soundPanner) {
  28825. this._soundPanner.disconnect();
  28826. this._soundPanner = null;
  28827. }
  28828. if (this._soundSource) {
  28829. this._soundSource.disconnect();
  28830. this._soundSource = null;
  28831. }
  28832. this._audioBuffer = null;
  28833. if (this._connectedMesh) {
  28834. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28835. this._connectedMesh = null;
  28836. }
  28837. }
  28838. };
  28839. Sound.prototype._soundLoaded = function (audioData) {
  28840. var _this = this;
  28841. this._isLoaded = true;
  28842. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28843. _this._audioBuffer = buffer;
  28844. _this._isReadyToPlay = true;
  28845. if (_this.autoplay) {
  28846. _this.play();
  28847. }
  28848. if (_this._readyToPlayCallback) {
  28849. _this._readyToPlayCallback();
  28850. }
  28851. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  28852. };
  28853. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28854. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28855. this._audioBuffer = audioBuffer;
  28856. this._isReadyToPlay = true;
  28857. }
  28858. };
  28859. Sound.prototype.updateOptions = function (options) {
  28860. if (options) {
  28861. this.loop = options.loop || this.loop;
  28862. this.maxDistance = options.maxDistance || this.maxDistance;
  28863. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28864. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28865. this.refDistance = options.refDistance || this.refDistance;
  28866. this.distanceModel = options.distanceModel || this.distanceModel;
  28867. this._playbackRate = options.playbackRate || this._playbackRate;
  28868. this._updateSpatialParameters();
  28869. if (this.isPlaying) {
  28870. this._soundSource.playbackRate.value = this._playbackRate;
  28871. }
  28872. }
  28873. };
  28874. Sound.prototype._createSpatialParameters = function () {
  28875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28876. if (this._scene.headphone) {
  28877. this._panningModel = "HRTF";
  28878. }
  28879. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28880. this._updateSpatialParameters();
  28881. this._soundPanner.connect(this._ouputAudioNode);
  28882. this._inputAudioNode = this._soundPanner;
  28883. }
  28884. };
  28885. Sound.prototype._updateSpatialParameters = function () {
  28886. if (this.spatialSound) {
  28887. if (this.useCustomAttenuation) {
  28888. // Tricks to disable in a way embedded Web Audio attenuation
  28889. this._soundPanner.distanceModel = "linear";
  28890. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28891. this._soundPanner.refDistance = 1;
  28892. this._soundPanner.rolloffFactor = 1;
  28893. this._soundPanner.panningModel = this._panningModel;
  28894. }
  28895. else {
  28896. this._soundPanner.distanceModel = this.distanceModel;
  28897. this._soundPanner.maxDistance = this.maxDistance;
  28898. this._soundPanner.refDistance = this.refDistance;
  28899. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28900. this._soundPanner.panningModel = this._panningModel;
  28901. }
  28902. }
  28903. };
  28904. Sound.prototype.switchPanningModelToHRTF = function () {
  28905. this._panningModel = "HRTF";
  28906. this._switchPanningModel();
  28907. };
  28908. Sound.prototype.switchPanningModelToEqualPower = function () {
  28909. this._panningModel = "equalpower";
  28910. this._switchPanningModel();
  28911. };
  28912. Sound.prototype._switchPanningModel = function () {
  28913. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28914. this._soundPanner.panningModel = this._panningModel;
  28915. }
  28916. };
  28917. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28919. this._ouputAudioNode.disconnect();
  28920. this._ouputAudioNode.connect(soundTrackAudioNode);
  28921. }
  28922. };
  28923. /**
  28924. * Transform this sound into a directional source
  28925. * @param coneInnerAngle Size of the inner cone in degree
  28926. * @param coneOuterAngle Size of the outer cone in degree
  28927. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28928. */
  28929. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28930. if (coneOuterAngle < coneInnerAngle) {
  28931. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28932. return;
  28933. }
  28934. this._coneInnerAngle = coneInnerAngle;
  28935. this._coneOuterAngle = coneOuterAngle;
  28936. this._coneOuterGain = coneOuterGain;
  28937. this._isDirectional = true;
  28938. if (this.isPlaying && this.loop) {
  28939. this.stop();
  28940. this.play();
  28941. }
  28942. };
  28943. Sound.prototype.setPosition = function (newPosition) {
  28944. this._position = newPosition;
  28945. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28946. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28947. }
  28948. };
  28949. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28950. this._localDirection = newLocalDirection;
  28951. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28952. this._updateDirection();
  28953. }
  28954. };
  28955. Sound.prototype._updateDirection = function () {
  28956. var mat = this._connectedMesh.getWorldMatrix();
  28957. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28958. direction.normalize();
  28959. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28960. };
  28961. Sound.prototype.updateDistanceFromListener = function () {
  28962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28963. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28964. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28965. }
  28966. };
  28967. Sound.prototype.setAttenuationFunction = function (callback) {
  28968. this._customAttenuationFunction = callback;
  28969. };
  28970. /**
  28971. * Play the sound
  28972. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28973. */
  28974. Sound.prototype.play = function (time) {
  28975. var _this = this;
  28976. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28977. try {
  28978. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28979. if (!this._soundSource) {
  28980. if (this.spatialSound) {
  28981. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28982. if (this._isDirectional) {
  28983. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28984. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28985. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28986. if (this._connectedMesh) {
  28987. this._updateDirection();
  28988. }
  28989. else {
  28990. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28991. }
  28992. }
  28993. }
  28994. }
  28995. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28996. this._soundSource.buffer = this._audioBuffer;
  28997. this._soundSource.connect(this._inputAudioNode);
  28998. this._soundSource.loop = this.loop;
  28999. this._soundSource.playbackRate.value = this._playbackRate;
  29000. this._startTime = startTime;
  29001. this._soundSource.onended = function () { _this._onended(); };
  29002. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29003. this.isPlaying = true;
  29004. this.isPaused = false;
  29005. }
  29006. catch (ex) {
  29007. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29008. }
  29009. }
  29010. };
  29011. Sound.prototype._onended = function () {
  29012. this.isPlaying = false;
  29013. if (this.onended) {
  29014. this.onended();
  29015. }
  29016. };
  29017. /**
  29018. * Stop the sound
  29019. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29020. */
  29021. Sound.prototype.stop = function (time) {
  29022. if (this.isPlaying) {
  29023. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29024. this._soundSource.stop(stopTime);
  29025. this.isPlaying = false;
  29026. }
  29027. };
  29028. Sound.prototype.pause = function () {
  29029. if (this.isPlaying) {
  29030. this.stop(0);
  29031. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29032. this.isPaused = true;
  29033. }
  29034. };
  29035. Sound.prototype.setVolume = function (newVolume, time) {
  29036. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29037. if (time) {
  29038. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29039. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29040. }
  29041. else {
  29042. this._soundGain.gain.value = newVolume;
  29043. }
  29044. }
  29045. this._volume = newVolume;
  29046. };
  29047. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29048. this._playbackRate = newPlaybackRate;
  29049. if (this.isPlaying) {
  29050. this._soundSource.playbackRate.value = this._playbackRate;
  29051. }
  29052. };
  29053. Sound.prototype.getVolume = function () {
  29054. return this._volume;
  29055. };
  29056. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29057. var _this = this;
  29058. this._connectedMesh = meshToConnectTo;
  29059. if (!this.spatialSound) {
  29060. this.spatialSound = true;
  29061. this._createSpatialParameters();
  29062. if (this.isPlaying && this.loop) {
  29063. this.stop();
  29064. this.play();
  29065. }
  29066. }
  29067. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29068. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29069. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29070. };
  29071. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29072. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29073. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29074. this._updateDirection();
  29075. }
  29076. };
  29077. return Sound;
  29078. })();
  29079. BABYLON.Sound = Sound;
  29080. })(BABYLON || (BABYLON = {}));
  29081. //# sourceMappingURL=babylon.sound.js.map
  29082. var BABYLON;
  29083. (function (BABYLON) {
  29084. var SoundTrack = (function () {
  29085. function SoundTrack(scene, options) {
  29086. this.id = -1;
  29087. this._isMainTrack = false;
  29088. this._scene = scene;
  29089. this._audioEngine = BABYLON.Engine.audioEngine;
  29090. this.soundCollection = new Array();
  29091. if (this._audioEngine.canUseWebAudio) {
  29092. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29093. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29094. if (options) {
  29095. if (options.volume) {
  29096. this._outputAudioNode.gain.value = options.volume;
  29097. }
  29098. if (options.mainTrack) {
  29099. this._isMainTrack = options.mainTrack;
  29100. }
  29101. }
  29102. }
  29103. if (!this._isMainTrack) {
  29104. this._scene.soundTracks.push(this);
  29105. this.id = this._scene.soundTracks.length - 1;
  29106. }
  29107. }
  29108. SoundTrack.prototype.dispose = function () {
  29109. if (this._audioEngine.canUseWebAudio) {
  29110. if (this._connectedAnalyser) {
  29111. this._connectedAnalyser.stopDebugCanvas();
  29112. }
  29113. while (this.soundCollection.length) {
  29114. this.soundCollection[0].dispose();
  29115. }
  29116. this._outputAudioNode.disconnect();
  29117. this._outputAudioNode = null;
  29118. }
  29119. };
  29120. SoundTrack.prototype.AddSound = function (sound) {
  29121. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29122. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29123. }
  29124. if (sound.soundTrackId) {
  29125. if (sound.soundTrackId === -1) {
  29126. this._scene.mainSoundTrack.RemoveSound(sound);
  29127. }
  29128. else {
  29129. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29130. }
  29131. }
  29132. this.soundCollection.push(sound);
  29133. sound.soundTrackId = this.id;
  29134. };
  29135. SoundTrack.prototype.RemoveSound = function (sound) {
  29136. var index = this.soundCollection.indexOf(sound);
  29137. if (index !== -1) {
  29138. this.soundCollection.splice(index, 1);
  29139. }
  29140. };
  29141. SoundTrack.prototype.setVolume = function (newVolume) {
  29142. if (this._audioEngine.canUseWebAudio) {
  29143. this._outputAudioNode.gain.value = newVolume;
  29144. }
  29145. };
  29146. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29147. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29148. for (var i = 0; i < this.soundCollection.length; i++) {
  29149. this.soundCollection[i].switchPanningModelToHRTF();
  29150. }
  29151. }
  29152. };
  29153. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29154. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29155. for (var i = 0; i < this.soundCollection.length; i++) {
  29156. this.soundCollection[i].switchPanningModelToEqualPower();
  29157. }
  29158. }
  29159. };
  29160. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29161. if (this._connectedAnalyser) {
  29162. this._connectedAnalyser.stopDebugCanvas();
  29163. }
  29164. this._connectedAnalyser = analyser;
  29165. if (this._audioEngine.canUseWebAudio) {
  29166. this._outputAudioNode.disconnect();
  29167. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29168. }
  29169. };
  29170. return SoundTrack;
  29171. })();
  29172. BABYLON.SoundTrack = SoundTrack;
  29173. })(BABYLON || (BABYLON = {}));
  29174. //# sourceMappingURL=babylon.soundtrack.js.map
  29175. var BABYLON;
  29176. (function (BABYLON) {
  29177. var DebugLayer = (function () {
  29178. function DebugLayer(scene) {
  29179. var _this = this;
  29180. this._transformationMatrix = BABYLON.Matrix.Identity();
  29181. this._enabled = false;
  29182. this._labelsEnabled = false;
  29183. this._displayStatistics = true;
  29184. this._displayTree = false;
  29185. this._displayLogs = false;
  29186. this._identityMatrix = BABYLON.Matrix.Identity();
  29187. this.axisRatio = 0.02;
  29188. this.accentColor = "orange";
  29189. this._scene = scene;
  29190. this._syncPositions = function () {
  29191. var engine = _this._scene.getEngine();
  29192. var canvasRect = engine.getRenderingCanvasClientRect();
  29193. if (_this._showUI) {
  29194. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29195. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29196. _this._statsDiv.style.width = "400px";
  29197. _this._statsDiv.style.height = "auto";
  29198. _this._statsSubsetDiv.style.maxHeight = "240px";
  29199. _this._optionsDiv.style.left = "0px";
  29200. _this._optionsDiv.style.top = "10px";
  29201. _this._optionsDiv.style.width = "200px";
  29202. _this._optionsDiv.style.height = "auto";
  29203. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29204. _this._logDiv.style.left = "0px";
  29205. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29206. _this._logDiv.style.width = "600px";
  29207. _this._logDiv.style.height = "160px";
  29208. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29209. _this._treeDiv.style.top = "10px";
  29210. _this._treeDiv.style.width = "300px";
  29211. _this._treeDiv.style.height = "auto";
  29212. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29213. }
  29214. _this._globalDiv.style.left = canvasRect.left + "px";
  29215. _this._globalDiv.style.top = canvasRect.top + "px";
  29216. _this._drawingCanvas.style.left = "0px";
  29217. _this._drawingCanvas.style.top = "0px";
  29218. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29219. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29220. var devicePixelRatio = window.devicePixelRatio || 1;
  29221. var context = _this._drawingContext;
  29222. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29223. context.mozBackingStorePixelRatio ||
  29224. context.msBackingStorePixelRatio ||
  29225. context.oBackingStorePixelRatio ||
  29226. context.backingStorePixelRatio || 1;
  29227. _this._ratio = devicePixelRatio / backingStoreRatio;
  29228. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29229. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29230. };
  29231. this._onCanvasClick = function (evt) {
  29232. _this._clickPosition = {
  29233. x: evt.clientX * _this._ratio,
  29234. y: evt.clientY * _this._ratio
  29235. };
  29236. };
  29237. this._syncUI = function () {
  29238. if (_this._showUI) {
  29239. if (_this._displayStatistics) {
  29240. _this._displayStats();
  29241. _this._statsDiv.style.display = "";
  29242. }
  29243. else {
  29244. _this._statsDiv.style.display = "none";
  29245. }
  29246. if (_this._displayLogs) {
  29247. _this._logDiv.style.display = "";
  29248. }
  29249. else {
  29250. _this._logDiv.style.display = "none";
  29251. }
  29252. if (_this._displayTree) {
  29253. _this._treeDiv.style.display = "";
  29254. if (_this._needToRefreshMeshesTree) {
  29255. _this._needToRefreshMeshesTree = false;
  29256. _this._refreshMeshesTreeContent();
  29257. }
  29258. }
  29259. else {
  29260. _this._treeDiv.style.display = "none";
  29261. }
  29262. }
  29263. };
  29264. this._syncData = function () {
  29265. if (_this._labelsEnabled || !_this._showUI) {
  29266. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29267. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29268. var engine = _this._scene.getEngine();
  29269. var viewport = _this._camera.viewport;
  29270. var globalViewport = viewport.toGlobal(engine);
  29271. // Meshes
  29272. var meshes = _this._camera.getActiveMeshes();
  29273. for (var index = 0; index < meshes.length; index++) {
  29274. var mesh = meshes.data[index];
  29275. var position = mesh.getBoundingInfo().boundingSphere.center;
  29276. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29277. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29278. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29279. }
  29280. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29281. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29282. }
  29283. }
  29284. // Cameras
  29285. var cameras = _this._scene.cameras;
  29286. for (index = 0; index < cameras.length; index++) {
  29287. var camera = cameras[index];
  29288. if (camera === _this._camera) {
  29289. continue;
  29290. }
  29291. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29292. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29293. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29294. _this._camera.detachControl(engine.getRenderingCanvas());
  29295. _this._camera = camera;
  29296. _this._camera.attachControl(engine.getRenderingCanvas());
  29297. }, function () { return "purple"; });
  29298. }
  29299. }
  29300. // Lights
  29301. var lights = _this._scene.lights;
  29302. for (index = 0; index < lights.length; index++) {
  29303. var light = lights[index];
  29304. if (light.position) {
  29305. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29306. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29307. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29308. light.setEnabled(!light.isEnabled());
  29309. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29310. }
  29311. }
  29312. }
  29313. }
  29314. _this._clickPosition = undefined;
  29315. };
  29316. }
  29317. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29318. while (this._treeSubsetDiv.hasChildNodes()) {
  29319. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29320. }
  29321. // Add meshes
  29322. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29323. sortedArray.sort(function (a, b) {
  29324. if (a.name === b.name) {
  29325. return 0;
  29326. }
  29327. return (a.name > b.name) ? 1 : -1;
  29328. });
  29329. for (var index = 0; index < sortedArray.length; index++) {
  29330. var mesh = sortedArray[index];
  29331. if (!mesh.isEnabled()) {
  29332. continue;
  29333. }
  29334. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29335. m.isVisible = element.checked;
  29336. }, mesh);
  29337. }
  29338. };
  29339. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29340. this._drawingContext.beginPath();
  29341. this._drawingContext.moveTo(zero.x, zero.y);
  29342. this._drawingContext.lineTo(unit.x, unit.y);
  29343. this._drawingContext.strokeStyle = color;
  29344. this._drawingContext.lineWidth = 4;
  29345. this._drawingContext.stroke();
  29346. this._drawingContext.font = "normal 14px Segoe UI";
  29347. this._drawingContext.fillStyle = color;
  29348. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29349. };
  29350. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29351. var position = mesh.getBoundingInfo().boundingSphere.center;
  29352. var worldMatrix = mesh.getWorldMatrix();
  29353. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29354. var unit = (unprojectedVector.subtract(position)).length();
  29355. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29356. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29357. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29358. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29359. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29360. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29361. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29362. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29363. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29364. };
  29365. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29366. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29367. this._drawingContext.font = "normal 12px Segoe UI";
  29368. var textMetrics = this._drawingContext.measureText(text);
  29369. var centerX = projectedPosition.x - textMetrics.width / 2;
  29370. var centerY = projectedPosition.y;
  29371. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29372. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29373. onClick();
  29374. }
  29375. this._drawingContext.beginPath();
  29376. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29377. this._drawingContext.fillStyle = getFillStyle();
  29378. this._drawingContext.globalAlpha = 0.5;
  29379. this._drawingContext.fill();
  29380. this._drawingContext.globalAlpha = 1.0;
  29381. this._drawingContext.strokeStyle = '#FFFFFF';
  29382. this._drawingContext.lineWidth = 1;
  29383. this._drawingContext.stroke();
  29384. this._drawingContext.fillStyle = "#FFFFFF";
  29385. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29386. this._drawingContext.beginPath();
  29387. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29388. this._drawingContext.fill();
  29389. }
  29390. };
  29391. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29392. if (!this._clickPosition) {
  29393. return false;
  29394. }
  29395. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29396. return false;
  29397. }
  29398. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29399. return false;
  29400. }
  29401. return true;
  29402. };
  29403. DebugLayer.prototype.isVisible = function () {
  29404. return this._enabled;
  29405. };
  29406. DebugLayer.prototype.hide = function () {
  29407. if (!this._enabled) {
  29408. return;
  29409. }
  29410. this._enabled = false;
  29411. var engine = this._scene.getEngine();
  29412. this._scene.unregisterBeforeRender(this._syncData);
  29413. this._scene.unregisterAfterRender(this._syncUI);
  29414. document.body.removeChild(this._globalDiv);
  29415. window.removeEventListener("resize", this._syncPositions);
  29416. this._scene.forceShowBoundingBoxes = false;
  29417. this._scene.forceWireframe = false;
  29418. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29419. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29420. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29421. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29422. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29423. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29424. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29425. this._scene.shadowsEnabled = true;
  29426. this._scene.particlesEnabled = true;
  29427. this._scene.postProcessesEnabled = true;
  29428. this._scene.collisionsEnabled = true;
  29429. this._scene.lightsEnabled = true;
  29430. this._scene.texturesEnabled = true;
  29431. this._scene.lensFlaresEnabled = true;
  29432. this._scene.proceduralTexturesEnabled = true;
  29433. this._scene.renderTargetsEnabled = true;
  29434. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29435. };
  29436. DebugLayer.prototype.show = function (showUI, camera) {
  29437. if (showUI === void 0) { showUI = true; }
  29438. if (camera === void 0) { camera = null; }
  29439. if (this._enabled) {
  29440. return;
  29441. }
  29442. this._enabled = true;
  29443. if (camera) {
  29444. this._camera = camera;
  29445. }
  29446. else {
  29447. this._camera = this._scene.activeCamera;
  29448. }
  29449. this._showUI = showUI;
  29450. var engine = this._scene.getEngine();
  29451. this._globalDiv = document.createElement("div");
  29452. document.body.appendChild(this._globalDiv);
  29453. this._generateDOMelements();
  29454. window.addEventListener("resize", this._syncPositions);
  29455. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29456. this._syncPositions();
  29457. this._scene.registerBeforeRender(this._syncData);
  29458. this._scene.registerAfterRender(this._syncUI);
  29459. };
  29460. DebugLayer.prototype._clearLabels = function () {
  29461. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29462. for (var index = 0; index < this._scene.meshes.length; index++) {
  29463. var mesh = this._scene.meshes[index];
  29464. mesh.renderOverlay = false;
  29465. }
  29466. };
  29467. DebugLayer.prototype._generateheader = function (root, text) {
  29468. var header = document.createElement("div");
  29469. header.innerHTML = text + "&nbsp;";
  29470. header.style.textAlign = "right";
  29471. header.style.width = "100%";
  29472. header.style.color = "white";
  29473. header.style.backgroundColor = "Black";
  29474. header.style.padding = "5px 5px 4px 0px";
  29475. header.style.marginLeft = "-5px";
  29476. header.style.fontWeight = "bold";
  29477. root.appendChild(header);
  29478. };
  29479. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29480. var label = document.createElement("label");
  29481. label.innerHTML = title;
  29482. label.style.color = color;
  29483. root.appendChild(label);
  29484. root.appendChild(document.createElement("br"));
  29485. };
  29486. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29487. if (tag === void 0) { tag = null; }
  29488. var label = document.createElement("label");
  29489. var boundingBoxesCheckbox = document.createElement("input");
  29490. boundingBoxesCheckbox.type = "checkbox";
  29491. boundingBoxesCheckbox.checked = initialState;
  29492. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29493. task(evt.target, tag);
  29494. });
  29495. label.appendChild(boundingBoxesCheckbox);
  29496. var container = document.createElement("span");
  29497. var leftPart = document.createElement("span");
  29498. var rightPart = document.createElement("span");
  29499. rightPart.style.cssFloat = "right";
  29500. leftPart.innerHTML = leftTitle;
  29501. rightPart.innerHTML = rightTitle;
  29502. rightPart.style.fontSize = "12px";
  29503. rightPart.style.maxWidth = "200px";
  29504. container.appendChild(leftPart);
  29505. container.appendChild(rightPart);
  29506. label.appendChild(container);
  29507. root.appendChild(label);
  29508. root.appendChild(document.createElement("br"));
  29509. };
  29510. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29511. if (tag === void 0) { tag = null; }
  29512. var label = document.createElement("label");
  29513. var checkBox = document.createElement("input");
  29514. checkBox.type = "checkbox";
  29515. checkBox.checked = initialState;
  29516. checkBox.addEventListener("change", function (evt) {
  29517. task(evt.target, tag);
  29518. });
  29519. label.appendChild(checkBox);
  29520. label.appendChild(document.createTextNode(title));
  29521. root.appendChild(label);
  29522. root.appendChild(document.createElement("br"));
  29523. };
  29524. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29525. if (tag === void 0) { tag = null; }
  29526. var button = document.createElement("button");
  29527. button.innerHTML = title;
  29528. button.style.height = "24px";
  29529. button.style.color = "#444444";
  29530. button.style.border = "1px solid white";
  29531. button.className = "debugLayerButton";
  29532. button.addEventListener("click", function (evt) {
  29533. task(evt.target, tag);
  29534. });
  29535. root.appendChild(button);
  29536. root.appendChild(document.createElement("br"));
  29537. };
  29538. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29539. if (tag === void 0) { tag = null; }
  29540. var label = document.createElement("label");
  29541. var boundingBoxesRadio = document.createElement("input");
  29542. boundingBoxesRadio.type = "radio";
  29543. boundingBoxesRadio.name = name;
  29544. boundingBoxesRadio.checked = initialState;
  29545. boundingBoxesRadio.addEventListener("change", function (evt) {
  29546. task(evt.target, tag);
  29547. });
  29548. label.appendChild(boundingBoxesRadio);
  29549. label.appendChild(document.createTextNode(title));
  29550. root.appendChild(label);
  29551. root.appendChild(document.createElement("br"));
  29552. };
  29553. DebugLayer.prototype._generateDOMelements = function () {
  29554. var _this = this;
  29555. this._globalDiv.id = "DebugLayer";
  29556. this._globalDiv.style.position = "absolute";
  29557. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29558. this._globalDiv.style.fontSize = "14px";
  29559. this._globalDiv.style.color = "white";
  29560. // Drawing canvas
  29561. this._drawingCanvas = document.createElement("canvas");
  29562. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29563. this._drawingCanvas.style.position = "absolute";
  29564. this._drawingCanvas.style.pointerEvents = "none";
  29565. this._drawingContext = this._drawingCanvas.getContext("2d");
  29566. this._globalDiv.appendChild(this._drawingCanvas);
  29567. if (this._showUI) {
  29568. var background = "rgba(128, 128, 128, 0.4)";
  29569. var border = "rgb(180, 180, 180) solid 1px";
  29570. // Stats
  29571. this._statsDiv = document.createElement("div");
  29572. this._statsDiv.id = "DebugLayerStats";
  29573. this._statsDiv.style.border = border;
  29574. this._statsDiv.style.position = "absolute";
  29575. this._statsDiv.style.background = background;
  29576. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29577. this._generateheader(this._statsDiv, "STATISTICS");
  29578. this._statsSubsetDiv = document.createElement("div");
  29579. this._statsSubsetDiv.style.paddingTop = "5px";
  29580. this._statsSubsetDiv.style.paddingBottom = "5px";
  29581. this._statsSubsetDiv.style.overflowY = "auto";
  29582. this._statsDiv.appendChild(this._statsSubsetDiv);
  29583. // Tree
  29584. this._treeDiv = document.createElement("div");
  29585. this._treeDiv.id = "DebugLayerTree";
  29586. this._treeDiv.style.border = border;
  29587. this._treeDiv.style.position = "absolute";
  29588. this._treeDiv.style.background = background;
  29589. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29590. this._treeDiv.style.display = "none";
  29591. this._generateheader(this._treeDiv, "MESHES TREE");
  29592. this._treeSubsetDiv = document.createElement("div");
  29593. this._treeSubsetDiv.style.paddingTop = "5px";
  29594. this._treeSubsetDiv.style.paddingRight = "5px";
  29595. this._treeSubsetDiv.style.overflowY = "auto";
  29596. this._treeSubsetDiv.style.maxHeight = "300px";
  29597. this._treeDiv.appendChild(this._treeSubsetDiv);
  29598. this._needToRefreshMeshesTree = true;
  29599. // Logs
  29600. this._logDiv = document.createElement("div");
  29601. this._logDiv.style.border = border;
  29602. this._logDiv.id = "DebugLayerLogs";
  29603. this._logDiv.style.position = "absolute";
  29604. this._logDiv.style.background = background;
  29605. this._logDiv.style.padding = "0px 0px 0px 5px";
  29606. this._logDiv.style.display = "none";
  29607. this._generateheader(this._logDiv, "LOGS");
  29608. this._logSubsetDiv = document.createElement("div");
  29609. this._logSubsetDiv.style.height = "127px";
  29610. this._logSubsetDiv.style.paddingTop = "5px";
  29611. this._logSubsetDiv.style.overflowY = "auto";
  29612. this._logSubsetDiv.style.fontSize = "12px";
  29613. this._logSubsetDiv.style.fontFamily = "consolas";
  29614. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29615. this._logDiv.appendChild(this._logSubsetDiv);
  29616. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29617. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29618. };
  29619. // Options
  29620. this._optionsDiv = document.createElement("div");
  29621. this._optionsDiv.id = "DebugLayerOptions";
  29622. this._optionsDiv.style.border = border;
  29623. this._optionsDiv.style.position = "absolute";
  29624. this._optionsDiv.style.background = background;
  29625. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29626. this._optionsDiv.style.overflowY = "auto";
  29627. this._generateheader(this._optionsDiv, "OPTIONS");
  29628. this._optionsSubsetDiv = document.createElement("div");
  29629. this._optionsSubsetDiv.style.paddingTop = "5px";
  29630. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29631. this._optionsSubsetDiv.style.overflowY = "auto";
  29632. this._optionsSubsetDiv.style.maxHeight = "200px";
  29633. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29634. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29635. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29636. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29637. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29638. _this._displayTree = element.checked;
  29639. _this._needToRefreshMeshesTree = true;
  29640. });
  29641. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29642. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29643. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29644. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29645. _this._labelsEnabled = element.checked;
  29646. if (!_this._labelsEnabled) {
  29647. _this._clearLabels();
  29648. }
  29649. });
  29650. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29651. if (element.checked) {
  29652. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29653. }
  29654. else {
  29655. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29656. }
  29657. });
  29658. ;
  29659. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29660. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29661. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29662. if (element.checked) {
  29663. _this._scene.forceWireframe = false;
  29664. _this._scene.forcePointsCloud = false;
  29665. }
  29666. });
  29667. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29668. if (element.checked) {
  29669. _this._scene.forceWireframe = true;
  29670. _this._scene.forcePointsCloud = false;
  29671. }
  29672. });
  29673. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29674. if (element.checked) {
  29675. _this._scene.forceWireframe = false;
  29676. _this._scene.forcePointsCloud = true;
  29677. }
  29678. });
  29679. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29680. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29681. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29682. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29683. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29684. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29685. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29686. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29687. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29688. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29689. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29690. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29691. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29692. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29693. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29694. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29695. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29696. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29697. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29698. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29699. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29700. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29701. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29702. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29703. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29704. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29705. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29706. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29707. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29708. if (element.checked) {
  29709. _this._scene.headphone = true;
  29710. }
  29711. });
  29712. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29713. if (element.checked) {
  29714. _this._scene.headphone = false;
  29715. }
  29716. });
  29717. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29718. _this._scene.audioEnabled = !element.checked;
  29719. });
  29720. }
  29721. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29722. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29723. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29724. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29725. this._globalDiv.appendChild(this._statsDiv);
  29726. this._globalDiv.appendChild(this._logDiv);
  29727. this._globalDiv.appendChild(this._optionsDiv);
  29728. this._globalDiv.appendChild(this._treeDiv);
  29729. }
  29730. };
  29731. DebugLayer.prototype._displayStats = function () {
  29732. var scene = this._scene;
  29733. var engine = scene.getEngine();
  29734. var glInfo = engine.getGlInfo();
  29735. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29736. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29737. + "<b>Count</b><br>"
  29738. + "Total meshes: " + scene.meshes.length + "<br>"
  29739. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29740. + "Total materials: " + scene.materials.length + "<br>"
  29741. + "Total textures: " + scene.textures.length + "<br>"
  29742. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29743. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29744. + "Active bones: " + scene.getActiveBones() + "<br>"
  29745. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29746. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29747. + "<b>Duration</b><br>"
  29748. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29749. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29750. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29751. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29752. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29753. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29754. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29755. + "</div>"
  29756. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29757. + "<b>Extensions</b><br>"
  29758. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29759. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29760. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29761. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29762. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29763. + "<b>Caps.</b><br>"
  29764. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29765. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29766. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29767. + "</div><br>"
  29768. + "<b>Info</b><br>"
  29769. + glInfo.version + "<br>"
  29770. + glInfo.renderer + "<br>";
  29771. if (this.customStatsFunction) {
  29772. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29773. }
  29774. };
  29775. return DebugLayer;
  29776. })();
  29777. BABYLON.DebugLayer = DebugLayer;
  29778. })(BABYLON || (BABYLON = {}));
  29779. //# sourceMappingURL=babylon.debugLayer.js.map
  29780. var BABYLON;
  29781. (function (BABYLON) {
  29782. var RawTexture = (function (_super) {
  29783. __extends(RawTexture, _super);
  29784. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29785. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29786. if (invertY === void 0) { invertY = false; }
  29787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29788. _super.call(this, null, scene, !generateMipMaps, invertY);
  29789. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29790. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29791. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29792. }
  29793. // Statics
  29794. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29796. if (invertY === void 0) { invertY = false; }
  29797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29798. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29799. };
  29800. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29802. if (invertY === void 0) { invertY = false; }
  29803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29804. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29805. };
  29806. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29807. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29808. if (invertY === void 0) { invertY = false; }
  29809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29810. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29811. };
  29812. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29813. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29814. if (invertY === void 0) { invertY = false; }
  29815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29816. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29817. };
  29818. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29819. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29820. if (invertY === void 0) { invertY = false; }
  29821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29822. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29823. };
  29824. return RawTexture;
  29825. })(BABYLON.Texture);
  29826. BABYLON.RawTexture = RawTexture;
  29827. })(BABYLON || (BABYLON = {}));
  29828. //# sourceMappingURL=babylon.rawTexture.js.map
  29829. var BABYLON;
  29830. (function (BABYLON) {
  29831. var IndexedVector2 = (function (_super) {
  29832. __extends(IndexedVector2, _super);
  29833. function IndexedVector2(original, index) {
  29834. _super.call(this, original.x, original.y);
  29835. this.index = index;
  29836. }
  29837. return IndexedVector2;
  29838. })(BABYLON.Vector2);
  29839. var PolygonPoints = (function () {
  29840. function PolygonPoints() {
  29841. this.elements = new Array();
  29842. }
  29843. PolygonPoints.prototype.add = function (originalPoints) {
  29844. var _this = this;
  29845. var result = new Array();
  29846. originalPoints.forEach(function (point) {
  29847. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29848. var newPoint = new IndexedVector2(point, _this.elements.length);
  29849. result.push(newPoint);
  29850. _this.elements.push(newPoint);
  29851. }
  29852. });
  29853. return result;
  29854. };
  29855. PolygonPoints.prototype.computeBounds = function () {
  29856. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29857. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29858. this.elements.forEach(function (point) {
  29859. // x
  29860. if (point.x < lmin.x) {
  29861. lmin.x = point.x;
  29862. }
  29863. else if (point.x > lmax.x) {
  29864. lmax.x = point.x;
  29865. }
  29866. // y
  29867. if (point.y < lmin.y) {
  29868. lmin.y = point.y;
  29869. }
  29870. else if (point.y > lmax.y) {
  29871. lmax.y = point.y;
  29872. }
  29873. });
  29874. return {
  29875. min: lmin,
  29876. max: lmax,
  29877. width: lmax.x - lmin.x,
  29878. height: lmax.y - lmin.y
  29879. };
  29880. };
  29881. return PolygonPoints;
  29882. })();
  29883. var Polygon = (function () {
  29884. function Polygon() {
  29885. }
  29886. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29887. return [
  29888. new BABYLON.Vector2(xmin, ymin),
  29889. new BABYLON.Vector2(xmax, ymin),
  29890. new BABYLON.Vector2(xmax, ymax),
  29891. new BABYLON.Vector2(xmin, ymax)
  29892. ];
  29893. };
  29894. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29895. if (cx === void 0) { cx = 0; }
  29896. if (cy === void 0) { cy = 0; }
  29897. if (numberOfSides === void 0) { numberOfSides = 32; }
  29898. var result = new Array();
  29899. var angle = 0;
  29900. var increment = (Math.PI * 2) / numberOfSides;
  29901. for (var i = 0; i < numberOfSides; i++) {
  29902. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29903. angle -= increment;
  29904. }
  29905. return result;
  29906. };
  29907. Polygon.Parse = function (input) {
  29908. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29909. var i, result = [];
  29910. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29911. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  29912. }
  29913. return result;
  29914. };
  29915. Polygon.StartingAt = function (x, y) {
  29916. return BABYLON.Path2.StartingAt(x, y);
  29917. };
  29918. return Polygon;
  29919. })();
  29920. BABYLON.Polygon = Polygon;
  29921. var PolygonMeshBuilder = (function () {
  29922. function PolygonMeshBuilder(name, contours, scene) {
  29923. this._points = new PolygonPoints();
  29924. this._outlinepoints = new PolygonPoints();
  29925. this._holes = [];
  29926. if (!("poly2tri" in window)) {
  29927. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29928. }
  29929. this._name = name;
  29930. this._scene = scene;
  29931. var points;
  29932. if (contours instanceof BABYLON.Path2) {
  29933. points = contours.getPoints();
  29934. }
  29935. else {
  29936. points = contours;
  29937. }
  29938. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29939. this._outlinepoints.add(points);
  29940. }
  29941. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29942. this._swctx.addHole(this._points.add(hole));
  29943. var holepoints = new PolygonPoints();
  29944. holepoints.add(hole);
  29945. this._holes.push(holepoints);
  29946. return this;
  29947. };
  29948. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  29949. var _this = this;
  29950. if (updatable === void 0) { updatable = false; }
  29951. var result = new BABYLON.Mesh(this._name, this._scene);
  29952. var normals = [];
  29953. var positions = [];
  29954. var uvs = [];
  29955. var bounds = this._points.computeBounds();
  29956. this._points.elements.forEach(function (p) {
  29957. normals.push(0, 1.0, 0);
  29958. positions.push(p.x, 0, p.y);
  29959. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29960. });
  29961. var indices = [];
  29962. this._swctx.triangulate();
  29963. this._swctx.getTriangles().forEach(function (triangle) {
  29964. triangle.getPoints().forEach(function (point) {
  29965. indices.push(point.index);
  29966. });
  29967. });
  29968. if (depth > 0) {
  29969. var positionscount = (positions.length / 3); //get the current pointcount
  29970. this._points.elements.forEach(function (p) {
  29971. normals.push(0, -1.0, 0);
  29972. positions.push(p.x, -depth, p.y);
  29973. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  29974. });
  29975. var p1; //we need to change order of point so the triangles are made in the rigth way.
  29976. var p2;
  29977. var poscounter = 0;
  29978. this._swctx.getTriangles().forEach(function (triangle) {
  29979. triangle.getPoints().forEach(function (point) {
  29980. switch (poscounter) {
  29981. case 0:
  29982. p1 = point;
  29983. break;
  29984. case 1:
  29985. p2 = point;
  29986. break;
  29987. case 2:
  29988. indices.push(point.index + positionscount);
  29989. indices.push(p2.index + positionscount);
  29990. indices.push(p1.index + positionscount);
  29991. poscounter = -1;
  29992. break;
  29993. }
  29994. poscounter++;
  29995. //indices.push((<IndexedVector2>point).index + positionscount);
  29996. });
  29997. });
  29998. //Add the sides
  29999. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30000. this._holes.forEach(function (hole) {
  30001. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30002. });
  30003. }
  30004. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30005. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30006. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30007. result.setIndices(indices);
  30008. return result;
  30009. };
  30010. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30011. var StartIndex = positions.length / 3;
  30012. var ulength = 0;
  30013. for (var i = 0; i < points.elements.length; i++) {
  30014. var p = points.elements[i];
  30015. var p1;
  30016. if ((i + 1) > points.elements.length - 1) {
  30017. p1 = points.elements[0];
  30018. }
  30019. else {
  30020. p1 = points.elements[i + 1];
  30021. }
  30022. positions.push(p.x, 0, p.y);
  30023. positions.push(p.x, -depth, p.y);
  30024. positions.push(p1.x, 0, p1.y);
  30025. positions.push(p1.x, -depth, p1.y);
  30026. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30027. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30028. var v3 = v2.subtract(v1);
  30029. var v4 = new BABYLON.Vector3(0, 1, 0);
  30030. var vn = BABYLON.Vector3.Cross(v3, v4);
  30031. vn = vn.normalize();
  30032. uvs.push(ulength / bounds.width, 0);
  30033. uvs.push(ulength / bounds.width, 1);
  30034. ulength += v3.length();
  30035. uvs.push((ulength / bounds.width), 0);
  30036. uvs.push((ulength / bounds.width), 1);
  30037. if (!flip) {
  30038. normals.push(-vn.x, -vn.y, -vn.z);
  30039. normals.push(-vn.x, -vn.y, -vn.z);
  30040. normals.push(-vn.x, -vn.y, -vn.z);
  30041. normals.push(-vn.x, -vn.y, -vn.z);
  30042. indices.push(StartIndex);
  30043. indices.push(StartIndex + 1);
  30044. indices.push(StartIndex + 2);
  30045. indices.push(StartIndex + 1);
  30046. indices.push(StartIndex + 3);
  30047. indices.push(StartIndex + 2);
  30048. }
  30049. else {
  30050. normals.push(vn.x, vn.y, vn.z);
  30051. normals.push(vn.x, vn.y, vn.z);
  30052. normals.push(vn.x, vn.y, vn.z);
  30053. normals.push(vn.x, vn.y, vn.z);
  30054. indices.push(StartIndex);
  30055. indices.push(StartIndex + 2);
  30056. indices.push(StartIndex + 1);
  30057. indices.push(StartIndex + 1);
  30058. indices.push(StartIndex + 2);
  30059. indices.push(StartIndex + 3);
  30060. }
  30061. StartIndex += 4;
  30062. }
  30063. ;
  30064. };
  30065. return PolygonMeshBuilder;
  30066. })();
  30067. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30068. })(BABYLON || (BABYLON = {}));
  30069. //# sourceMappingURL=babylon.polygonMesh.js.map
  30070. var BABYLON;
  30071. (function (BABYLON) {
  30072. var SimplificationSettings = (function () {
  30073. function SimplificationSettings(quality, distance, optimizeMesh) {
  30074. this.quality = quality;
  30075. this.distance = distance;
  30076. this.optimizeMesh = optimizeMesh;
  30077. }
  30078. return SimplificationSettings;
  30079. })();
  30080. BABYLON.SimplificationSettings = SimplificationSettings;
  30081. var SimplificationQueue = (function () {
  30082. function SimplificationQueue() {
  30083. this.running = false;
  30084. this._simplificationArray = [];
  30085. }
  30086. SimplificationQueue.prototype.addTask = function (task) {
  30087. this._simplificationArray.push(task);
  30088. };
  30089. SimplificationQueue.prototype.executeNext = function () {
  30090. var task = this._simplificationArray.pop();
  30091. if (task) {
  30092. this.running = true;
  30093. this.runSimplification(task);
  30094. }
  30095. else {
  30096. this.running = false;
  30097. }
  30098. };
  30099. SimplificationQueue.prototype.runSimplification = function (task) {
  30100. var _this = this;
  30101. if (task.parallelProcessing) {
  30102. //parallel simplifier
  30103. task.settings.forEach(function (setting) {
  30104. var simplifier = _this.getSimplifier(task);
  30105. simplifier.simplify(setting, function (newMesh) {
  30106. task.mesh.addLODLevel(setting.distance, newMesh);
  30107. newMesh.isVisible = true;
  30108. //check if it is the last
  30109. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30110. //all done, run the success callback.
  30111. task.successCallback();
  30112. }
  30113. _this.executeNext();
  30114. });
  30115. });
  30116. }
  30117. else {
  30118. //single simplifier.
  30119. var simplifier = this.getSimplifier(task);
  30120. var runDecimation = function (setting, callback) {
  30121. simplifier.simplify(setting, function (newMesh) {
  30122. task.mesh.addLODLevel(setting.distance, newMesh);
  30123. newMesh.isVisible = true;
  30124. //run the next quality level
  30125. callback();
  30126. });
  30127. };
  30128. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30129. runDecimation(task.settings[loop.index], function () {
  30130. loop.executeNext();
  30131. });
  30132. }, function () {
  30133. //execution ended, run the success callback.
  30134. if (task.successCallback) {
  30135. task.successCallback();
  30136. }
  30137. _this.executeNext();
  30138. });
  30139. }
  30140. };
  30141. SimplificationQueue.prototype.getSimplifier = function (task) {
  30142. switch (task.simplificationType) {
  30143. case SimplificationType.QUADRATIC:
  30144. default:
  30145. return new QuadraticErrorSimplification(task.mesh);
  30146. }
  30147. };
  30148. return SimplificationQueue;
  30149. })();
  30150. BABYLON.SimplificationQueue = SimplificationQueue;
  30151. /**
  30152. * The implemented types of simplification.
  30153. * At the moment only Quadratic Error Decimation is implemented.
  30154. */
  30155. (function (SimplificationType) {
  30156. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30157. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30158. var SimplificationType = BABYLON.SimplificationType;
  30159. var DecimationTriangle = (function () {
  30160. function DecimationTriangle(vertices) {
  30161. this.vertices = vertices;
  30162. this.error = new Array(4);
  30163. this.deleted = false;
  30164. this.isDirty = false;
  30165. this.deletePending = false;
  30166. this.borderFactor = 0;
  30167. }
  30168. return DecimationTriangle;
  30169. })();
  30170. BABYLON.DecimationTriangle = DecimationTriangle;
  30171. var DecimationVertex = (function () {
  30172. function DecimationVertex(position, id) {
  30173. this.position = position;
  30174. this.id = id;
  30175. this.isBorder = true;
  30176. this.q = new QuadraticMatrix();
  30177. this.triangleCount = 0;
  30178. this.triangleStart = 0;
  30179. this.originalOffsets = [];
  30180. }
  30181. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30182. this.position.copyFrom(newPosition);
  30183. };
  30184. return DecimationVertex;
  30185. })();
  30186. BABYLON.DecimationVertex = DecimationVertex;
  30187. var QuadraticMatrix = (function () {
  30188. function QuadraticMatrix(data) {
  30189. this.data = new Array(10);
  30190. for (var i = 0; i < 10; ++i) {
  30191. if (data && data[i]) {
  30192. this.data[i] = data[i];
  30193. }
  30194. else {
  30195. this.data[i] = 0;
  30196. }
  30197. }
  30198. }
  30199. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30200. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30201. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30202. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30203. return det;
  30204. };
  30205. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30206. for (var i = 0; i < 10; ++i) {
  30207. this.data[i] += matrix.data[i];
  30208. }
  30209. };
  30210. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30211. for (var i = 0; i < 10; ++i) {
  30212. this.data[i] += data[i];
  30213. }
  30214. };
  30215. QuadraticMatrix.prototype.add = function (matrix) {
  30216. var m = new QuadraticMatrix();
  30217. for (var i = 0; i < 10; ++i) {
  30218. m.data[i] = this.data[i] + matrix.data[i];
  30219. }
  30220. return m;
  30221. };
  30222. QuadraticMatrix.FromData = function (a, b, c, d) {
  30223. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30224. };
  30225. //returning an array to avoid garbage collection
  30226. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30227. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30228. };
  30229. return QuadraticMatrix;
  30230. })();
  30231. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30232. var Reference = (function () {
  30233. function Reference(vertexId, triangleId) {
  30234. this.vertexId = vertexId;
  30235. this.triangleId = triangleId;
  30236. }
  30237. return Reference;
  30238. })();
  30239. BABYLON.Reference = Reference;
  30240. /**
  30241. * An implementation of the Quadratic Error simplification algorithm.
  30242. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30243. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30244. * @author RaananW
  30245. */
  30246. var QuadraticErrorSimplification = (function () {
  30247. function QuadraticErrorSimplification(_mesh) {
  30248. this._mesh = _mesh;
  30249. this.initialized = false;
  30250. this.syncIterations = 5000;
  30251. this.aggressiveness = 7;
  30252. this.decimationIterations = 100;
  30253. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30254. }
  30255. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30256. var _this = this;
  30257. this.initDecimatedMesh();
  30258. //iterating through the submeshes array, one after the other.
  30259. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30260. _this.initWithMesh(loop.index, function () {
  30261. _this.runDecimation(settings, loop.index, function () {
  30262. loop.executeNext();
  30263. });
  30264. }, settings.optimizeMesh);
  30265. }, function () {
  30266. setTimeout(function () {
  30267. successCallback(_this._reconstructedMesh);
  30268. }, 0);
  30269. });
  30270. };
  30271. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30272. var _this = this;
  30273. var gCount = 0;
  30274. triangle.vertices.forEach(function (vertex) {
  30275. var count = 0;
  30276. var vPos = vertex.position;
  30277. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30278. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30279. ++count;
  30280. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30281. ++count;
  30282. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30283. ++count;
  30284. if (count > 1) {
  30285. ++gCount;
  30286. }
  30287. ;
  30288. });
  30289. if (gCount > 1) {
  30290. console.log(triangle, gCount);
  30291. }
  30292. return gCount > 1;
  30293. };
  30294. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30295. var _this = this;
  30296. var targetCount = ~~(this.triangles.length * settings.quality);
  30297. var deletedTriangles = 0;
  30298. var triangleCount = this.triangles.length;
  30299. var iterationFunction = function (iteration, callback) {
  30300. setTimeout(function () {
  30301. if (iteration % 5 === 0) {
  30302. _this.updateMesh(iteration === 0);
  30303. }
  30304. for (var i = 0; i < _this.triangles.length; ++i) {
  30305. _this.triangles[i].isDirty = false;
  30306. }
  30307. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30308. var trianglesIterator = function (i) {
  30309. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30310. var t = _this.triangles[tIdx];
  30311. if (!t)
  30312. return;
  30313. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30314. return;
  30315. }
  30316. for (var j = 0; j < 3; ++j) {
  30317. if (t.error[j] < threshold) {
  30318. var deleted0 = [];
  30319. var deleted1 = [];
  30320. var v0 = t.vertices[j];
  30321. var v1 = t.vertices[(j + 1) % 3];
  30322. if (v0.isBorder !== v1.isBorder)
  30323. continue;
  30324. var p = BABYLON.Vector3.Zero();
  30325. var n = BABYLON.Vector3.Zero();
  30326. var uv = BABYLON.Vector2.Zero();
  30327. var color = new BABYLON.Color4(0, 0, 0, 1);
  30328. _this.calculateError(v0, v1, p, n, uv, color);
  30329. var delTr = [];
  30330. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30331. continue;
  30332. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30333. continue;
  30334. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30335. continue;
  30336. var uniqueArray = [];
  30337. delTr.forEach(function (deletedT) {
  30338. if (uniqueArray.indexOf(deletedT) === -1) {
  30339. deletedT.deletePending = true;
  30340. uniqueArray.push(deletedT);
  30341. }
  30342. });
  30343. if (uniqueArray.length % 2 != 0) {
  30344. continue;
  30345. }
  30346. v0.q = v1.q.add(v0.q);
  30347. v0.updatePosition(p);
  30348. var tStart = _this.references.length;
  30349. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30350. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30351. var tCount = _this.references.length - tStart;
  30352. if (tCount <= v0.triangleCount) {
  30353. if (tCount) {
  30354. for (var c = 0; c < tCount; c++) {
  30355. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30356. }
  30357. }
  30358. }
  30359. else {
  30360. v0.triangleStart = tStart;
  30361. }
  30362. v0.triangleCount = tCount;
  30363. break;
  30364. }
  30365. }
  30366. };
  30367. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30368. }, 0);
  30369. };
  30370. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30371. if (triangleCount - deletedTriangles <= targetCount)
  30372. loop.breakLoop();
  30373. else {
  30374. iterationFunction(loop.index, function () {
  30375. loop.executeNext();
  30376. });
  30377. }
  30378. }, function () {
  30379. setTimeout(function () {
  30380. //reconstruct this part of the mesh
  30381. _this.reconstructMesh(submeshIndex);
  30382. successCallback();
  30383. }, 0);
  30384. });
  30385. };
  30386. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30387. var _this = this;
  30388. this.vertices = [];
  30389. this.triangles = [];
  30390. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30391. var indices = this._mesh.getIndices();
  30392. var submesh = this._mesh.subMeshes[submeshIndex];
  30393. var findInVertices = function (positionToSearch) {
  30394. if (optimizeMesh) {
  30395. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30396. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30397. return _this.vertices[ii];
  30398. }
  30399. }
  30400. }
  30401. return null;
  30402. };
  30403. var vertexReferences = [];
  30404. var vertexInit = function (i) {
  30405. var offset = i + submesh.verticesStart;
  30406. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30407. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30408. vertex.originalOffsets.push(offset);
  30409. if (vertex.id == _this.vertices.length) {
  30410. _this.vertices.push(vertex);
  30411. }
  30412. vertexReferences.push(vertex.id);
  30413. };
  30414. //var totalVertices = mesh.getTotalVertices();
  30415. var totalVertices = submesh.verticesCount;
  30416. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30417. var indicesInit = function (i) {
  30418. var offset = (submesh.indexStart / 3) + i;
  30419. var pos = (offset * 3);
  30420. var i0 = indices[pos + 0];
  30421. var i1 = indices[pos + 1];
  30422. var i2 = indices[pos + 2];
  30423. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30424. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30425. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30426. var triangle = new DecimationTriangle([v0, v1, v2]);
  30427. triangle.originalOffset = pos;
  30428. _this.triangles.push(triangle);
  30429. };
  30430. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30431. _this.init(callback);
  30432. });
  30433. });
  30434. };
  30435. QuadraticErrorSimplification.prototype.init = function (callback) {
  30436. var _this = this;
  30437. var triangleInit1 = function (i) {
  30438. var t = _this.triangles[i];
  30439. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30440. for (var j = 0; j < 3; j++) {
  30441. 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))));
  30442. }
  30443. };
  30444. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30445. var triangleInit2 = function (i) {
  30446. var t = _this.triangles[i];
  30447. for (var j = 0; j < 3; ++j) {
  30448. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30449. }
  30450. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30451. };
  30452. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30453. _this.initialized = true;
  30454. callback();
  30455. });
  30456. });
  30457. };
  30458. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30459. var newTriangles = [];
  30460. var i;
  30461. for (i = 0; i < this.vertices.length; ++i) {
  30462. this.vertices[i].triangleCount = 0;
  30463. }
  30464. var t;
  30465. var j;
  30466. for (i = 0; i < this.triangles.length; ++i) {
  30467. if (!this.triangles[i].deleted) {
  30468. t = this.triangles[i];
  30469. for (j = 0; j < 3; ++j) {
  30470. t.vertices[j].triangleCount = 1;
  30471. }
  30472. newTriangles.push(t);
  30473. }
  30474. }
  30475. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30476. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30477. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30478. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30479. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30480. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30481. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30482. var vertexCount = 0;
  30483. for (i = 0; i < this.vertices.length; ++i) {
  30484. var vertex = this.vertices[i];
  30485. vertex.id = vertexCount;
  30486. if (vertex.triangleCount) {
  30487. vertex.originalOffsets.forEach(function (originalOffset) {
  30488. newPositionData.push(vertex.position.x);
  30489. newPositionData.push(vertex.position.y);
  30490. newPositionData.push(vertex.position.z);
  30491. newNormalData.push(normalData[originalOffset * 3]);
  30492. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30493. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30494. if (uvs && uvs.length) {
  30495. newUVsData.push(uvs[(originalOffset * 2)]);
  30496. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30497. }
  30498. else if (colorsData && colorsData.length) {
  30499. newColorsData.push(colorsData[(originalOffset * 4)]);
  30500. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30501. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30502. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30503. }
  30504. ++vertexCount;
  30505. });
  30506. }
  30507. }
  30508. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30509. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30510. var submeshesArray = this._reconstructedMesh.subMeshes;
  30511. this._reconstructedMesh.subMeshes = [];
  30512. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30513. var originalIndices = this._mesh.getIndices();
  30514. for (i = 0; i < newTriangles.length; ++i) {
  30515. var t = newTriangles[i];
  30516. //now get the new referencing point for each vertex
  30517. [0, 1, 2].forEach(function (idx) {
  30518. var id = originalIndices[t.originalOffset + idx];
  30519. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30520. if (offset < 0)
  30521. offset = 0;
  30522. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30523. });
  30524. }
  30525. //overwriting the old vertex buffers and indices.
  30526. this._reconstructedMesh.setIndices(newIndicesArray);
  30527. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30528. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30529. if (newUVsData.length > 0)
  30530. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30531. if (newColorsData.length > 0)
  30532. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30533. //create submesh
  30534. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30535. if (submeshIndex > 0) {
  30536. this._reconstructedMesh.subMeshes = [];
  30537. submeshesArray.forEach(function (submesh) {
  30538. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30539. });
  30540. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30541. }
  30542. };
  30543. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30544. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30545. this._reconstructedMesh.material = this._mesh.material;
  30546. this._reconstructedMesh.parent = this._mesh.parent;
  30547. this._reconstructedMesh.isVisible = false;
  30548. };
  30549. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30550. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30551. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30552. if (t.deleted)
  30553. continue;
  30554. var s = this.references[vertex1.triangleStart + i].vertexId;
  30555. var v1 = t.vertices[(s + 1) % 3];
  30556. var v2 = t.vertices[(s + 2) % 3];
  30557. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30558. deletedArray[i] = true;
  30559. delTr.push(t);
  30560. continue;
  30561. }
  30562. var d1 = v1.position.subtract(point);
  30563. d1 = d1.normalize();
  30564. var d2 = v2.position.subtract(point);
  30565. d2 = d2.normalize();
  30566. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30567. return true;
  30568. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30569. deletedArray[i] = false;
  30570. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30571. return true;
  30572. }
  30573. return false;
  30574. };
  30575. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30576. var newDeleted = deletedTriangles;
  30577. for (var i = 0; i < vertex.triangleCount; ++i) {
  30578. var ref = this.references[vertex.triangleStart + i];
  30579. var t = this.triangles[ref.triangleId];
  30580. if (t.deleted)
  30581. continue;
  30582. if (deletedArray[i] && t.deletePending) {
  30583. t.deleted = true;
  30584. newDeleted++;
  30585. continue;
  30586. }
  30587. t.vertices[ref.vertexId] = origVertex;
  30588. t.isDirty = true;
  30589. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30590. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30591. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30592. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30593. this.references.push(ref);
  30594. }
  30595. return newDeleted;
  30596. };
  30597. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30598. for (var i = 0; i < this.vertices.length; ++i) {
  30599. var vCount = [];
  30600. var vId = [];
  30601. var v = this.vertices[i];
  30602. var j;
  30603. for (j = 0; j < v.triangleCount; ++j) {
  30604. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30605. for (var ii = 0; ii < 3; ii++) {
  30606. var ofs = 0;
  30607. var vv = triangle.vertices[ii];
  30608. while (ofs < vCount.length) {
  30609. if (vId[ofs] === vv.id)
  30610. break;
  30611. ++ofs;
  30612. }
  30613. if (ofs === vCount.length) {
  30614. vCount.push(1);
  30615. vId.push(vv.id);
  30616. }
  30617. else {
  30618. vCount[ofs]++;
  30619. }
  30620. }
  30621. }
  30622. for (j = 0; j < vCount.length; ++j) {
  30623. if (vCount[j] === 1) {
  30624. this.vertices[vId[j]].isBorder = true;
  30625. }
  30626. else {
  30627. this.vertices[vId[j]].isBorder = false;
  30628. }
  30629. }
  30630. }
  30631. };
  30632. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30633. if (identifyBorders === void 0) { identifyBorders = false; }
  30634. var i;
  30635. if (!identifyBorders) {
  30636. var newTrianglesVector = [];
  30637. for (i = 0; i < this.triangles.length; ++i) {
  30638. if (!this.triangles[i].deleted) {
  30639. newTrianglesVector.push(this.triangles[i]);
  30640. }
  30641. }
  30642. this.triangles = newTrianglesVector;
  30643. }
  30644. for (i = 0; i < this.vertices.length; ++i) {
  30645. this.vertices[i].triangleCount = 0;
  30646. this.vertices[i].triangleStart = 0;
  30647. }
  30648. var t;
  30649. var j;
  30650. var v;
  30651. for (i = 0; i < this.triangles.length; ++i) {
  30652. t = this.triangles[i];
  30653. for (j = 0; j < 3; ++j) {
  30654. v = t.vertices[j];
  30655. v.triangleCount++;
  30656. }
  30657. }
  30658. var tStart = 0;
  30659. for (i = 0; i < this.vertices.length; ++i) {
  30660. this.vertices[i].triangleStart = tStart;
  30661. tStart += this.vertices[i].triangleCount;
  30662. this.vertices[i].triangleCount = 0;
  30663. }
  30664. var newReferences = new Array(this.triangles.length * 3);
  30665. for (i = 0; i < this.triangles.length; ++i) {
  30666. t = this.triangles[i];
  30667. for (j = 0; j < 3; ++j) {
  30668. v = t.vertices[j];
  30669. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30670. v.triangleCount++;
  30671. }
  30672. }
  30673. this.references = newReferences;
  30674. if (identifyBorders) {
  30675. this.identifyBorder();
  30676. }
  30677. };
  30678. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30679. var x = point.x;
  30680. var y = point.y;
  30681. var z = point.z;
  30682. 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
  30683. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30684. };
  30685. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30686. var q = vertex1.q.add(vertex2.q);
  30687. var border = vertex1.isBorder && vertex2.isBorder;
  30688. var error = 0;
  30689. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30690. if (qDet !== 0 && !border) {
  30691. if (!pointResult) {
  30692. pointResult = BABYLON.Vector3.Zero();
  30693. }
  30694. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30695. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30696. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30697. error = this.vertexError(q, pointResult);
  30698. }
  30699. else {
  30700. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30701. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30702. var error1 = this.vertexError(q, vertex1.position);
  30703. var error2 = this.vertexError(q, vertex2.position);
  30704. var error3 = this.vertexError(q, p3);
  30705. error = Math.min(error1, error2, error3);
  30706. if (error === error1) {
  30707. if (pointResult) {
  30708. pointResult.copyFrom(vertex1.position);
  30709. }
  30710. }
  30711. else if (error === error2) {
  30712. if (pointResult) {
  30713. pointResult.copyFrom(vertex2.position);
  30714. }
  30715. }
  30716. else {
  30717. if (pointResult) {
  30718. pointResult.copyFrom(p3);
  30719. }
  30720. }
  30721. }
  30722. return error;
  30723. };
  30724. return QuadraticErrorSimplification;
  30725. })();
  30726. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30727. })(BABYLON || (BABYLON = {}));
  30728. //# sourceMappingURL=babylon.meshSimplification.js.map
  30729. var BABYLON;
  30730. (function (BABYLON) {
  30731. var Analyser = (function () {
  30732. function Analyser(scene) {
  30733. this.SMOOTHING = 0.75;
  30734. this.FFT_SIZE = 512;
  30735. this.BARGRAPHAMPLITUDE = 256;
  30736. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30737. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30738. this._scene = scene;
  30739. this._audioEngine = BABYLON.Engine.audioEngine;
  30740. if (this._audioEngine.canUseWebAudio) {
  30741. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30742. this._webAudioAnalyser.minDecibels = -140;
  30743. this._webAudioAnalyser.maxDecibels = 0;
  30744. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30745. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30746. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30747. }
  30748. }
  30749. Analyser.prototype.getFrequencyBinCount = function () {
  30750. if (this._audioEngine.canUseWebAudio) {
  30751. return this._webAudioAnalyser.frequencyBinCount;
  30752. }
  30753. else {
  30754. return 0;
  30755. }
  30756. };
  30757. Analyser.prototype.getByteFrequencyData = function () {
  30758. if (this._audioEngine.canUseWebAudio) {
  30759. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30760. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30761. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30762. }
  30763. return this._byteFreqs;
  30764. };
  30765. Analyser.prototype.getByteTimeDomainData = function () {
  30766. if (this._audioEngine.canUseWebAudio) {
  30767. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30768. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30769. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30770. }
  30771. return this._byteTime;
  30772. };
  30773. Analyser.prototype.getFloatFrequencyData = function () {
  30774. if (this._audioEngine.canUseWebAudio) {
  30775. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30776. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30777. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30778. }
  30779. return this._floatFreqs;
  30780. };
  30781. Analyser.prototype.drawDebugCanvas = function () {
  30782. var _this = this;
  30783. if (this._audioEngine.canUseWebAudio) {
  30784. if (!this._debugCanvas) {
  30785. this._debugCanvas = document.createElement("canvas");
  30786. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30787. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30788. this._debugCanvas.style.position = "absolute";
  30789. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30790. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30791. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30792. document.body.appendChild(this._debugCanvas);
  30793. this._registerFunc = function () {
  30794. _this.drawDebugCanvas();
  30795. };
  30796. this._scene.registerBeforeRender(this._registerFunc);
  30797. }
  30798. if (this._registerFunc) {
  30799. var workingArray = this.getByteFrequencyData();
  30800. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30801. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30802. // Draw the frequency domain chart.
  30803. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30804. var value = workingArray[i];
  30805. var percent = value / this.BARGRAPHAMPLITUDE;
  30806. var height = this.DEBUGCANVASSIZE.height * percent;
  30807. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30808. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30809. var hue = i / this.getFrequencyBinCount() * 360;
  30810. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30811. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30812. }
  30813. }
  30814. }
  30815. };
  30816. Analyser.prototype.stopDebugCanvas = function () {
  30817. if (this._debugCanvas) {
  30818. this._scene.unregisterBeforeRender(this._registerFunc);
  30819. this._registerFunc = null;
  30820. document.body.removeChild(this._debugCanvas);
  30821. this._debugCanvas = null;
  30822. this._debugCanvasContext = null;
  30823. }
  30824. };
  30825. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30826. if (this._audioEngine.canUseWebAudio) {
  30827. inputAudioNode.connect(this._webAudioAnalyser);
  30828. this._webAudioAnalyser.connect(outputAudioNode);
  30829. }
  30830. };
  30831. Analyser.prototype.dispose = function () {
  30832. if (this._audioEngine.canUseWebAudio) {
  30833. this._webAudioAnalyser.disconnect();
  30834. }
  30835. };
  30836. return Analyser;
  30837. })();
  30838. BABYLON.Analyser = Analyser;
  30839. })(BABYLON || (BABYLON = {}));
  30840. //# sourceMappingURL=babylon.analyser.js.map
  30841. var BABYLON;
  30842. (function (BABYLON) {
  30843. var DepthRenderer = (function () {
  30844. function DepthRenderer(scene, type) {
  30845. var _this = this;
  30846. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30847. this._viewMatrix = BABYLON.Matrix.Zero();
  30848. this._projectionMatrix = BABYLON.Matrix.Zero();
  30849. this._transformMatrix = BABYLON.Matrix.Zero();
  30850. this._worldViewProjection = BABYLON.Matrix.Zero();
  30851. this._scene = scene;
  30852. var engine = scene.getEngine();
  30853. // Render target
  30854. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30855. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30856. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30857. this._depthMap.refreshRate = 1;
  30858. this._depthMap.renderParticles = false;
  30859. this._depthMap.renderList = null;
  30860. // set default depth value to 1.0 (far away)
  30861. this._depthMap.onClear = function (engine) {
  30862. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30863. };
  30864. // Custom render function
  30865. var renderSubMesh = function (subMesh) {
  30866. var mesh = subMesh.getRenderingMesh();
  30867. var scene = _this._scene;
  30868. var engine = scene.getEngine();
  30869. // Culling
  30870. engine.setState(subMesh.getMaterial().backFaceCulling);
  30871. // Managing instances
  30872. var batch = mesh._getInstancesRenderList(subMesh._id);
  30873. if (batch.mustReturn) {
  30874. return;
  30875. }
  30876. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30877. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30878. engine.enableEffect(_this._effect);
  30879. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30880. var material = subMesh.getMaterial();
  30881. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30882. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30883. // Alpha test
  30884. if (material && material.needAlphaTesting()) {
  30885. var alphaTexture = material.getAlphaTestTexture();
  30886. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30887. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30888. }
  30889. // Bones
  30890. if (mesh.useBones) {
  30891. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30892. }
  30893. // Draw
  30894. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30895. }
  30896. };
  30897. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30898. var index;
  30899. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30900. renderSubMesh(opaqueSubMeshes.data[index]);
  30901. }
  30902. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30903. renderSubMesh(alphaTestSubMeshes.data[index]);
  30904. }
  30905. };
  30906. }
  30907. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30908. var defines = [];
  30909. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30910. var mesh = subMesh.getMesh();
  30911. var scene = mesh.getScene();
  30912. var material = subMesh.getMaterial();
  30913. // Alpha test
  30914. if (material && material.needAlphaTesting()) {
  30915. defines.push("#define ALPHATEST");
  30916. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30917. attribs.push(BABYLON.VertexBuffer.UVKind);
  30918. defines.push("#define UV1");
  30919. }
  30920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30921. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30922. defines.push("#define UV2");
  30923. }
  30924. }
  30925. // Bones
  30926. if (mesh.useBones) {
  30927. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30928. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30929. defines.push("#define BONES");
  30930. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30931. }
  30932. // Instances
  30933. if (useInstances) {
  30934. defines.push("#define INSTANCES");
  30935. attribs.push("world0");
  30936. attribs.push("world1");
  30937. attribs.push("world2");
  30938. attribs.push("world3");
  30939. }
  30940. // Get correct effect
  30941. var join = defines.join("\n");
  30942. if (this._cachedDefines !== join) {
  30943. this._cachedDefines = join;
  30944. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30945. }
  30946. return this._effect.isReady();
  30947. };
  30948. DepthRenderer.prototype.getDepthMap = function () {
  30949. return this._depthMap;
  30950. };
  30951. // Methods
  30952. DepthRenderer.prototype.dispose = function () {
  30953. this._depthMap.dispose();
  30954. };
  30955. return DepthRenderer;
  30956. })();
  30957. BABYLON.DepthRenderer = DepthRenderer;
  30958. })(BABYLON || (BABYLON = {}));
  30959. //# sourceMappingURL=babylon.depthRenderer.js.map
  30960. var BABYLON;
  30961. (function (BABYLON) {
  30962. var SSAORenderingPipeline = (function (_super) {
  30963. __extends(SSAORenderingPipeline, _super);
  30964. /**
  30965. * @constructor
  30966. * @param {string} name - The rendering pipeline name
  30967. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30968. * @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 }
  30969. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30970. */
  30971. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30972. var _this = this;
  30973. _super.call(this, scene.getEngine(), name);
  30974. // Members
  30975. /**
  30976. * The PassPostProcess id in the pipeline that contains the original scene color
  30977. * @type {string}
  30978. */
  30979. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30980. /**
  30981. * The SSAO PostProcess id in the pipeline
  30982. * @type {string}
  30983. */
  30984. this.SSAORenderEffect = "SSAORenderEffect";
  30985. /**
  30986. * The horizontal blur PostProcess id in the pipeline
  30987. * @type {string}
  30988. */
  30989. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30990. /**
  30991. * The vertical blur PostProcess id in the pipeline
  30992. * @type {string}
  30993. */
  30994. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30995. /**
  30996. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30997. * @type {string}
  30998. */
  30999. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31000. /**
  31001. * The output strength of the SSAO post-process. Default value is 1.0.
  31002. * @type {number}
  31003. */
  31004. this.totalStrength = 1.0;
  31005. /**
  31006. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31007. * @type {number}
  31008. */
  31009. this.radius = 0.0002;
  31010. /**
  31011. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31012. * Must not be equal to fallOff and superior to fallOff.
  31013. * Default value is 0.0075
  31014. * @type {number}
  31015. */
  31016. this.area = 0.0075;
  31017. /**
  31018. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31019. * Must not be equal to area and inferior to area.
  31020. * Default value is 0.0002
  31021. * @type {number}
  31022. */
  31023. this.fallOff = 0.0002;
  31024. this._firstUpdate = true;
  31025. this._scene = scene;
  31026. // Set up assets
  31027. this._createRandomTexture();
  31028. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31029. var ssaoRatio = ratio.ssaoRatio || ratio;
  31030. var combineRatio = ratio.combineRatio || ratio;
  31031. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31032. this._createSSAOPostProcess(ssaoRatio);
  31033. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31034. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31035. this._createSSAOCombinePostProcess(combineRatio);
  31036. // Set up pipeline
  31037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31042. // Finish
  31043. scene.postProcessRenderPipelineManager.addPipeline(this);
  31044. if (cameras)
  31045. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31046. }
  31047. // Public Methods
  31048. /**
  31049. * Returns the horizontal blur PostProcess
  31050. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31051. */
  31052. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31053. return this._blurHPostProcess;
  31054. };
  31055. /**
  31056. * Returns the vertical blur PostProcess
  31057. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31058. */
  31059. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31060. return this._blurVPostProcess;
  31061. };
  31062. /**
  31063. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31064. */
  31065. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31066. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31067. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31068. this._originalColorPostProcess = undefined;
  31069. this._ssaoPostProcess = undefined;
  31070. this._blurHPostProcess = undefined;
  31071. this._blurVPostProcess = undefined;
  31072. this._ssaoCombinePostProcess = undefined;
  31073. this._randomTexture.dispose();
  31074. if (disableDepthRender)
  31075. this._scene.disableDepthRenderer();
  31076. };
  31077. // Private Methods
  31078. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31079. var _this = this;
  31080. var sampleSphere = [
  31081. 0.5381, 0.1856, -0.4319,
  31082. 0.1379, 0.2486, 0.4430,
  31083. 0.3371, 0.5679, -0.0057,
  31084. -0.6999, -0.0451, -0.0019,
  31085. 0.0689, -0.1598, -0.8547,
  31086. 0.0560, 0.0069, -0.1843,
  31087. -0.0146, 0.1402, 0.0762,
  31088. 0.0100, -0.1924, -0.0344,
  31089. -0.3577, -0.5301, -0.4358,
  31090. -0.3169, 0.1063, 0.0158,
  31091. 0.0103, -0.5869, 0.0046,
  31092. -0.0897, -0.4940, 0.3287,
  31093. 0.7119, -0.0154, -0.0918,
  31094. -0.0533, 0.0596, -0.5411,
  31095. 0.0352, -0.0631, 0.5460,
  31096. -0.4776, 0.2847, -0.0271
  31097. ];
  31098. var samplesFactor = 1.0 / 16.0;
  31099. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31100. this._ssaoPostProcess.onApply = function (effect) {
  31101. if (_this._firstUpdate) {
  31102. effect.setArray3("sampleSphere", sampleSphere);
  31103. effect.setFloat("samplesFactor", samplesFactor);
  31104. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31105. _this._firstUpdate = false;
  31106. }
  31107. effect.setFloat("totalStrength", _this.totalStrength);
  31108. effect.setFloat("radius", _this.radius);
  31109. effect.setFloat("area", _this.area);
  31110. effect.setFloat("fallOff", _this.fallOff);
  31111. effect.setTexture("textureSampler", _this._depthTexture);
  31112. effect.setTexture("randomSampler", _this._randomTexture);
  31113. };
  31114. };
  31115. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31116. var _this = this;
  31117. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31118. this._ssaoCombinePostProcess.onApply = function (effect) {
  31119. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31120. };
  31121. };
  31122. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31123. var size = 512;
  31124. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31125. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31126. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31127. var context = this._randomTexture.getContext();
  31128. var rand = function (min, max) {
  31129. return Math.random() * (max - min) + min;
  31130. };
  31131. for (var x = 0; x < size; x++) {
  31132. for (var y = 0; y < size; y++) {
  31133. var randVector = BABYLON.Vector3.Zero();
  31134. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31135. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31136. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31137. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31138. context.fillRect(x, y, 1, 1);
  31139. }
  31140. }
  31141. this._randomTexture.update(false);
  31142. };
  31143. return SSAORenderingPipeline;
  31144. })(BABYLON.PostProcessRenderPipeline);
  31145. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31146. })(BABYLON || (BABYLON = {}));
  31147. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31148. var BABYLON;
  31149. (function (BABYLON) {
  31150. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31151. var VolumetricLightScatteringPostProcess = (function (_super) {
  31152. __extends(VolumetricLightScatteringPostProcess, _super);
  31153. /**
  31154. * @constructor
  31155. * @param {string} name - The post-process name
  31156. * @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)
  31157. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31158. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31159. * @param {number} samples - The post-process quality, default 100
  31160. * @param {number} samplingMode - The post-process filtering mode
  31161. * @param {BABYLON.Engine} engine - The babylon engine
  31162. * @param {boolean} reusable - If the post-process is reusable
  31163. */
  31164. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31165. var _this = this;
  31166. if (samples === void 0) { samples = 100; }
  31167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31168. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31169. this._screenCoordinates = BABYLON.Vector2.Zero();
  31170. /**
  31171. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31172. * @type {boolean}
  31173. */
  31174. this.useCustomMeshPosition = false;
  31175. /**
  31176. * If the post-process should inverse the light scattering direction
  31177. * @type {boolean}
  31178. */
  31179. this.invert = true;
  31180. /**
  31181. * Array containing the excluded meshes not rendered in the internal pass
  31182. */
  31183. this.excludedMeshes = new Array();
  31184. this.exposure = 0.3;
  31185. this.decay = 0.96815;
  31186. this.weight = 0.58767;
  31187. this.density = 0.926;
  31188. var scene = camera.getScene();
  31189. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31190. // Configure mesh
  31191. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31192. // Configure
  31193. this._createPass(scene, ratio.passRatio || ratio);
  31194. this.onApply = function (effect) {
  31195. _this._updateMeshScreenCoordinates(scene);
  31196. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31197. effect.setFloat("exposure", _this.exposure);
  31198. effect.setFloat("decay", _this.decay);
  31199. effect.setFloat("weight", _this.weight);
  31200. effect.setFloat("density", _this.density);
  31201. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31202. };
  31203. }
  31204. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31205. var mesh = subMesh.getMesh();
  31206. var defines = [];
  31207. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31208. var material = subMesh.getMaterial();
  31209. var needUV = false;
  31210. // Render this.mesh as default
  31211. if (mesh === this.mesh) {
  31212. defines.push("#define BASIC_RENDER");
  31213. defines.push("#define NEED_UV");
  31214. needUV = true;
  31215. }
  31216. // Alpha test
  31217. if (material) {
  31218. if (material.needAlphaTesting() || mesh === this.mesh)
  31219. defines.push("#define ALPHATEST");
  31220. if (material.opacityTexture !== undefined) {
  31221. defines.push("#define OPACITY");
  31222. if (material.opacityTexture.getAlphaFromRGB)
  31223. defines.push("#define OPACITYRGB");
  31224. if (!needUV)
  31225. defines.push("#define NEED_UV");
  31226. }
  31227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31228. attribs.push(BABYLON.VertexBuffer.UVKind);
  31229. defines.push("#define UV1");
  31230. }
  31231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31232. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31233. defines.push("#define UV2");
  31234. }
  31235. }
  31236. // Bones
  31237. if (mesh.useBones) {
  31238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31240. defines.push("#define BONES");
  31241. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31242. }
  31243. // Instances
  31244. if (useInstances) {
  31245. defines.push("#define INSTANCES");
  31246. attribs.push("world0");
  31247. attribs.push("world1");
  31248. attribs.push("world2");
  31249. attribs.push("world3");
  31250. }
  31251. // Get correct effect
  31252. var join = defines.join("\n");
  31253. if (this._cachedDefines !== join) {
  31254. this._cachedDefines = join;
  31255. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31256. }
  31257. return this._volumetricLightScatteringPass.isReady();
  31258. };
  31259. /**
  31260. * Sets the new light position for light scattering effect
  31261. * @param {BABYLON.Vector3} The new custom light position
  31262. */
  31263. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31264. this._customMeshPosition = position;
  31265. };
  31266. /**
  31267. * Returns the light position for light scattering effect
  31268. * @return {BABYLON.Vector3} The custom light position
  31269. */
  31270. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31271. return this._customMeshPosition;
  31272. };
  31273. /**
  31274. * Disposes the internal assets and detaches the post-process from the camera
  31275. */
  31276. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31277. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31278. if (rttIndex !== -1) {
  31279. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31280. }
  31281. this._volumetricLightScatteringRTT.dispose();
  31282. _super.prototype.dispose.call(this, camera);
  31283. };
  31284. /**
  31285. * Returns the render target texture used by the post-process
  31286. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31287. */
  31288. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31289. return this._volumetricLightScatteringRTT;
  31290. };
  31291. // Private methods
  31292. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31293. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31294. return true;
  31295. }
  31296. return false;
  31297. };
  31298. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31299. var _this = this;
  31300. var engine = scene.getEngine();
  31301. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31302. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31303. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31304. this._volumetricLightScatteringRTT.renderList = null;
  31305. this._volumetricLightScatteringRTT.renderParticles = false;
  31306. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31307. // Custom render function for submeshes
  31308. var renderSubMesh = function (subMesh) {
  31309. var mesh = subMesh.getRenderingMesh();
  31310. if (_this._meshExcluded(mesh)) {
  31311. return;
  31312. }
  31313. var scene = mesh.getScene();
  31314. var engine = scene.getEngine();
  31315. // Culling
  31316. engine.setState(subMesh.getMaterial().backFaceCulling);
  31317. // Managing instances
  31318. var batch = mesh._getInstancesRenderList(subMesh._id);
  31319. if (batch.mustReturn) {
  31320. return;
  31321. }
  31322. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31323. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31324. engine.enableEffect(_this._volumetricLightScatteringPass);
  31325. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31326. var material = subMesh.getMaterial();
  31327. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31328. // Alpha test
  31329. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31330. var alphaTexture = material.getAlphaTestTexture();
  31331. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31332. if (alphaTexture) {
  31333. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31334. }
  31335. if (material.opacityTexture !== undefined) {
  31336. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31337. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31338. }
  31339. }
  31340. // Bones
  31341. if (mesh.useBones) {
  31342. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31343. }
  31344. // Draw
  31345. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31346. }
  31347. };
  31348. // Render target texture callbacks
  31349. var savedSceneClearColor;
  31350. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31351. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31352. savedSceneClearColor = scene.clearColor;
  31353. scene.clearColor = sceneClearColor;
  31354. };
  31355. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31356. scene.clearColor = savedSceneClearColor;
  31357. };
  31358. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31359. var engine = scene.getEngine();
  31360. var index;
  31361. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31362. renderSubMesh(opaqueSubMeshes.data[index]);
  31363. }
  31364. engine.setAlphaTesting(true);
  31365. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31366. renderSubMesh(alphaTestSubMeshes.data[index]);
  31367. }
  31368. engine.setAlphaTesting(false);
  31369. if (transparentSubMeshes.length) {
  31370. // Sort sub meshes
  31371. for (index = 0; index < transparentSubMeshes.length; index++) {
  31372. var submesh = transparentSubMeshes.data[index];
  31373. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31374. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31375. }
  31376. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31377. sortedArray.sort(function (a, b) {
  31378. // Alpha index first
  31379. if (a._alphaIndex > b._alphaIndex) {
  31380. return 1;
  31381. }
  31382. if (a._alphaIndex < b._alphaIndex) {
  31383. return -1;
  31384. }
  31385. // Then distance to camera
  31386. if (a._distanceToCamera < b._distanceToCamera) {
  31387. return 1;
  31388. }
  31389. if (a._distanceToCamera > b._distanceToCamera) {
  31390. return -1;
  31391. }
  31392. return 0;
  31393. });
  31394. // Render sub meshes
  31395. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31396. for (index = 0; index < sortedArray.length; index++) {
  31397. renderSubMesh(sortedArray[index]);
  31398. }
  31399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31400. }
  31401. };
  31402. };
  31403. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31404. var transform = scene.getTransformMatrix();
  31405. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31406. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31407. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31408. if (this.invert)
  31409. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31410. };
  31411. // Static methods
  31412. /**
  31413. * Creates a default mesh for the Volumeric Light Scattering post-process
  31414. * @param {string} The mesh name
  31415. * @param {BABYLON.Scene} The scene where to create the mesh
  31416. * @return {BABYLON.Mesh} the default mesh
  31417. */
  31418. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31419. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31420. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31421. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31422. return mesh;
  31423. };
  31424. return VolumetricLightScatteringPostProcess;
  31425. })(BABYLON.PostProcess);
  31426. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31427. })(BABYLON || (BABYLON = {}));
  31428. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31429. var BABYLON;
  31430. (function (BABYLON) {
  31431. var LensRenderingPipeline = (function (_super) {
  31432. __extends(LensRenderingPipeline, _super);
  31433. /**
  31434. * @constructor
  31435. *
  31436. * Effect parameters are as follow:
  31437. * {
  31438. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31439. * edge_blur: number; // from 0 to x (1 for realism)
  31440. * distortion: number; // from 0 to x (1 for realism)
  31441. * grain_amount: number; // from 0 to 1
  31442. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31443. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31444. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31445. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31446. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31447. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31448. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31449. * }
  31450. * Note: if an effect parameter is unset, effect is disabled
  31451. *
  31452. * @param {string} name - The rendering pipeline name
  31453. * @param {object} parameters - An object containing all parameters (see above)
  31454. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31455. * @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)
  31456. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31457. */
  31458. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31459. var _this = this;
  31460. if (ratio === void 0) { ratio = 1.0; }
  31461. _super.call(this, scene.getEngine(), name);
  31462. // Lens effects can be of the following:
  31463. // - chromatic aberration (slight shift of RGB colors)
  31464. // - blur on the edge of the lens
  31465. // - lens distortion
  31466. // - depth-of-field blur & highlights enhancing
  31467. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31468. // - grain effect (noise or custom texture)
  31469. // Two additional texture samplers are needed:
  31470. // - depth map (for depth-of-field)
  31471. // - grain texture
  31472. /**
  31473. * The chromatic aberration PostProcess id in the pipeline
  31474. * @type {string}
  31475. */
  31476. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31477. /**
  31478. * The highlights enhancing PostProcess id in the pipeline
  31479. * @type {string}
  31480. */
  31481. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31482. /**
  31483. * The depth-of-field PostProcess id in the pipeline
  31484. * @type {string}
  31485. */
  31486. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31487. this._scene = scene;
  31488. // Fetch texture samplers
  31489. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31490. if (parameters.grain_texture) {
  31491. this._grainTexture = parameters.grain_texture;
  31492. }
  31493. else {
  31494. this._createGrainTexture();
  31495. }
  31496. // save parameters
  31497. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31498. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31499. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31500. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31501. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31502. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31503. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31504. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31505. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31506. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31507. // Create effects
  31508. this._createChromaticAberrationPostProcess(ratio);
  31509. this._createHighlightsPostProcess(ratio);
  31510. this._createDepthOfFieldPostProcess(ratio);
  31511. // Set up pipeline
  31512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31514. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31515. if (this._highlightsGain == -1) {
  31516. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31517. }
  31518. // Finish
  31519. scene.postProcessRenderPipelineManager.addPipeline(this);
  31520. if (cameras) {
  31521. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31522. }
  31523. }
  31524. // public methods (self explanatory)
  31525. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31526. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31527. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31528. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31529. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31530. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31531. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31532. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31533. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31534. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31535. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31536. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31537. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31538. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31539. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31540. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31541. this._highlightsGain = amount;
  31542. };
  31543. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31544. if (this._highlightsGain == -1) {
  31545. this._highlightsGain = 1.0;
  31546. }
  31547. this._highlightsThreshold = amount;
  31548. };
  31549. LensRenderingPipeline.prototype.disableHighlights = function () {
  31550. this._highlightsGain = -1;
  31551. };
  31552. /**
  31553. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31554. */
  31555. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31556. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31557. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31558. this._chromaticAberrationPostProcess = undefined;
  31559. this._highlightsPostProcess = undefined;
  31560. this._depthOfFieldPostProcess = undefined;
  31561. this._grainTexture.dispose();
  31562. if (disableDepthRender)
  31563. this._scene.disableDepthRenderer();
  31564. };
  31565. // colors shifting and distortion
  31566. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31567. var _this = this;
  31568. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31569. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31570. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31571. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31572. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31573. };
  31574. };
  31575. // highlights enhancing
  31576. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31577. var _this = this;
  31578. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31579. this._highlightsPostProcess.onApply = function (effect) {
  31580. effect.setFloat('gain', _this._highlightsGain);
  31581. effect.setFloat('threshold', _this._highlightsThreshold);
  31582. effect.setBool('pentagon', _this._dofPentagon);
  31583. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31584. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31585. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31586. };
  31587. };
  31588. // colors shifting and distortion
  31589. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31590. var _this = this;
  31591. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31592. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31593. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31594. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31595. this._depthOfFieldPostProcess.onApply = function (effect) {
  31596. effect.setBool('blur_noise', _this._blurNoise);
  31597. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31598. effect.setFloat('grain_amount', _this._grainAmount);
  31599. effect.setTexture("depthSampler", _this._depthTexture);
  31600. effect.setTexture("grainSampler", _this._grainTexture);
  31601. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31602. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31603. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31604. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31605. effect.setFloat('distortion', _this._distortion);
  31606. effect.setFloat('focus_depth', _this._dofDepth);
  31607. effect.setFloat('aperture', _this._dofAperture);
  31608. effect.setFloat('edge_blur', _this._edgeBlur);
  31609. effect.setBool('highlights', (_this._highlightsGain != -1));
  31610. };
  31611. };
  31612. // creates a black and white random noise texture, 512x512
  31613. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31614. var size = 512;
  31615. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31616. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31617. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31618. var context = this._grainTexture.getContext();
  31619. var rand = function (min, max) {
  31620. return Math.random() * (max - min) + min;
  31621. };
  31622. var value;
  31623. for (var x = 0; x < size; x++) {
  31624. for (var y = 0; y < size; y++) {
  31625. value = Math.floor(rand(0.42, 0.58) * 255);
  31626. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31627. context.fillRect(x, y, 1, 1);
  31628. }
  31629. }
  31630. this._grainTexture.update(false);
  31631. };
  31632. return LensRenderingPipeline;
  31633. })(BABYLON.PostProcessRenderPipeline);
  31634. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31635. })(BABYLON || (BABYLON = {}));
  31636. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31637. //
  31638. // This post-process allows the modification of rendered colors by using
  31639. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31640. //
  31641. // The object needs to be provided an url to a texture containing the color
  31642. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31643. // Use an image editing software to tweak the LUT to match your needs.
  31644. //
  31645. // For an example of a color LUT, see here:
  31646. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31647. // For explanations on color grading, see here:
  31648. // http://udn.epicgames.com/Three/ColorGrading.html
  31649. //
  31650. var BABYLON;
  31651. (function (BABYLON) {
  31652. var ColorCorrectionPostProcess = (function (_super) {
  31653. __extends(ColorCorrectionPostProcess, _super);
  31654. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31655. var _this = this;
  31656. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31657. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31658. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31659. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31660. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31661. this.onApply = function (effect) {
  31662. effect.setTexture("colorTable", _this._colorTableTexture);
  31663. };
  31664. }
  31665. return ColorCorrectionPostProcess;
  31666. })(BABYLON.PostProcess);
  31667. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31668. })(BABYLON || (BABYLON = {}));
  31669. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31670. var BABYLON;
  31671. (function (BABYLON) {
  31672. var StereoscopicFreeCamera = (function (_super) {
  31673. __extends(StereoscopicFreeCamera, _super);
  31674. function StereoscopicFreeCamera(name, position, eyeSpace, isVertical, scene) {
  31675. _super.call(this, name, position, scene);
  31676. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31677. }
  31678. return StereoscopicFreeCamera;
  31679. })(BABYLON.FreeCamera);
  31680. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  31681. var StereoscopicArcRotateCamera = (function (_super) {
  31682. __extends(StereoscopicArcRotateCamera, _super);
  31683. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  31684. _super.call(this, name, alpha, beta, radius, target, scene);
  31685. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31686. }
  31687. return StereoscopicArcRotateCamera;
  31688. })(BABYLON.ArcRotateCamera);
  31689. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  31690. var StereoscopicGamepadCamera = (function (_super) {
  31691. __extends(StereoscopicGamepadCamera, _super);
  31692. function StereoscopicGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  31693. _super.call(this, name, position, scene);
  31694. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31695. }
  31696. return StereoscopicGamepadCamera;
  31697. })(BABYLON.GamepadCamera);
  31698. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  31699. })(BABYLON || (BABYLON = {}));
  31700. //# sourceMappingURL=babylon.stereoscopicCamera.js.map
  31701. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  31702. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},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()}return 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 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=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?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},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||0>V)return;0>h&&(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 m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,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(f,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(f,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(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(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),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(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),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(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;s>c;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.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=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){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?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);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!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;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.id))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;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;a>t;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){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,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(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,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.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.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 i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.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 Int32Array(o.getIndices()||[])}},t}();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);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._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){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},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,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},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,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.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},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},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,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,r){return new t(i/255,o/255,r/255)},t.Lerp=function(i,o,r){var n=i.r+(o.r-i.r)*r,s=i.g+(o.g-i.g)*r,e=i.b+(o.b-i.b)*r;return new t(n,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,r){this.r=t,this.g=i,this.b=o,this.a=r}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.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},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.Lerp=function(i,o,r){var n=new t(0,0,0,0);return t.LerpToRef(i,o,r,n),n},t.LerpToRef=function(t,i,o,r){r.r=t.r+(i.r-t.r)*o,r.g=t.g+(i.g-t.g)*o,r.b=t.b+(i.b-t.b)*o,r.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,r,n){return new t(i/255,o/255,r/255,n/255)},t}();t.Color4=o;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a);return new i(h,u)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;return s=s>r.y?r.y:s,s=s<o.y?o.y:s,new i(n,s)},i.Hermite=function(t,o,r,n,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m;return new i(f,x)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r;return new i(n,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var r=t.x<o.x?t.x:o.x,n=t.y<o.y?t.y:o.y;return new i(r,n)},i.Maximize=function(t,o){var r=t.x>o.x?t.x:o.x,n=t.y>o.y?t.y:o.y;return new i(r,n)},i.Transform=function(t,o){var r=t.x*o.m[0]+t.y*o.m[4],n=t.x*o.m[1]+t.y*o.m[5];return new i(r,n)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,r=t.y-i.y;return o*o+r*r},i}();t.Vector2=r;var n=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.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},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=r*a,t.y=-n*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.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},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.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},i.prototype.subtractFromFloats=function(t,o,r){return new i(this.x-t,this.y-o,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)&&t.Tools.WithinEpsilon(this.z,i.z)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.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},i.prototype.multiplyByFloats=function(t,o,r){return new i(this.x*t,this.y*o,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.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},i.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},i.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},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.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},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,r,n){var s=i.Dot(t,r)-n,e=i.Dot(o,r)-n,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,r){r.x=t,r.y=i,r.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var r=i.Zero();return i.TransformCoordinatesToRef(t,o,r),r},i.TransformCoordinatesToRef=function(t,i,o){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],n=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=r/e,o.y=n/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,r,n){var s=t*r.m[0]+i*r.m[4]+o*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+o*r.m[9]+r.m[13],a=t*r.m[2]+i*r.m[6]+o*r.m[10]+r.m[14],h=t*r.m[3]+i*r.m[7]+o*r.m[11]+r.m[15];n.x=s/h,n.y=e/h,n.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var r=SIMD.float32x4.loadXYZ(t._data,0),n=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,0,0,0,0),n),SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,r,n){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(r.m,0),u=SIMD.float32x4.load(r.m,4),l=SIMD.float32x4.load(r.m,8),m=SIMD.float32x4.load(r.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(n._data,0,f)},i.TransformNormal=function(t,o){var r=i.Zero();return i.TransformNormalToRef(t,o,r),r},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,r,n){n.x=t*r.m[0]+i*r.m[4]+o*r.m[8],n.y=t*r.m[1]+i*r.m[5]+o*r.m[9],n.z=t*r.m[2]+i*r.m[6]+o*r.m[10]},i.CatmullRom=function(t,o,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a),l=.5*(2*o.z+(-t.z+r.z)*s+(2*t.z-5*o.z+4*r.z-n.z)*e+(-t.z+3*o.z-3*r.z+n.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;s=s>r.y?r.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<o.z?o.z:e,new i(n,s,e)},i.Hermite=function(t,o,r,n,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m,y=t.z*h+r.z*u+o.z*l+n.z*m;return new i(f,x,y)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r,e=t.z+(o.z-t.z)*r;return new i(n,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var r=i.Zero();return i.CrossToRef(t,o,r),r},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,r,n){var s=n.width,e=n.height,h=n.x,u=n.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(r).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,r,n,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,r,n,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*2-1);var u=i.TransformCoordinates(o,h),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,r=t.y-i.y,n=t.z-i.z;return o*o+r*r+n*n},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,r,n){var s,e,a,h=i.Normalize(o),u=(i.Normalize(r),i.Normalize(n)),l=f.X,m=f.Y,x=(f.Z,0),y=0,c=0,p=0,z=0,M=0,w=0,I=-1,d=(Math.PI,0),D=0;0==u.z?M=1:0==u.x?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),a=i.Cross(u,e),s=i.Cross(h,e),i.Dot(u,s)<0&&(I=1),D=i.Dot(h,e),c=Math.acos(D)*I,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),d++);var S,v;return p=0,z=0,M=0,I=-1,0==u.z?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new t.Vector3(p,z,M),v=t.Vector3.Cross(S,e),s=t.Vector3.Cross(u,S),t.Vector3.Dot(e,s)<0&&(I=1),D=t.Vector3.Dot(u,S),y=Math.acos(D)*I,t.Vector3.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),d++),I=-1,s=t.Vector3.Cross(l,e),t.Vector3.Dot(s,m)<0&&(I=1),D=t.Vector3.Dot(e,l),x=-Math.acos(D)*I,0>D&&2>d&&(x=Math.PI+x),new t.Vector3(y,x,c)},i}();t.Vector3=n;var s=function(){function i(t,i,o,r){this.x=t,this.y=i,this.z=o,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.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},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},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.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},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},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.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},i.prototype.subtractFromFloats=function(t,o,r,n){return new i(this.x-t,this.y-o,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,n.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},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.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,r){return this.x===t&&this.y===i&&this.z===o&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.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},i.prototype.multiplyByFloats=function(t,o,r,n){return new i(this.x*t,this.y*o,this.z*r,this.w*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.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},i.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},i.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},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.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.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},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,o,r){return this.x=t,this.y=i,this.z=o,this.w=r,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,r,n){n.x=t,n.y=i,n.z=o,n.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,r=t.y-i.y,n=t.z-i.z,s=t.w-i.w;return o*o+r*r+n*n+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=o,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,r){return this.x=t,this.y=i,this.z=o,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,n=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,r,n,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=n.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,r=this.z,n=this.w,s=i*o,e=i*r,a=n*o,h=n*r,u=n*i,l=o*r,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-r*r)):(t.x=Math.atan2(s-h,.5-f-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,r=this.z*this.z,n=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+r),t.m[1]=2*(n+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(n-s),t.m[5]=1-2*(r+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,r=t.m,n=r[0],s=r[4],e=r[8],a=r[1],h=r[5],u=r[9],l=r[2],m=r[6],f=r[10],x=n+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):n>h&&n>f?(o=2*Math.sqrt(1+n-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-n-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-n-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var r=new t,n=Math.sin(o/2);return r.w=Math.cos(o/2),r.x=i.x*n,r.y=i.y*n,r.z=i.z*n,r},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,r){var n=new t;return t.RotationYawPitchRollToRef(i,o,r,n),n},t.RotationYawPitchRollToRef=function(t,i,o,r){var n=.5*o,s=.5*i,e=.5*t,a=Math.sin(n),h=Math.cos(n),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);r.x=f*u*h+m*l*a,r.y=m*l*h-f*u*a,r.z=f*l*a-m*u*h,r.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,r){var n=new t;return t.RotationAlphaBetaGammaToRef(i,o,r,n),n},t.RotationAlphaBetaGammaToRef=function(t,i,o,r){var n=.5*(o+t),s=.5*(o-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(n)*Math.cos(e),r.w=Math.cos(n)*Math.cos(e)},t.Slerp=function(i,o,r){var n,s,e=r,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,n=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,n=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+n*o.x,s*i.y+n*o.y,s*i.z+n*o.z,s*i.w+n*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1: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]?!1:!0},i.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],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=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]*o)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*n+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],r=this.m[2],n=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,I=u*p-f*x,d=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*I+h*d),g=s*M-e*I+h*D,T=-(s*w-e*d+a*D),R=1/(i*S+o*v+r*g+n*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*m,q=e*f-h*l,V=e*m-a*l,E=s*f-h*u,Z=s*m-a*u,N=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-r*M+n*w)*R,t.m[5]=(i*z-r*I+n*d)*R,t.m[9]=-(i*M-o*I+n*D)*R,t.m[13]=(i*w-o*d+r*D)*R,t.m[2]=(o*_-r*b+n*A)*R,t.m[6]=-(i*_-r*F+n*P)*R,t.m[10]=(i*b-o*F+n*C)*R,t.m[14]=-(i*A-o*P+r*C)*R,t.m[3]=-(o*L-r*q+n*V)*R,t.m[7]=(i*L-r*E+n*Z)*R,t.m[11]=-(i*q-o*E+n*N)*R,t.m[15]=(i*V-o*Z+r*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,r,n,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),n=SIMD.float32x4.shuffle(c,p,2,3,6,7),r=SIMD.float32x4.shuffle(s,n,0,2,4,6),n=SIMD.float32x4.shuffle(n,s,1,3,5,7),s=SIMD.float32x4.mul(r,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),n),s=SIMD.float32x4.swizzle(s,1,0,3,2),r=SIMD.float32x4.swizzle(r,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(r,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var r=this.m[0],n=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],I=t.m[1],d=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=r*w+n*S+s*R+e*F,i[o+1]=r*I+n*v+s*_+e*P,i[o+2]=r*d+n*g+s*b+e*C,i[o+3]=r*D+n*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+l*F,i[o+5]=a*I+h*v+u*_+l*P,i[o+6]=a*d+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*A+l*L,i[o+8]=m*w+f*S+x*R+y*F,i[o+9]=m*I+f*v+x*_+y*P,i[o+10]=m*d+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*I+p*v+z*_+M*P,i[o+14]=c*d+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var r=this.m,n=t.m,s=SIMD.float32x4.load(n,0),e=SIMD.float32x4.load(n,4),a=SIMD.float32x4.load(n,8),h=SIMD.float32x4.load(n,12),u=SIMD.float32x4.load(r,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var l=SIMD.float32x4.load(r,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(r,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(r,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.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]},i.prototype.clone=function(){return i.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]);\n\n},i.prototype.decompose=function(o,r,n){n.x=this.m[12],n.y=this.m[13],n.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,o){var r=new i;return o||(o=0),i.FromArrayToRef(t,o,r),r},i.FromArrayToRef=function(t,i,o){for(var r=0;16>r;r++)o.m[r]=t[r+i]},i.FromValuesToRef=function(t,i,o,r,n,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=r,p.m[4]=n,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,r,n,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=r,z.m[3]=n,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,r){var n=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),n=n.multiply(s),n.setTranslation(r),n},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-o,i.m[6]=o,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.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-o,i.m[8]=o,i.m[10]=r,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.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=o,i.m[4]=-o,i.m[5]=r,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.RotationAxis=function(t,o){var r=Math.sin(-o),n=Math.cos(-o),s=1-n;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+n,e.m[1]=t.x*t.y*s-t.z*r,e.m[2]=t.x*t.z*s+t.y*r,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*r,e.m[5]=t.y*t.y*s+n,e.m[6]=t.y*t.z*s-t.x*r,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*r,e.m[9]=t.z*t.y*s+t.x*r,e.m[10]=t.z*t.z*s+n,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,r){var n=new i;return i.RotationYawPitchRollToRef(t,o,r,n),n},i.RotationYawPitchRollToRef=function(t,i,o,r){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,o,r){var n=i.Zero();return i.ScalingToRef(t,o,r,n),n},i.ScalingToRef=function(t,i,o,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=o,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,o,r){var n=i.Identity();return i.TranslationToRef(t,o,r,n),n},i.TranslationToRef=function(t,o,r,n){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,r,1,n)},i.LookAtLH=function(t,o,r){var n=i.Zero();return i.LookAtLHToRef(t,o,r,n),n},i.LookAtLHToRef=function(t,o,r,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),h=-n.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,r){var n=r.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),I=SIMD.float32x4(0,1,0,0),d=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(n,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(n,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(n,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(n,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,r,n){var s=i.Zero();return i.OrthoLHToRef(t,o,r,n,s),s},i.OrthoLHToRef=function(t,o,r,n,s){var e=2/t,a=2/o,h=1/(n-r),u=r/(r-n);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,r,n,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,r,n,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,r,n,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(n-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+o)/(o-r),e.m[14]=n/(n-s),e.m[15]=1},i.PerspectiveLH=function(t,o,r,n){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-n/(r-n),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n),s},i.PerspectiveFovLH=function(t,o,r,n){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,r,n,s),s},i.PerspectiveFovLHToRef=function(i,o,r,n,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-n/(r-n),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n)},i.GetFinalMatrix=function(t,o,r,n,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(r).multiply(n).multiply(m)},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,r=t.normal.y,n=t.normal.z,s=-2*o,e=-2*r,a=-2*n;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=a*r,i.m[7]=0,i.m[8]=s*n,i.m[9]=e*n,i.m[10]=a*n+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=n.Zero(),i._yAxis=n.Zero(),i._zAxis=n.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,r){this.normal=new n(t,i,o),this.d=r}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.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 o=a.Transpose(i),r=this.normal.x,n=this.normal.y,s=this.normal.z,e=this.d,h=r*o.m[0]+n*o.m[1]+s*o.m[2]+e*o.m[3],u=r*o.m[4]+n*o.m[5]+s*o.m[6]+e*o.m[7],l=r*o.m[8]+n*o.m[9]+s*o.m[10]+e*o.m[11],m=r*o.m[12]+n*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},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,o){var r,n=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-n*u,f=n*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return r=0!==x?1/x:0,this.normal.x=l*r,this.normal.y=m*r,this.normal.z=f*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=n.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return n.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,o,r){var n=new t(0,0,0,0);return n.copyFromPoints(i,o,r),n},t.FromPositionAndNormal=function(i,o){var r=new t(0,0,0,0);return o.normalize(),r.normal=o,r.d=-(o.x*i.x+o.y*i.y+o.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return n.Dot(o,i)+r},t}();t.Plane=h;var u=function(){function t(t,i,o,r){this.x=t,this.y=i,this.width=o,this.height=r}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*o,this.y*r,this.width*o,this.height*r)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],r=0;6>r;r++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},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[10]+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=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o=0,r=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var n=1/this.direction.x,s=(t.x-this.origin.x)*n,e=(i.x-this.origin.x)*n;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),r=Math.min(e,r),o>r)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,s=(t.y-this.origin.y)*n,e=(i.y-this.origin.y)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,s=(t.z-this.origin.z)*n,e=(i.z-this.origin.z)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,r=t.center.z-this.origin.z,n=i*i+o*o+r*r,s=t.radius*t.radius;if(s>=n)return!0;var e=i*this.direction.x+o*this.direction.y+r*this.direction.z;if(0>e)return!1;var a=n-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,r){this._edge1||(this._edge1=n.Zero(),this._edge2=n.Zero(),this._pvec=n.Zero(),this._tvec=n.Zero(),this._qvec=n.Zero()),o.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),n.CrossToRef(this.direction,this._edge2,this._pvec);var s=n.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=n.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;n.CrossToRef(this._tvec,this._edge1,this._qvec);var h=n.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=n.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,r,s,e,a,h){var u=n.Unproject(new n(t,o,0),r,s,e,a,h),l=n.Unproject(new n(t,o,1),r,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,r){void 0===r&&(r=a.Identity());var n=o.subtract(t),s=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z);return n.normalize(),i.Transform(new i(t,n,s),r)},i.Transform=function(t,o){var r=n.TransformCoordinates(t.origin,o),s=n.TransformNormal(t.direction,o);return new i(r,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new n(1,0,0),t.Y=new n(0,1,0),t.Z=new n(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,r,n){for(var s=1-3*r+3*i,e=3*r-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*n+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=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,o){var r=o.subtract(i),n=Math.atan2(r.y,r.x);return new t(n)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var n=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,e=(n-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new n(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var n=new r(i,o),s=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,n,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new r(i,o),u=new r(n,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var o=i*this.length(),n=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+n;if(o>=n&&l>=o){var m=u.normalize(),f=o-n;return new r(a.x+m.x*f,a.y+m.y*f)}n=l}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function t(t,i){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 o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],r=this._normalVector(this._curve[0],o,t);this._normals[0]=r,this._normals[0].normalize(),this._binormals[0]=n.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,l=1;i>l;l++)s=this._getLastNonNullVector(l),i-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=n.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=n.Cross(a,this._normals[l]),this._binormals[l].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0==o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},t.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0==o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},t.prototype._normalVector=function(t,i,o){var r;if(void 0===o||null===o){var s;1!==i.y?s=new n(0,-1,0):1!==i.x?s=new n(1,0,0):1!==i.z&&(s=new n(0,0,1)),r=n.Cross(i,s)}else r=n.Cross(i,o),n.CrossToRef(r,i,r);return r.normalize(),r},t}();t.Path3D=w;var I=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,r,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,r){var n=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*r;return n},h=0;s>=h;h++)e.push(new n(a(h/s,t.x,o.x,r.x),a(h/s,t.y,o.y,r.y),a(h/s,t.z,o.z,r.z)));return new i(e)},i.CreateCubicBezier=function(t,o,r,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,r,n){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*r+t*t*t*n;return s},u=0;e>=u;u++)a.push(new n(h(u/e,t.x,o.x,r.x,s.x),h(u/e,t.y,o.y,r.y,s.y),h(u/e,t.z,o.z,r.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,r,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,r,n,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),s=1;s<n.length;s++)r.push(n[s].subtract(n[0]).add(o));var e=new i(r);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=I;var d=function(){function t(t,i){void 0===t&&(t=n.Zero()),void 0===i&&(i=n.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var D=function(){function t(t,i,o){void 0===t&&(t=n.Zero()),void 0===i&&(i=n.Up()),void 0===o&&(o=r.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=n.TransformCoordinatesToRef,R=n.TransformCoordinatesFromFloatsToRef,_=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,n.TransformCoordinatesToRef=T,n.TransformCoordinatesFromFloatsToRef=R,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,n.TransformCoordinatesToRef=n.TransformCoordinatesToRefSIMD,n.TransformCoordinatesFromFloatsToRef=n.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";
  31703. if (window.module && module.exports) {
  31704. module.exports = BABYLON;
  31705. };