babylon.2.1-alpha.debug.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163
  1. var __extends = 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. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. 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);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. 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)
  1124. }
  1125. else {
  1126. 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)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. 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));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. 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]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. 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);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. 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);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var hw = 2.0 / width;
  1718. var hh = 2.0 / height;
  1719. var id = 1.0 / (zfar - znear);
  1720. var nid = znear / (znear - zfar);
  1721. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1722. };
  1723. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1724. var matrix = Matrix.Zero();
  1725. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1726. return matrix;
  1727. };
  1728. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1729. result.m[0] = 2.0 / (right - left);
  1730. result.m[1] = result.m[2] = result.m[3] = 0;
  1731. result.m[5] = 2.0 / (top - bottom);
  1732. result.m[4] = result.m[6] = result.m[7] = 0;
  1733. result.m[10] = -1.0 / (znear - zfar);
  1734. result.m[8] = result.m[9] = result.m[11] = 0;
  1735. result.m[12] = (left + right) / (left - right);
  1736. result.m[13] = (top + bottom) / (bottom - top);
  1737. result.m[14] = znear / (znear - zfar);
  1738. result.m[15] = 1.0;
  1739. };
  1740. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1741. var matrix = Matrix.Zero();
  1742. matrix.m[0] = (2.0 * znear) / width;
  1743. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1744. matrix.m[5] = (2.0 * znear) / height;
  1745. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1746. matrix.m[10] = -zfar / (znear - zfar);
  1747. matrix.m[8] = matrix.m[9] = 0.0;
  1748. matrix.m[11] = 1.0;
  1749. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1750. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1751. return matrix;
  1752. };
  1753. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1754. var matrix = Matrix.Zero();
  1755. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1759. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1760. var tan = 1.0 / (Math.tan(fov * 0.5));
  1761. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1762. if (v_fixed) {
  1763. result.m[0] = tan / aspect;
  1764. }
  1765. else {
  1766. result.m[0] = tan;
  1767. }
  1768. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1769. if (v_fixed) {
  1770. result.m[5] = tan;
  1771. }
  1772. else {
  1773. result.m[5] = tan * aspect;
  1774. }
  1775. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1776. result.m[8] = result.m[9] = 0.0;
  1777. result.m[10] = -zfar / (znear - zfar);
  1778. result.m[11] = 1.0;
  1779. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1780. result.m[14] = (znear * zfar) / (znear - zfar);
  1781. };
  1782. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1783. var cw = viewport.width;
  1784. var ch = viewport.height;
  1785. var cx = viewport.x;
  1786. var cy = viewport.y;
  1787. 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);
  1788. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1789. };
  1790. Matrix.Transpose = function (matrix) {
  1791. var result = new Matrix();
  1792. result.m[0] = matrix.m[0];
  1793. result.m[1] = matrix.m[4];
  1794. result.m[2] = matrix.m[8];
  1795. result.m[3] = matrix.m[12];
  1796. result.m[4] = matrix.m[1];
  1797. result.m[5] = matrix.m[5];
  1798. result.m[6] = matrix.m[9];
  1799. result.m[7] = matrix.m[13];
  1800. result.m[8] = matrix.m[2];
  1801. result.m[9] = matrix.m[6];
  1802. result.m[10] = matrix.m[10];
  1803. result.m[11] = matrix.m[14];
  1804. result.m[12] = matrix.m[3];
  1805. result.m[13] = matrix.m[7];
  1806. result.m[14] = matrix.m[11];
  1807. result.m[15] = matrix.m[15];
  1808. return result;
  1809. };
  1810. Matrix.Reflection = function (plane) {
  1811. var matrix = new Matrix();
  1812. Matrix.ReflectionToRef(plane, matrix);
  1813. return matrix;
  1814. };
  1815. Matrix.ReflectionToRef = function (plane, result) {
  1816. plane.normalize();
  1817. var x = plane.normal.x;
  1818. var y = plane.normal.y;
  1819. var z = plane.normal.z;
  1820. var temp = -2 * x;
  1821. var temp2 = -2 * y;
  1822. var temp3 = -2 * z;
  1823. result.m[0] = (temp * x) + 1;
  1824. result.m[1] = temp2 * x;
  1825. result.m[2] = temp3 * x;
  1826. result.m[3] = 0.0;
  1827. result.m[4] = temp * y;
  1828. result.m[5] = (temp2 * y) + 1;
  1829. result.m[6] = temp3 * y;
  1830. result.m[7] = 0.0;
  1831. result.m[8] = temp * z;
  1832. result.m[9] = temp2 * z;
  1833. result.m[10] = (temp3 * z) + 1;
  1834. result.m[11] = 0.0;
  1835. result.m[12] = temp * plane.d;
  1836. result.m[13] = temp2 * plane.d;
  1837. result.m[14] = temp3 * plane.d;
  1838. result.m[15] = 1.0;
  1839. };
  1840. Matrix._tempQuaternion = new Quaternion();
  1841. Matrix._xAxis = Vector3.Zero();
  1842. Matrix._yAxis = Vector3.Zero();
  1843. Matrix._zAxis = Vector3.Zero();
  1844. return Matrix;
  1845. })();
  1846. BABYLON.Matrix = Matrix;
  1847. var Plane = (function () {
  1848. function Plane(a, b, c, d) {
  1849. this.normal = new Vector3(a, b, c);
  1850. this.d = d;
  1851. }
  1852. Plane.prototype.asArray = function () {
  1853. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1854. };
  1855. // Methods
  1856. Plane.prototype.clone = function () {
  1857. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1858. };
  1859. Plane.prototype.normalize = function () {
  1860. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1861. var magnitude = 0;
  1862. if (norm !== 0) {
  1863. magnitude = 1.0 / norm;
  1864. }
  1865. this.normal.x *= magnitude;
  1866. this.normal.y *= magnitude;
  1867. this.normal.z *= magnitude;
  1868. this.d *= magnitude;
  1869. return this;
  1870. };
  1871. Plane.prototype.transform = function (transformation) {
  1872. var transposedMatrix = Matrix.Transpose(transformation);
  1873. var x = this.normal.x;
  1874. var y = this.normal.y;
  1875. var z = this.normal.z;
  1876. var d = this.d;
  1877. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1878. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1879. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1880. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1881. return new Plane(normalX, normalY, normalZ, finalD);
  1882. };
  1883. Plane.prototype.dotCoordinate = function (point) {
  1884. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1885. };
  1886. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1887. var x1 = point2.x - point1.x;
  1888. var y1 = point2.y - point1.y;
  1889. var z1 = point2.z - point1.z;
  1890. var x2 = point3.x - point1.x;
  1891. var y2 = point3.y - point1.y;
  1892. var z2 = point3.z - point1.z;
  1893. var yz = (y1 * z2) - (z1 * y2);
  1894. var xz = (z1 * x2) - (x1 * z2);
  1895. var xy = (x1 * y2) - (y1 * x2);
  1896. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1897. var invPyth;
  1898. if (pyth !== 0) {
  1899. invPyth = 1.0 / pyth;
  1900. }
  1901. else {
  1902. invPyth = 0;
  1903. }
  1904. this.normal.x = yz * invPyth;
  1905. this.normal.y = xz * invPyth;
  1906. this.normal.z = xy * invPyth;
  1907. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1908. return this;
  1909. };
  1910. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1911. var dot = Vector3.Dot(this.normal, direction);
  1912. return (dot <= epsilon);
  1913. };
  1914. Plane.prototype.signedDistanceTo = function (point) {
  1915. return Vector3.Dot(point, this.normal) + this.d;
  1916. };
  1917. // Statics
  1918. Plane.FromArray = function (array) {
  1919. return new Plane(array[0], array[1], array[2], array[3]);
  1920. };
  1921. Plane.FromPoints = function (point1, point2, point3) {
  1922. var result = new Plane(0, 0, 0, 0);
  1923. result.copyFromPoints(point1, point2, point3);
  1924. return result;
  1925. };
  1926. Plane.FromPositionAndNormal = function (origin, normal) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. normal.normalize();
  1929. result.normal = normal;
  1930. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1931. return result;
  1932. };
  1933. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1934. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1935. return Vector3.Dot(point, normal) + d;
  1936. };
  1937. return Plane;
  1938. })();
  1939. BABYLON.Plane = Plane;
  1940. var Viewport = (function () {
  1941. function Viewport(x, y, width, height) {
  1942. this.x = x;
  1943. this.y = y;
  1944. this.width = width;
  1945. this.height = height;
  1946. }
  1947. Viewport.prototype.toGlobal = function (engine) {
  1948. var width = engine.getRenderWidth();
  1949. var height = engine.getRenderHeight();
  1950. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1951. };
  1952. return Viewport;
  1953. })();
  1954. BABYLON.Viewport = Viewport;
  1955. var Frustum = (function () {
  1956. function Frustum() {
  1957. }
  1958. Frustum.GetPlanes = function (transform) {
  1959. var frustumPlanes = [];
  1960. for (var index = 0; index < 6; index++) {
  1961. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1962. }
  1963. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1964. return frustumPlanes;
  1965. };
  1966. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1967. // Near
  1968. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1969. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1970. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1971. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1972. frustumPlanes[0].normalize();
  1973. // Far
  1974. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1975. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1976. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1977. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1978. frustumPlanes[1].normalize();
  1979. // Left
  1980. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1981. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1982. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1983. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1984. frustumPlanes[2].normalize();
  1985. // Right
  1986. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1987. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1988. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1989. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1990. frustumPlanes[3].normalize();
  1991. // Top
  1992. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1993. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1994. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1995. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1996. frustumPlanes[4].normalize();
  1997. // Bottom
  1998. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1999. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2000. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2001. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2002. frustumPlanes[5].normalize();
  2003. };
  2004. return Frustum;
  2005. })();
  2006. BABYLON.Frustum = Frustum;
  2007. var Ray = (function () {
  2008. function Ray(origin, direction, length) {
  2009. if (length === void 0) { length = Number.MAX_VALUE; }
  2010. this.origin = origin;
  2011. this.direction = direction;
  2012. this.length = length;
  2013. }
  2014. // Methods
  2015. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2016. var d = 0.0;
  2017. var maxValue = Number.MAX_VALUE;
  2018. if (Math.abs(this.direction.x) < 0.0000001) {
  2019. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2020. return false;
  2021. }
  2022. }
  2023. else {
  2024. var inv = 1.0 / this.direction.x;
  2025. var min = (minimum.x - this.origin.x) * inv;
  2026. var max = (maximum.x - this.origin.x) * inv;
  2027. if (max === -Infinity) {
  2028. max = Infinity;
  2029. }
  2030. if (min > max) {
  2031. var temp = min;
  2032. min = max;
  2033. max = temp;
  2034. }
  2035. d = Math.max(min, d);
  2036. maxValue = Math.min(max, maxValue);
  2037. if (d > maxValue) {
  2038. return false;
  2039. }
  2040. }
  2041. if (Math.abs(this.direction.y) < 0.0000001) {
  2042. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2043. return false;
  2044. }
  2045. }
  2046. else {
  2047. inv = 1.0 / this.direction.y;
  2048. min = (minimum.y - this.origin.y) * inv;
  2049. max = (maximum.y - this.origin.y) * inv;
  2050. if (max === -Infinity) {
  2051. max = Infinity;
  2052. }
  2053. if (min > max) {
  2054. temp = min;
  2055. min = max;
  2056. max = temp;
  2057. }
  2058. d = Math.max(min, d);
  2059. maxValue = Math.min(max, maxValue);
  2060. if (d > maxValue) {
  2061. return false;
  2062. }
  2063. }
  2064. if (Math.abs(this.direction.z) < 0.0000001) {
  2065. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2066. return false;
  2067. }
  2068. }
  2069. else {
  2070. inv = 1.0 / this.direction.z;
  2071. min = (minimum.z - this.origin.z) * inv;
  2072. max = (maximum.z - this.origin.z) * inv;
  2073. if (max === -Infinity) {
  2074. max = Infinity;
  2075. }
  2076. if (min > max) {
  2077. temp = min;
  2078. min = max;
  2079. max = temp;
  2080. }
  2081. d = Math.max(min, d);
  2082. maxValue = Math.min(max, maxValue);
  2083. if (d > maxValue) {
  2084. return false;
  2085. }
  2086. }
  2087. return true;
  2088. };
  2089. Ray.prototype.intersectsBox = function (box) {
  2090. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2091. };
  2092. Ray.prototype.intersectsSphere = function (sphere) {
  2093. var x = sphere.center.x - this.origin.x;
  2094. var y = sphere.center.y - this.origin.y;
  2095. var z = sphere.center.z - this.origin.z;
  2096. var pyth = (x * x) + (y * y) + (z * z);
  2097. var rr = sphere.radius * sphere.radius;
  2098. if (pyth <= rr) {
  2099. return true;
  2100. }
  2101. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2102. if (dot < 0.0) {
  2103. return false;
  2104. }
  2105. var temp = pyth - (dot * dot);
  2106. return temp <= rr;
  2107. };
  2108. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2109. if (!this._edge1) {
  2110. this._edge1 = Vector3.Zero();
  2111. this._edge2 = Vector3.Zero();
  2112. this._pvec = Vector3.Zero();
  2113. this._tvec = Vector3.Zero();
  2114. this._qvec = Vector3.Zero();
  2115. }
  2116. vertex1.subtractToRef(vertex0, this._edge1);
  2117. vertex2.subtractToRef(vertex0, this._edge2);
  2118. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2119. var det = Vector3.Dot(this._edge1, this._pvec);
  2120. if (det === 0) {
  2121. return null;
  2122. }
  2123. var invdet = 1 / det;
  2124. this.origin.subtractToRef(vertex0, this._tvec);
  2125. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2126. if (bu < 0 || bu > 1.0) {
  2127. return null;
  2128. }
  2129. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2130. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2131. if (bv < 0 || bu + bv > 1.0) {
  2132. return null;
  2133. }
  2134. //check if the distance is longer than the predefined length.
  2135. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2136. if (distance > this.length) {
  2137. return null;
  2138. }
  2139. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2140. };
  2141. // Statics
  2142. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2143. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2144. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2145. var direction = end.subtract(start);
  2146. direction.normalize();
  2147. return new Ray(start, direction);
  2148. };
  2149. /**
  2150. * 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
  2151. * transformed to the given world matrix.
  2152. * @param origin The origin point
  2153. * @param end The end point
  2154. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2155. */
  2156. Ray.CreateNewFromTo = function (origin, end, world) {
  2157. if (world === void 0) { world = Matrix.Identity(); }
  2158. var direction = end.subtract(origin);
  2159. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2160. direction.normalize();
  2161. return Ray.Transform(new Ray(origin, direction, length), world);
  2162. };
  2163. Ray.Transform = function (ray, matrix) {
  2164. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2165. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2166. return new Ray(newOrigin, newDirection, ray.length);
  2167. };
  2168. return Ray;
  2169. })();
  2170. BABYLON.Ray = Ray;
  2171. (function (Space) {
  2172. Space[Space["LOCAL"] = 0] = "LOCAL";
  2173. Space[Space["WORLD"] = 1] = "WORLD";
  2174. })(BABYLON.Space || (BABYLON.Space = {}));
  2175. var Space = BABYLON.Space;
  2176. var Axis = (function () {
  2177. function Axis() {
  2178. }
  2179. Axis.X = new Vector3(1, 0, 0);
  2180. Axis.Y = new Vector3(0, 1, 0);
  2181. Axis.Z = new Vector3(0, 0, 1);
  2182. return Axis;
  2183. })();
  2184. BABYLON.Axis = Axis;
  2185. ;
  2186. var BezierCurve = (function () {
  2187. function BezierCurve() {
  2188. }
  2189. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2190. // Extract X (which is equal to time here)
  2191. var f0 = 1 - 3 * x2 + 3 * x1;
  2192. var f1 = 3 * x2 - 6 * x1;
  2193. var f2 = 3 * x1;
  2194. var refinedT = t;
  2195. for (var i = 0; i < 5; i++) {
  2196. var refinedT2 = refinedT * refinedT;
  2197. var refinedT3 = refinedT2 * refinedT;
  2198. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2199. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2200. refinedT -= (x - t) * slope;
  2201. refinedT = Math.min(1, Math.max(0, refinedT));
  2202. }
  2203. // Resolve cubic bezier for the given x
  2204. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2205. };
  2206. return BezierCurve;
  2207. })();
  2208. BABYLON.BezierCurve = BezierCurve;
  2209. (function (Orientation) {
  2210. Orientation[Orientation["CW"] = 0] = "CW";
  2211. Orientation[Orientation["CCW"] = 1] = "CCW";
  2212. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2213. var Orientation = BABYLON.Orientation;
  2214. var Angle = (function () {
  2215. function Angle(radians) {
  2216. var _this = this;
  2217. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2218. this.radians = function () { return _this._radians; };
  2219. this._radians = radians;
  2220. if (this._radians < 0)
  2221. this._radians += (2 * Math.PI);
  2222. }
  2223. Angle.BetweenTwoPoints = function (a, b) {
  2224. var delta = b.subtract(a);
  2225. var theta = Math.atan2(delta.y, delta.x);
  2226. return new Angle(theta);
  2227. };
  2228. Angle.FromRadians = function (radians) {
  2229. return new Angle(radians);
  2230. };
  2231. Angle.FromDegrees = function (degrees) {
  2232. return new Angle(degrees * Math.PI / 180);
  2233. };
  2234. return Angle;
  2235. })();
  2236. BABYLON.Angle = Angle;
  2237. var Arc2 = (function () {
  2238. function Arc2(startPoint, midPoint, endPoint) {
  2239. this.startPoint = startPoint;
  2240. this.midPoint = midPoint;
  2241. this.endPoint = endPoint;
  2242. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2243. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2244. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2245. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2246. 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);
  2247. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2248. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2249. var a1 = this.startAngle.degrees();
  2250. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2251. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2252. // angles correction
  2253. if (a2 - a1 > +180.0)
  2254. a2 -= 360.0;
  2255. if (a2 - a1 < -180.0)
  2256. a2 += 360.0;
  2257. if (a3 - a2 > +180.0)
  2258. a3 -= 360.0;
  2259. if (a3 - a2 < -180.0)
  2260. a3 += 360.0;
  2261. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2262. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2263. }
  2264. return Arc2;
  2265. })();
  2266. BABYLON.Arc2 = Arc2;
  2267. var PathCursor = (function () {
  2268. function PathCursor(path) {
  2269. this.path = path;
  2270. this._onchange = new Array();
  2271. this.value = 0;
  2272. this.animations = new Array();
  2273. }
  2274. PathCursor.prototype.getPoint = function () {
  2275. var point = this.path.getPointAtLengthPosition(this.value);
  2276. return new Vector3(point.x, 0, point.y);
  2277. };
  2278. PathCursor.prototype.moveAhead = function (step) {
  2279. if (step === void 0) { step = 0.002; }
  2280. this.move(step);
  2281. return this;
  2282. };
  2283. PathCursor.prototype.moveBack = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(-step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.move = function (step) {
  2289. if (Math.abs(step) > 1) {
  2290. throw "step size should be less than 1.";
  2291. }
  2292. this.value += step;
  2293. this.ensureLimits();
  2294. this.raiseOnChange();
  2295. return this;
  2296. };
  2297. PathCursor.prototype.ensureLimits = function () {
  2298. while (this.value > 1) {
  2299. this.value -= 1;
  2300. }
  2301. while (this.value < 0) {
  2302. this.value += 1;
  2303. }
  2304. return this;
  2305. };
  2306. // used by animation engine
  2307. PathCursor.prototype.markAsDirty = function (propertyName) {
  2308. this.ensureLimits();
  2309. this.raiseOnChange();
  2310. return this;
  2311. };
  2312. PathCursor.prototype.raiseOnChange = function () {
  2313. var _this = this;
  2314. this._onchange.forEach(function (f) { return f(_this); });
  2315. return this;
  2316. };
  2317. PathCursor.prototype.onchange = function (f) {
  2318. this._onchange.push(f);
  2319. return this;
  2320. };
  2321. return PathCursor;
  2322. })();
  2323. BABYLON.PathCursor = PathCursor;
  2324. var Path2 = (function () {
  2325. function Path2(x, y) {
  2326. this._points = [];
  2327. this._length = 0;
  2328. this.closed = false;
  2329. this._points.push(new Vector2(x, y));
  2330. }
  2331. Path2.prototype.addLineTo = function (x, y) {
  2332. if (closed) {
  2333. BABYLON.Tools.Error("cannot add lines to closed paths");
  2334. return this;
  2335. }
  2336. var newPoint = new Vector2(x, y);
  2337. var previousPoint = this._points[this._points.length - 1];
  2338. this._points.push(newPoint);
  2339. this._length += newPoint.subtract(previousPoint).length();
  2340. return this;
  2341. };
  2342. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2343. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2344. if (closed) {
  2345. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2346. return this;
  2347. }
  2348. var startPoint = this._points[this._points.length - 1];
  2349. var midPoint = new Vector2(midX, midY);
  2350. var endPoint = new Vector2(endX, endY);
  2351. var arc = new Arc2(startPoint, midPoint, endPoint);
  2352. var increment = arc.angle.radians() / numberOfSegments;
  2353. if (arc.orientation === 0 /* CW */)
  2354. increment *= -1;
  2355. var currentAngle = arc.startAngle.radians() + increment;
  2356. for (var i = 0; i < numberOfSegments; i++) {
  2357. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2358. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2359. this.addLineTo(x, y);
  2360. currentAngle += increment;
  2361. }
  2362. return this;
  2363. };
  2364. Path2.prototype.close = function () {
  2365. this.closed = true;
  2366. return this;
  2367. };
  2368. Path2.prototype.length = function () {
  2369. var result = this._length;
  2370. if (!this.closed) {
  2371. var lastPoint = this._points[this._points.length - 1];
  2372. var firstPoint = this._points[0];
  2373. result += (firstPoint.subtract(lastPoint).length());
  2374. }
  2375. return result;
  2376. };
  2377. Path2.prototype.getPoints = function () {
  2378. return this._points;
  2379. };
  2380. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2381. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2382. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2383. return Vector2.Zero();
  2384. }
  2385. var lengthPosition = normalizedLengthPosition * this.length();
  2386. var previousOffset = 0;
  2387. for (var i = 0; i < this._points.length; i++) {
  2388. var j = (i + 1) % this._points.length;
  2389. var a = this._points[i];
  2390. var b = this._points[j];
  2391. var bToA = b.subtract(a);
  2392. var nextOffset = (bToA.length() + previousOffset);
  2393. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2394. var dir = bToA.normalize();
  2395. var localOffset = lengthPosition - previousOffset;
  2396. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2397. }
  2398. previousOffset = nextOffset;
  2399. }
  2400. BABYLON.Tools.Error("internal error");
  2401. return Vector2.Zero();
  2402. };
  2403. Path2.StartingAt = function (x, y) {
  2404. return new Path2(x, y);
  2405. };
  2406. return Path2;
  2407. })();
  2408. BABYLON.Path2 = Path2;
  2409. })(BABYLON || (BABYLON = {}));
  2410. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2411. (function (BABYLON) {
  2412. // Screenshots
  2413. var screenshotCanvas;
  2414. var cloneValue = function (source, destinationObject) {
  2415. if (!source)
  2416. return null;
  2417. if (source instanceof BABYLON.Mesh) {
  2418. return null;
  2419. }
  2420. if (source instanceof BABYLON.SubMesh) {
  2421. return source.clone(destinationObject);
  2422. }
  2423. else if (source.clone) {
  2424. return source.clone();
  2425. }
  2426. return null;
  2427. };
  2428. var Tools = (function () {
  2429. function Tools() {
  2430. }
  2431. Tools.GetFilename = function (path) {
  2432. var index = path.lastIndexOf("/");
  2433. if (index < 0)
  2434. return path;
  2435. return path.substring(index + 1);
  2436. };
  2437. Tools.GetDOMTextContent = function (element) {
  2438. var result = "";
  2439. var child = element.firstChild;
  2440. while (child) {
  2441. if (child.nodeType === 3) {
  2442. result += child.textContent;
  2443. }
  2444. child = child.nextSibling;
  2445. }
  2446. return result;
  2447. };
  2448. Tools.ToDegrees = function (angle) {
  2449. return angle * 180 / Math.PI;
  2450. };
  2451. Tools.ToRadians = function (angle) {
  2452. return angle * Math.PI / 180;
  2453. };
  2454. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2455. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2456. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2457. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2458. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2459. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2460. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2461. }
  2462. return {
  2463. minimum: minimum,
  2464. maximum: maximum
  2465. };
  2466. };
  2467. Tools.ExtractMinAndMax = function (positions, start, count) {
  2468. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2469. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2470. for (var index = start; index < start + count; index++) {
  2471. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2472. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2473. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2474. }
  2475. return {
  2476. minimum: minimum,
  2477. maximum: maximum
  2478. };
  2479. };
  2480. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2481. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2482. return undefined;
  2483. return Array.isArray(obj) ? obj : [obj];
  2484. };
  2485. // Misc.
  2486. Tools.GetPointerPrefix = function () {
  2487. var eventPrefix = "pointer";
  2488. // Check if hand.js is referenced or if the browser natively supports pointer events
  2489. if (!navigator.pointerEnabled) {
  2490. eventPrefix = "mouse";
  2491. }
  2492. return eventPrefix;
  2493. };
  2494. Tools.QueueNewFrame = function (func) {
  2495. if (window.requestAnimationFrame)
  2496. window.requestAnimationFrame(func);
  2497. else if (window.msRequestAnimationFrame)
  2498. window.msRequestAnimationFrame(func);
  2499. else if (window.webkitRequestAnimationFrame)
  2500. window.webkitRequestAnimationFrame(func);
  2501. else if (window.mozRequestAnimationFrame)
  2502. window.mozRequestAnimationFrame(func);
  2503. else if (window.oRequestAnimationFrame)
  2504. window.oRequestAnimationFrame(func);
  2505. else {
  2506. window.setTimeout(func, 16);
  2507. }
  2508. };
  2509. Tools.RequestFullscreen = function (element) {
  2510. if (element.requestFullscreen)
  2511. element.requestFullscreen();
  2512. else if (element.msRequestFullscreen)
  2513. element.msRequestFullscreen();
  2514. else if (element.webkitRequestFullscreen)
  2515. element.webkitRequestFullscreen();
  2516. else if (element.mozRequestFullScreen)
  2517. element.mozRequestFullScreen();
  2518. };
  2519. Tools.ExitFullscreen = function () {
  2520. if (document.exitFullscreen) {
  2521. document.exitFullscreen();
  2522. }
  2523. else if (document.mozCancelFullScreen) {
  2524. document.mozCancelFullScreen();
  2525. }
  2526. else if (document.webkitCancelFullScreen) {
  2527. document.webkitCancelFullScreen();
  2528. }
  2529. else if (document.msCancelFullScreen) {
  2530. document.msCancelFullScreen();
  2531. }
  2532. };
  2533. // External files
  2534. Tools.CleanUrl = function (url) {
  2535. url = url.replace(/#/mg, "%23");
  2536. return url;
  2537. };
  2538. Tools.LoadImage = function (url, onload, onerror, database) {
  2539. url = Tools.CleanUrl(url);
  2540. var img = new Image();
  2541. if (url.substr(0, 5) !== "data:")
  2542. img.crossOrigin = 'anonymous';
  2543. img.onload = function () {
  2544. onload(img);
  2545. };
  2546. img.onerror = function (err) {
  2547. onerror(img, err);
  2548. };
  2549. var noIndexedDB = function () {
  2550. img.src = url;
  2551. };
  2552. var loadFromIndexedDB = function () {
  2553. database.loadImageFromDB(url, img);
  2554. };
  2555. //ANY database to do!
  2556. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2557. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2558. }
  2559. else {
  2560. if (url.indexOf("file:") === -1) {
  2561. noIndexedDB();
  2562. }
  2563. else {
  2564. try {
  2565. var textureName = url.substring(5);
  2566. var blobURL;
  2567. try {
  2568. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2569. }
  2570. catch (ex) {
  2571. // Chrome doesn't support oneTimeOnly parameter
  2572. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2573. }
  2574. img.src = blobURL;
  2575. }
  2576. catch (e) {
  2577. Tools.Log("Error while trying to load texture: " + textureName);
  2578. img.src = null;
  2579. }
  2580. }
  2581. }
  2582. return img;
  2583. };
  2584. //ANY
  2585. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2586. url = Tools.CleanUrl(url);
  2587. var noIndexedDB = function () {
  2588. var request = new XMLHttpRequest();
  2589. var loadUrl = Tools.BaseUrl + url;
  2590. request.open('GET', loadUrl, true);
  2591. if (useArrayBuffer) {
  2592. request.responseType = "arraybuffer";
  2593. }
  2594. request.onprogress = progressCallBack;
  2595. request.onreadystatechange = function () {
  2596. if (request.readyState === 4) {
  2597. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2598. callback(!useArrayBuffer ? request.responseText : request.response);
  2599. }
  2600. else {
  2601. if (onError) {
  2602. onError();
  2603. }
  2604. else {
  2605. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2606. }
  2607. }
  2608. }
  2609. };
  2610. request.send(null);
  2611. };
  2612. var loadFromIndexedDB = function () {
  2613. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2614. };
  2615. if (url.indexOf("file:") !== -1) {
  2616. var fileName = url.substring(5);
  2617. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2618. }
  2619. else {
  2620. // Caching all files
  2621. if (database && database.enableSceneOffline) {
  2622. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2623. }
  2624. else {
  2625. noIndexedDB();
  2626. }
  2627. }
  2628. };
  2629. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2630. var reader = new FileReader();
  2631. reader.onload = function (e) {
  2632. //target doesn't have result from ts 1.3
  2633. callback(e.target['result']);
  2634. };
  2635. reader.onprogress = progressCallback;
  2636. reader.readAsDataURL(fileToLoad);
  2637. };
  2638. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2639. var reader = new FileReader();
  2640. reader.onload = function (e) {
  2641. //target doesn't have result from ts 1.3
  2642. callback(e.target['result']);
  2643. };
  2644. reader.onprogress = progressCallBack;
  2645. if (!useArrayBuffer) {
  2646. // Asynchronous read
  2647. reader.readAsText(fileToLoad);
  2648. }
  2649. else {
  2650. reader.readAsArrayBuffer(fileToLoad);
  2651. }
  2652. };
  2653. // Misc.
  2654. Tools.Clamp = function (value, min, max) {
  2655. if (min === void 0) { min = 0; }
  2656. if (max === void 0) { max = 1; }
  2657. return Math.min(max, Math.max(min, value));
  2658. };
  2659. // Returns -1 when value is a negative number and
  2660. // +1 when value is a positive number.
  2661. Tools.Sign = function (value) {
  2662. value = +value; // convert to a number
  2663. if (value === 0 || isNaN(value))
  2664. return value;
  2665. return value > 0 ? 1 : -1;
  2666. };
  2667. Tools.Format = function (value, decimals) {
  2668. if (decimals === void 0) { decimals = 2; }
  2669. return value.toFixed(decimals);
  2670. };
  2671. Tools.CheckExtends = function (v, min, max) {
  2672. if (v.x < min.x)
  2673. min.x = v.x;
  2674. if (v.y < min.y)
  2675. min.y = v.y;
  2676. if (v.z < min.z)
  2677. min.z = v.z;
  2678. if (v.x > max.x)
  2679. max.x = v.x;
  2680. if (v.y > max.y)
  2681. max.y = v.y;
  2682. if (v.z > max.z)
  2683. max.z = v.z;
  2684. };
  2685. Tools.WithinEpsilon = function (a, b, epsilon) {
  2686. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2687. var num = a - b;
  2688. return -epsilon <= num && num <= epsilon;
  2689. };
  2690. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2691. for (var prop in source) {
  2692. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2693. continue;
  2694. }
  2695. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2696. continue;
  2697. }
  2698. var sourceValue = source[prop];
  2699. var typeOfSourceValue = typeof sourceValue;
  2700. if (typeOfSourceValue === "function") {
  2701. continue;
  2702. }
  2703. if (typeOfSourceValue === "object") {
  2704. if (sourceValue instanceof Array) {
  2705. destination[prop] = [];
  2706. if (sourceValue.length > 0) {
  2707. if (typeof sourceValue[0] == "object") {
  2708. for (var index = 0; index < sourceValue.length; index++) {
  2709. var clonedValue = cloneValue(sourceValue[index], destination);
  2710. if (destination[prop].indexOf(clonedValue) === -1) {
  2711. destination[prop].push(clonedValue);
  2712. }
  2713. }
  2714. }
  2715. else {
  2716. destination[prop] = sourceValue.slice(0);
  2717. }
  2718. }
  2719. }
  2720. else {
  2721. destination[prop] = cloneValue(sourceValue, destination);
  2722. }
  2723. }
  2724. else {
  2725. destination[prop] = sourceValue;
  2726. }
  2727. }
  2728. };
  2729. Tools.IsEmpty = function (obj) {
  2730. for (var i in obj) {
  2731. return false;
  2732. }
  2733. return true;
  2734. };
  2735. Tools.RegisterTopRootEvents = function (events) {
  2736. for (var index = 0; index < events.length; index++) {
  2737. var event = events[index];
  2738. window.addEventListener(event.name, event.handler, false);
  2739. try {
  2740. if (window.parent) {
  2741. window.parent.addEventListener(event.name, event.handler, false);
  2742. }
  2743. }
  2744. catch (e) {
  2745. }
  2746. }
  2747. };
  2748. Tools.UnregisterTopRootEvents = function (events) {
  2749. for (var index = 0; index < events.length; index++) {
  2750. var event = events[index];
  2751. window.removeEventListener(event.name, event.handler);
  2752. try {
  2753. if (window.parent) {
  2754. window.parent.removeEventListener(event.name, event.handler);
  2755. }
  2756. }
  2757. catch (e) {
  2758. }
  2759. }
  2760. };
  2761. Tools.CreateScreenshot = function (engine, camera, size) {
  2762. var width;
  2763. var height;
  2764. var scene = camera.getScene();
  2765. var previousCamera = null;
  2766. if (scene.activeCamera !== camera) {
  2767. previousCamera = scene.activeCamera;
  2768. scene.activeCamera = camera;
  2769. }
  2770. //If a precision value is specified
  2771. if (size.precision) {
  2772. width = Math.round(engine.getRenderWidth() * size.precision);
  2773. height = Math.round(width / engine.getAspectRatio(camera));
  2774. size = { width: width, height: height };
  2775. }
  2776. else if (size.width && size.height) {
  2777. width = size.width;
  2778. height = size.height;
  2779. }
  2780. else if (size.width && !size.height) {
  2781. width = size.width;
  2782. height = Math.round(width / engine.getAspectRatio(camera));
  2783. size = { width: width, height: height };
  2784. }
  2785. else if (size.height && !size.width) {
  2786. height = size.height;
  2787. width = Math.round(height * engine.getAspectRatio(camera));
  2788. size = { width: width, height: height };
  2789. }
  2790. else if (!isNaN(size)) {
  2791. height = size;
  2792. width = size;
  2793. }
  2794. else {
  2795. Tools.Error("Invalid 'size' parameter !");
  2796. return;
  2797. }
  2798. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2799. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2800. texture.renderList = scene.meshes;
  2801. texture.onAfterRender = function () {
  2802. // Read the contents of the framebuffer
  2803. var numberOfChannelsByLine = width * 4;
  2804. var halfHeight = height / 2;
  2805. //Reading datas from WebGL
  2806. var data = engine.readPixels(0, 0, width, height);
  2807. for (var i = 0; i < halfHeight; i++) {
  2808. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2809. var currentCell = j + i * numberOfChannelsByLine;
  2810. var targetLine = height - i - 1;
  2811. var targetCell = j + targetLine * numberOfChannelsByLine;
  2812. var temp = data[currentCell];
  2813. data[currentCell] = data[targetCell];
  2814. data[targetCell] = temp;
  2815. }
  2816. }
  2817. // Create a 2D canvas to store the result
  2818. if (!screenshotCanvas) {
  2819. screenshotCanvas = document.createElement('canvas');
  2820. }
  2821. screenshotCanvas.width = width;
  2822. screenshotCanvas.height = height;
  2823. var context = screenshotCanvas.getContext('2d');
  2824. // Copy the pixels to a 2D canvas
  2825. var imageData = context.createImageData(width, height);
  2826. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2827. var data = imageData.data;
  2828. data.set(data);
  2829. context.putImageData(imageData, 0, 0);
  2830. var base64Image = screenshotCanvas.toDataURL();
  2831. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2832. if (("download" in document.createElement("a"))) {
  2833. var a = window.document.createElement("a");
  2834. a.href = base64Image;
  2835. var date = new Date();
  2836. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2837. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2838. window.document.body.appendChild(a);
  2839. a.addEventListener("click", function () {
  2840. a.parentElement.removeChild(a);
  2841. });
  2842. a.click();
  2843. }
  2844. else {
  2845. var newWindow = window.open("");
  2846. var img = newWindow.document.createElement("img");
  2847. img.src = base64Image;
  2848. newWindow.document.body.appendChild(img);
  2849. }
  2850. };
  2851. scene.incrementRenderId();
  2852. texture.render(true);
  2853. texture.dispose();
  2854. if (previousCamera) {
  2855. scene.activeCamera = previousCamera;
  2856. }
  2857. };
  2858. // XHR response validator for local file scenario
  2859. Tools.ValidateXHRData = function (xhr, dataType) {
  2860. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2861. if (dataType === void 0) { dataType = 7; }
  2862. try {
  2863. if (dataType & 1) {
  2864. if (xhr.responseText && xhr.responseText.length > 0) {
  2865. return true;
  2866. }
  2867. else if (dataType === 1) {
  2868. return false;
  2869. }
  2870. }
  2871. if (dataType & 2) {
  2872. // Check header width and height since there is no "TGA" magic number
  2873. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2874. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2875. return true;
  2876. }
  2877. else if (dataType === 2) {
  2878. return false;
  2879. }
  2880. }
  2881. if (dataType & 4) {
  2882. // Check for the "DDS" magic number
  2883. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2884. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2885. return true;
  2886. }
  2887. else {
  2888. return false;
  2889. }
  2890. }
  2891. }
  2892. catch (e) {
  2893. }
  2894. return false;
  2895. };
  2896. Object.defineProperty(Tools, "NoneLogLevel", {
  2897. get: function () {
  2898. return Tools._NoneLogLevel;
  2899. },
  2900. enumerable: true,
  2901. configurable: true
  2902. });
  2903. Object.defineProperty(Tools, "MessageLogLevel", {
  2904. get: function () {
  2905. return Tools._MessageLogLevel;
  2906. },
  2907. enumerable: true,
  2908. configurable: true
  2909. });
  2910. Object.defineProperty(Tools, "WarningLogLevel", {
  2911. get: function () {
  2912. return Tools._WarningLogLevel;
  2913. },
  2914. enumerable: true,
  2915. configurable: true
  2916. });
  2917. Object.defineProperty(Tools, "ErrorLogLevel", {
  2918. get: function () {
  2919. return Tools._ErrorLogLevel;
  2920. },
  2921. enumerable: true,
  2922. configurable: true
  2923. });
  2924. Object.defineProperty(Tools, "AllLogLevel", {
  2925. get: function () {
  2926. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2927. },
  2928. enumerable: true,
  2929. configurable: true
  2930. });
  2931. Tools._AddLogEntry = function (entry) {
  2932. Tools._LogCache = entry + Tools._LogCache;
  2933. if (Tools.OnNewCacheEntry) {
  2934. Tools.OnNewCacheEntry(entry);
  2935. }
  2936. };
  2937. Tools._FormatMessage = function (message) {
  2938. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2939. var date = new Date();
  2940. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2941. };
  2942. Tools._LogDisabled = function (message) {
  2943. // nothing to do
  2944. };
  2945. Tools._LogEnabled = function (message) {
  2946. var formattedMessage = Tools._FormatMessage(message);
  2947. console.log("BJS - " + formattedMessage);
  2948. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2949. Tools._AddLogEntry(entry);
  2950. };
  2951. Tools._WarnDisabled = function (message) {
  2952. // nothing to do
  2953. };
  2954. Tools._WarnEnabled = function (message) {
  2955. var formattedMessage = Tools._FormatMessage(message);
  2956. console.warn("BJS - " + formattedMessage);
  2957. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2958. Tools._AddLogEntry(entry);
  2959. };
  2960. Tools._ErrorDisabled = function (message) {
  2961. // nothing to do
  2962. };
  2963. Tools._ErrorEnabled = function (message) {
  2964. var formattedMessage = Tools._FormatMessage(message);
  2965. console.error("BJS - " + formattedMessage);
  2966. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2967. Tools._AddLogEntry(entry);
  2968. };
  2969. Object.defineProperty(Tools, "LogCache", {
  2970. get: function () {
  2971. return Tools._LogCache;
  2972. },
  2973. enumerable: true,
  2974. configurable: true
  2975. });
  2976. Object.defineProperty(Tools, "LogLevels", {
  2977. set: function (level) {
  2978. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2979. Tools.Log = Tools._LogEnabled;
  2980. }
  2981. else {
  2982. Tools.Log = Tools._LogDisabled;
  2983. }
  2984. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2985. Tools.Warn = Tools._WarnEnabled;
  2986. }
  2987. else {
  2988. Tools.Warn = Tools._WarnDisabled;
  2989. }
  2990. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2991. Tools.Error = Tools._ErrorEnabled;
  2992. }
  2993. else {
  2994. Tools.Error = Tools._ErrorDisabled;
  2995. }
  2996. },
  2997. enumerable: true,
  2998. configurable: true
  2999. });
  3000. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3001. get: function () {
  3002. return Tools._PerformanceNoneLogLevel;
  3003. },
  3004. enumerable: true,
  3005. configurable: true
  3006. });
  3007. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3008. get: function () {
  3009. return Tools._PerformanceUserMarkLogLevel;
  3010. },
  3011. enumerable: true,
  3012. configurable: true
  3013. });
  3014. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3015. get: function () {
  3016. return Tools._PerformanceConsoleLogLevel;
  3017. },
  3018. enumerable: true,
  3019. configurable: true
  3020. });
  3021. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3022. set: function (level) {
  3023. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3024. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3025. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3026. return;
  3027. }
  3028. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3029. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3030. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3031. return;
  3032. }
  3033. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3034. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3035. },
  3036. enumerable: true,
  3037. configurable: true
  3038. });
  3039. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3040. };
  3041. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3042. };
  3043. Tools._StartUserMark = function (counterName, condition) {
  3044. if (condition === void 0) { condition = true; }
  3045. if (!condition || !Tools._performance.mark) {
  3046. return;
  3047. }
  3048. Tools._performance.mark(counterName + "-Begin");
  3049. };
  3050. Tools._EndUserMark = function (counterName, condition) {
  3051. if (condition === void 0) { condition = true; }
  3052. if (!condition || !Tools._performance.mark) {
  3053. return;
  3054. }
  3055. Tools._performance.mark(counterName + "-End");
  3056. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3057. };
  3058. Tools._StartPerformanceConsole = function (counterName, condition) {
  3059. if (condition === void 0) { condition = true; }
  3060. if (!condition) {
  3061. return;
  3062. }
  3063. Tools._StartUserMark(counterName, condition);
  3064. if (console.time) {
  3065. console.time(counterName);
  3066. }
  3067. };
  3068. Tools._EndPerformanceConsole = function (counterName, condition) {
  3069. if (condition === void 0) { condition = true; }
  3070. if (!condition) {
  3071. return;
  3072. }
  3073. Tools._EndUserMark(counterName, condition);
  3074. if (console.time) {
  3075. console.timeEnd(counterName);
  3076. }
  3077. };
  3078. Object.defineProperty(Tools, "Now", {
  3079. get: function () {
  3080. if (window.performance && window.performance.now) {
  3081. return window.performance.now();
  3082. }
  3083. return new Date().getTime();
  3084. },
  3085. enumerable: true,
  3086. configurable: true
  3087. });
  3088. // Deprecated
  3089. Tools.GetFps = function () {
  3090. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3091. return 0;
  3092. };
  3093. Tools.BaseUrl = "";
  3094. Tools.GetExponantOfTwo = function (value, max) {
  3095. var count = 1;
  3096. do {
  3097. count *= 2;
  3098. } while (count < value);
  3099. if (count > max)
  3100. count = max;
  3101. return count;
  3102. };
  3103. // Logs
  3104. Tools._NoneLogLevel = 0;
  3105. Tools._MessageLogLevel = 1;
  3106. Tools._WarningLogLevel = 2;
  3107. Tools._ErrorLogLevel = 4;
  3108. Tools._LogCache = "";
  3109. Tools.Log = Tools._LogEnabled;
  3110. Tools.Warn = Tools._WarnEnabled;
  3111. Tools.Error = Tools._ErrorEnabled;
  3112. // Performances
  3113. Tools._PerformanceNoneLogLevel = 0;
  3114. Tools._PerformanceUserMarkLogLevel = 1;
  3115. Tools._PerformanceConsoleLogLevel = 2;
  3116. Tools._performance = window.performance;
  3117. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3118. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3119. return Tools;
  3120. })();
  3121. BABYLON.Tools = Tools;
  3122. /**
  3123. * An implementation of a loop for asynchronous functions.
  3124. */
  3125. var AsyncLoop = (function () {
  3126. /**
  3127. * Constroctor.
  3128. * @param iterations the number of iterations.
  3129. * @param _fn the function to run each iteration
  3130. * @param _successCallback the callback that will be called upon succesful execution
  3131. * @param offset starting offset.
  3132. */
  3133. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3134. if (offset === void 0) { offset = 0; }
  3135. this.iterations = iterations;
  3136. this._fn = _fn;
  3137. this._successCallback = _successCallback;
  3138. this.index = offset - 1;
  3139. this._done = false;
  3140. }
  3141. /**
  3142. * Execute the next iteration. Must be called after the last iteration was finished.
  3143. */
  3144. AsyncLoop.prototype.executeNext = function () {
  3145. if (!this._done) {
  3146. if (this.index + 1 < this.iterations) {
  3147. ++this.index;
  3148. this._fn(this);
  3149. }
  3150. else {
  3151. this.breakLoop();
  3152. }
  3153. }
  3154. };
  3155. /**
  3156. * Break the loop and run the success callback.
  3157. */
  3158. AsyncLoop.prototype.breakLoop = function () {
  3159. this._done = true;
  3160. this._successCallback();
  3161. };
  3162. /**
  3163. * Helper function
  3164. */
  3165. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3166. if (offset === void 0) { offset = 0; }
  3167. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3168. loop.executeNext();
  3169. return loop;
  3170. };
  3171. /**
  3172. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3173. * @param iterations total number of iterations
  3174. * @param syncedIterations number of synchronous iterations in each async iteration.
  3175. * @param fn the function to call each iteration.
  3176. * @param callback a success call back that will be called when iterating stops.
  3177. * @param breakFunction a break condition (optional)
  3178. * @param timeout timeout settings for the setTimeout function. default - 0.
  3179. * @constructor
  3180. */
  3181. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3182. if (timeout === void 0) { timeout = 0; }
  3183. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3184. if (breakFunction && breakFunction())
  3185. loop.breakLoop();
  3186. else {
  3187. setTimeout(function () {
  3188. for (var i = 0; i < syncedIterations; ++i) {
  3189. var iteration = (loop.index * syncedIterations) + i;
  3190. if (iteration >= iterations)
  3191. break;
  3192. fn(iteration);
  3193. if (breakFunction && breakFunction()) {
  3194. loop.breakLoop();
  3195. break;
  3196. }
  3197. }
  3198. loop.executeNext();
  3199. }, timeout);
  3200. }
  3201. }, callback);
  3202. };
  3203. return AsyncLoop;
  3204. })();
  3205. BABYLON.AsyncLoop = AsyncLoop;
  3206. })(BABYLON || (BABYLON = {}));
  3207. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3208. (function (BABYLON) {
  3209. var _DepthCullingState = (function () {
  3210. function _DepthCullingState() {
  3211. this._isDepthTestDirty = false;
  3212. this._isDepthMaskDirty = false;
  3213. this._isDepthFuncDirty = false;
  3214. this._isCullFaceDirty = false;
  3215. this._isCullDirty = false;
  3216. }
  3217. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3218. get: function () {
  3219. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3220. },
  3221. enumerable: true,
  3222. configurable: true
  3223. });
  3224. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3225. get: function () {
  3226. return this._cullFace;
  3227. },
  3228. set: function (value) {
  3229. if (this._cullFace === value) {
  3230. return;
  3231. }
  3232. this._cullFace = value;
  3233. this._isCullFaceDirty = true;
  3234. },
  3235. enumerable: true,
  3236. configurable: true
  3237. });
  3238. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3239. get: function () {
  3240. return this._cull;
  3241. },
  3242. set: function (value) {
  3243. if (this._cull === value) {
  3244. return;
  3245. }
  3246. this._cull = value;
  3247. this._isCullDirty = true;
  3248. },
  3249. enumerable: true,
  3250. configurable: true
  3251. });
  3252. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3253. get: function () {
  3254. return this._depthFunc;
  3255. },
  3256. set: function (value) {
  3257. if (this._depthFunc === value) {
  3258. return;
  3259. }
  3260. this._depthFunc = value;
  3261. this._isDepthFuncDirty = true;
  3262. },
  3263. enumerable: true,
  3264. configurable: true
  3265. });
  3266. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3267. get: function () {
  3268. return this._depthMask;
  3269. },
  3270. set: function (value) {
  3271. if (this._depthMask === value) {
  3272. return;
  3273. }
  3274. this._depthMask = value;
  3275. this._isDepthMaskDirty = true;
  3276. },
  3277. enumerable: true,
  3278. configurable: true
  3279. });
  3280. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3281. get: function () {
  3282. return this._depthTest;
  3283. },
  3284. set: function (value) {
  3285. if (this._depthTest === value) {
  3286. return;
  3287. }
  3288. this._depthTest = value;
  3289. this._isDepthTestDirty = true;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. _DepthCullingState.prototype.reset = function () {
  3295. this._depthMask = true;
  3296. this._depthTest = true;
  3297. this._depthFunc = null;
  3298. this._cull = null;
  3299. this._cullFace = null;
  3300. this._isDepthTestDirty = true;
  3301. this._isDepthMaskDirty = true;
  3302. this._isDepthFuncDirty = false;
  3303. this._isCullFaceDirty = false;
  3304. this._isCullDirty = false;
  3305. };
  3306. _DepthCullingState.prototype.apply = function (gl) {
  3307. if (!this.isDirty) {
  3308. return;
  3309. }
  3310. // Cull
  3311. if (this._isCullDirty) {
  3312. if (this.cull) {
  3313. gl.enable(gl.CULL_FACE);
  3314. }
  3315. else {
  3316. gl.disable(gl.CULL_FACE);
  3317. }
  3318. this._isCullDirty = false;
  3319. }
  3320. // Cull face
  3321. if (this._isCullFaceDirty) {
  3322. gl.cullFace(this.cullFace);
  3323. this._isCullFaceDirty = false;
  3324. }
  3325. // Depth mask
  3326. if (this._isDepthMaskDirty) {
  3327. gl.depthMask(this.depthMask);
  3328. this._isDepthMaskDirty = false;
  3329. }
  3330. // Depth test
  3331. if (this._isDepthTestDirty) {
  3332. if (this.depthTest) {
  3333. gl.enable(gl.DEPTH_TEST);
  3334. }
  3335. else {
  3336. gl.disable(gl.DEPTH_TEST);
  3337. }
  3338. this._isDepthTestDirty = false;
  3339. }
  3340. // Depth func
  3341. if (this._isDepthFuncDirty) {
  3342. gl.depthFunc(this.depthFunc);
  3343. this._isDepthFuncDirty = false;
  3344. }
  3345. };
  3346. return _DepthCullingState;
  3347. })();
  3348. BABYLON._DepthCullingState = _DepthCullingState;
  3349. var _AlphaState = (function () {
  3350. function _AlphaState() {
  3351. this._isAlphaBlendDirty = false;
  3352. this._isBlendFunctionParametersDirty = false;
  3353. this._alphaBlend = false;
  3354. this._blendFunctionParameters = new Array(4);
  3355. }
  3356. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3357. get: function () {
  3358. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3364. get: function () {
  3365. return this._alphaBlend;
  3366. },
  3367. set: function (value) {
  3368. if (this._alphaBlend === value) {
  3369. return;
  3370. }
  3371. this._alphaBlend = value;
  3372. this._isAlphaBlendDirty = true;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3378. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3379. return;
  3380. }
  3381. this._blendFunctionParameters[0] = value0;
  3382. this._blendFunctionParameters[1] = value1;
  3383. this._blendFunctionParameters[2] = value2;
  3384. this._blendFunctionParameters[3] = value3;
  3385. this._isBlendFunctionParametersDirty = true;
  3386. };
  3387. _AlphaState.prototype.reset = function () {
  3388. this._alphaBlend = false;
  3389. this._blendFunctionParameters[0] = null;
  3390. this._blendFunctionParameters[1] = null;
  3391. this._blendFunctionParameters[2] = null;
  3392. this._blendFunctionParameters[3] = null;
  3393. this._isAlphaBlendDirty = true;
  3394. this._isBlendFunctionParametersDirty = false;
  3395. };
  3396. _AlphaState.prototype.apply = function (gl) {
  3397. if (!this.isDirty) {
  3398. return;
  3399. }
  3400. // Alpha blend
  3401. if (this._isAlphaBlendDirty) {
  3402. if (this._alphaBlend) {
  3403. gl.enable(gl.BLEND);
  3404. }
  3405. else {
  3406. gl.disable(gl.BLEND);
  3407. }
  3408. this._isAlphaBlendDirty = false;
  3409. }
  3410. // Alpha function
  3411. if (this._isBlendFunctionParametersDirty) {
  3412. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3413. this._isBlendFunctionParametersDirty = false;
  3414. }
  3415. };
  3416. return _AlphaState;
  3417. })();
  3418. BABYLON._AlphaState = _AlphaState;
  3419. var compileShader = function (gl, source, type, defines) {
  3420. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3421. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3422. gl.compileShader(shader);
  3423. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3424. throw new Error(gl.getShaderInfoLog(shader));
  3425. }
  3426. return shader;
  3427. };
  3428. var getWebGLTextureType = function (gl, type) {
  3429. var textureType = gl.UNSIGNED_BYTE;
  3430. if (type === Engine.TEXTURETYPE_FLOAT)
  3431. textureType = gl.FLOAT;
  3432. return textureType;
  3433. };
  3434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3435. var magFilter = gl.NEAREST;
  3436. var minFilter = gl.NEAREST;
  3437. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3438. magFilter = gl.LINEAR;
  3439. if (generateMipMaps) {
  3440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3441. }
  3442. else {
  3443. minFilter = gl.LINEAR;
  3444. }
  3445. }
  3446. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3447. magFilter = gl.LINEAR;
  3448. if (generateMipMaps) {
  3449. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3450. }
  3451. else {
  3452. minFilter = gl.LINEAR;
  3453. }
  3454. }
  3455. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3456. magFilter = gl.NEAREST;
  3457. if (generateMipMaps) {
  3458. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3459. }
  3460. else {
  3461. minFilter = gl.NEAREST;
  3462. }
  3463. }
  3464. return {
  3465. min: minFilter,
  3466. mag: magFilter
  3467. };
  3468. };
  3469. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3471. var engine = scene.getEngine();
  3472. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3473. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3474. gl.bindTexture(gl.TEXTURE_2D, texture);
  3475. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3476. processFunction(potWidth, potHeight);
  3477. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3480. if (!noMipmap && !isCompressed) {
  3481. gl.generateMipmap(gl.TEXTURE_2D);
  3482. }
  3483. gl.bindTexture(gl.TEXTURE_2D, null);
  3484. engine._activeTexturesCache = [];
  3485. texture._baseWidth = width;
  3486. texture._baseHeight = height;
  3487. texture._width = potWidth;
  3488. texture._height = potHeight;
  3489. texture.isReady = true;
  3490. texture.samplingMode = samplingMode;
  3491. scene._removePendingData(texture);
  3492. };
  3493. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3494. var onload = function () {
  3495. loadedImages[index] = img;
  3496. loadedImages._internalCount++;
  3497. scene._removePendingData(img);
  3498. if (loadedImages._internalCount === 6) {
  3499. onfinish(loadedImages);
  3500. }
  3501. };
  3502. var onerror = function () {
  3503. scene._removePendingData(img);
  3504. };
  3505. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3506. scene._addPendingData(img);
  3507. };
  3508. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3509. var loadedImages = [];
  3510. loadedImages._internalCount = 0;
  3511. for (var index = 0; index < 6; index++) {
  3512. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3513. }
  3514. };
  3515. var EngineCapabilities = (function () {
  3516. function EngineCapabilities() {
  3517. }
  3518. return EngineCapabilities;
  3519. })();
  3520. BABYLON.EngineCapabilities = EngineCapabilities;
  3521. /**
  3522. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3523. */
  3524. var Engine = (function () {
  3525. /**
  3526. * @constructor
  3527. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3528. * @param {boolean} [antialias] - enable antialias
  3529. * @param options - further options to be sent to the getContext function
  3530. */
  3531. function Engine(canvas, antialias, options) {
  3532. var _this = this;
  3533. // Public members
  3534. this.isFullscreen = false;
  3535. this.isPointerLock = false;
  3536. this.cullBackFaces = true;
  3537. this.renderEvenInBackground = true;
  3538. this.scenes = new Array();
  3539. this._windowIsBackground = false;
  3540. this._loadingDivBackgroundColor = "black";
  3541. this._drawCalls = 0;
  3542. this._renderingQueueLaunched = false;
  3543. this._activeRenderLoops = [];
  3544. // FPS
  3545. this.fpsRange = 60;
  3546. this.previousFramesDuration = [];
  3547. this.fps = 60;
  3548. this.deltaTime = 0;
  3549. // States
  3550. this._depthCullingState = new _DepthCullingState();
  3551. this._alphaState = new _AlphaState();
  3552. this._alphaMode = Engine.ALPHA_DISABLE;
  3553. // Cache
  3554. this._loadedTexturesCache = new Array();
  3555. this._activeTexturesCache = new Array();
  3556. this._compiledEffects = {};
  3557. this._uintIndicesCurrentlySet = false;
  3558. this._renderingCanvas = canvas;
  3559. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3560. options = options || {};
  3561. options.antialias = antialias;
  3562. try {
  3563. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3564. }
  3565. catch (e) {
  3566. throw new Error("WebGL not supported");
  3567. }
  3568. if (!this._gl) {
  3569. throw new Error("WebGL not supported");
  3570. }
  3571. this._onBlur = function () {
  3572. _this._windowIsBackground = true;
  3573. };
  3574. this._onFocus = function () {
  3575. _this._windowIsBackground = false;
  3576. };
  3577. window.addEventListener("blur", this._onBlur);
  3578. window.addEventListener("focus", this._onFocus);
  3579. // Textures
  3580. this._workingCanvas = document.createElement("canvas");
  3581. this._workingContext = this._workingCanvas.getContext("2d");
  3582. // Viewport
  3583. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3584. this.resize();
  3585. // Caps
  3586. this._caps = new EngineCapabilities();
  3587. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3588. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3589. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3590. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3591. // Infos
  3592. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3593. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3594. if (rendererInfo != null) {
  3595. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3596. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3597. }
  3598. if (!this._glVendor) {
  3599. this._glVendor = "Unknown vendor";
  3600. }
  3601. if (!this._glRenderer) {
  3602. this._glRenderer = "Unknown renderer";
  3603. }
  3604. // Extensions
  3605. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3606. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3607. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3608. 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');
  3609. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3610. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3611. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3612. // Depth buffer
  3613. this.setDepthBuffer(true);
  3614. this.setDepthFunctionToLessOrEqual();
  3615. this.setDepthWrite(true);
  3616. // Fullscreen
  3617. this._onFullscreenChange = function () {
  3618. if (document.fullscreen !== undefined) {
  3619. _this.isFullscreen = document.fullscreen;
  3620. }
  3621. else if (document.mozFullScreen !== undefined) {
  3622. _this.isFullscreen = document.mozFullScreen;
  3623. }
  3624. else if (document.webkitIsFullScreen !== undefined) {
  3625. _this.isFullscreen = document.webkitIsFullScreen;
  3626. }
  3627. else if (document.msIsFullScreen !== undefined) {
  3628. _this.isFullscreen = document.msIsFullScreen;
  3629. }
  3630. // Pointer lock
  3631. if (_this.isFullscreen && _this._pointerLockRequested) {
  3632. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3633. if (canvas.requestPointerLock) {
  3634. canvas.requestPointerLock();
  3635. }
  3636. }
  3637. };
  3638. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3639. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3640. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3641. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3642. // Pointer lock
  3643. this._onPointerLockChange = function () {
  3644. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3645. };
  3646. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3647. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3648. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3649. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3650. if (!Engine.audioEngine) {
  3651. Engine.audioEngine = new BABYLON.AudioEngine();
  3652. }
  3653. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3654. }
  3655. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3656. get: function () {
  3657. return Engine._ALPHA_DISABLE;
  3658. },
  3659. enumerable: true,
  3660. configurable: true
  3661. });
  3662. Object.defineProperty(Engine, "ALPHA_ADD", {
  3663. get: function () {
  3664. return Engine._ALPHA_ADD;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3670. get: function () {
  3671. return Engine._ALPHA_COMBINE;
  3672. },
  3673. enumerable: true,
  3674. configurable: true
  3675. });
  3676. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3677. get: function () {
  3678. return Engine._DELAYLOADSTATE_NONE;
  3679. },
  3680. enumerable: true,
  3681. configurable: true
  3682. });
  3683. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3684. get: function () {
  3685. return Engine._DELAYLOADSTATE_LOADED;
  3686. },
  3687. enumerable: true,
  3688. configurable: true
  3689. });
  3690. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3691. get: function () {
  3692. return Engine._DELAYLOADSTATE_LOADING;
  3693. },
  3694. enumerable: true,
  3695. configurable: true
  3696. });
  3697. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3698. get: function () {
  3699. return Engine._DELAYLOADSTATE_NOTLOADED;
  3700. },
  3701. enumerable: true,
  3702. configurable: true
  3703. });
  3704. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3705. get: function () {
  3706. return Engine._TEXTUREFORMAT_ALPHA;
  3707. },
  3708. enumerable: true,
  3709. configurable: true
  3710. });
  3711. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3712. get: function () {
  3713. return Engine._TEXTUREFORMAT_LUMINANCE;
  3714. },
  3715. enumerable: true,
  3716. configurable: true
  3717. });
  3718. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3719. get: function () {
  3720. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3721. },
  3722. enumerable: true,
  3723. configurable: true
  3724. });
  3725. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3726. get: function () {
  3727. return Engine._TEXTUREFORMAT_RGB;
  3728. },
  3729. enumerable: true,
  3730. configurable: true
  3731. });
  3732. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3733. get: function () {
  3734. return Engine._TEXTUREFORMAT_RGBA;
  3735. },
  3736. enumerable: true,
  3737. configurable: true
  3738. });
  3739. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3740. get: function () {
  3741. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3747. get: function () {
  3748. return Engine._TEXTURETYPE_FLOAT;
  3749. },
  3750. enumerable: true,
  3751. configurable: true
  3752. });
  3753. Object.defineProperty(Engine, "Version", {
  3754. get: function () {
  3755. return "2.0.0";
  3756. },
  3757. enumerable: true,
  3758. configurable: true
  3759. });
  3760. Engine.prototype.getGlInfo = function () {
  3761. return {
  3762. vendor: this._glVendor,
  3763. renderer: this._glRenderer,
  3764. version: this._glVersion
  3765. };
  3766. };
  3767. Engine.prototype.getAspectRatio = function (camera) {
  3768. var viewport = camera.viewport;
  3769. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3770. };
  3771. Engine.prototype.getRenderWidth = function () {
  3772. if (this._currentRenderTarget) {
  3773. return this._currentRenderTarget._width;
  3774. }
  3775. return this._renderingCanvas.width;
  3776. };
  3777. Engine.prototype.getRenderHeight = function () {
  3778. if (this._currentRenderTarget) {
  3779. return this._currentRenderTarget._height;
  3780. }
  3781. return this._renderingCanvas.height;
  3782. };
  3783. Engine.prototype.getRenderingCanvas = function () {
  3784. return this._renderingCanvas;
  3785. };
  3786. Engine.prototype.getRenderingCanvasClientRect = function () {
  3787. return this._renderingCanvas.getBoundingClientRect();
  3788. };
  3789. Engine.prototype.setHardwareScalingLevel = function (level) {
  3790. this._hardwareScalingLevel = level;
  3791. this.resize();
  3792. };
  3793. Engine.prototype.getHardwareScalingLevel = function () {
  3794. return this._hardwareScalingLevel;
  3795. };
  3796. Engine.prototype.getLoadedTexturesCache = function () {
  3797. return this._loadedTexturesCache;
  3798. };
  3799. Engine.prototype.getCaps = function () {
  3800. return this._caps;
  3801. };
  3802. Object.defineProperty(Engine.prototype, "drawCalls", {
  3803. get: function () {
  3804. return this._drawCalls;
  3805. },
  3806. enumerable: true,
  3807. configurable: true
  3808. });
  3809. // Methods
  3810. Engine.prototype.resetDrawCalls = function () {
  3811. this._drawCalls = 0;
  3812. };
  3813. Engine.prototype.setDepthFunctionToGreater = function () {
  3814. this._depthCullingState.depthFunc = this._gl.GREATER;
  3815. };
  3816. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3817. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3818. };
  3819. Engine.prototype.setDepthFunctionToLess = function () {
  3820. this._depthCullingState.depthFunc = this._gl.LESS;
  3821. };
  3822. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3823. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3824. };
  3825. /**
  3826. * stop executing a render loop function and remove it from the execution array
  3827. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3828. */
  3829. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3830. if (!renderFunction) {
  3831. this._activeRenderLoops = [];
  3832. return;
  3833. }
  3834. var index = this._activeRenderLoops.indexOf(renderFunction);
  3835. if (index >= 0) {
  3836. this._activeRenderLoops.splice(index, 1);
  3837. }
  3838. };
  3839. Engine.prototype._renderLoop = function () {
  3840. var _this = this;
  3841. var shouldRender = true;
  3842. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3843. shouldRender = false;
  3844. }
  3845. if (shouldRender) {
  3846. // Start new frame
  3847. this.beginFrame();
  3848. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3849. var renderFunction = this._activeRenderLoops[index];
  3850. renderFunction();
  3851. }
  3852. // Present
  3853. this.endFrame();
  3854. }
  3855. if (this._activeRenderLoops.length > 0) {
  3856. // Register new frame
  3857. BABYLON.Tools.QueueNewFrame(function () {
  3858. _this._renderLoop();
  3859. });
  3860. }
  3861. else {
  3862. this._renderingQueueLaunched = false;
  3863. }
  3864. };
  3865. /**
  3866. * Register and execute a render loop. The engine can have more than one render function.
  3867. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3868. * @example
  3869. * engine.runRenderLoop(function () {
  3870. * scene.render()
  3871. * })
  3872. */
  3873. Engine.prototype.runRenderLoop = function (renderFunction) {
  3874. var _this = this;
  3875. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3876. return;
  3877. }
  3878. this._activeRenderLoops.push(renderFunction);
  3879. if (!this._renderingQueueLaunched) {
  3880. this._renderingQueueLaunched = true;
  3881. BABYLON.Tools.QueueNewFrame(function () {
  3882. _this._renderLoop();
  3883. });
  3884. }
  3885. };
  3886. /**
  3887. * Toggle full screen mode.
  3888. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3889. */
  3890. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3891. if (this.isFullscreen) {
  3892. BABYLON.Tools.ExitFullscreen();
  3893. }
  3894. else {
  3895. this._pointerLockRequested = requestPointerLock;
  3896. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3897. }
  3898. };
  3899. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3900. this.applyStates();
  3901. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3902. if (this._depthCullingState.depthMask) {
  3903. this._gl.clearDepth(1.0);
  3904. }
  3905. var mode = 0;
  3906. if (backBuffer)
  3907. mode |= this._gl.COLOR_BUFFER_BIT;
  3908. if (depthStencil && this._depthCullingState.depthMask)
  3909. mode |= this._gl.DEPTH_BUFFER_BIT;
  3910. this._gl.clear(mode);
  3911. };
  3912. /**
  3913. * Set the WebGL's viewport
  3914. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3915. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3916. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3917. */
  3918. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3919. var width = requiredWidth || this._renderingCanvas.width;
  3920. var height = requiredHeight || this._renderingCanvas.height;
  3921. var x = viewport.x || 0;
  3922. var y = viewport.y || 0;
  3923. this._cachedViewport = viewport;
  3924. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3925. };
  3926. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3927. this._cachedViewport = null;
  3928. this._gl.viewport(x, y, width, height);
  3929. };
  3930. Engine.prototype.beginFrame = function () {
  3931. this._measureFps();
  3932. };
  3933. Engine.prototype.endFrame = function () {
  3934. //this.flushFramebuffer();
  3935. };
  3936. /**
  3937. * resize the view according to the canvas' size.
  3938. * @example
  3939. * window.addEventListener("resize", function () {
  3940. * engine.resize();
  3941. * });
  3942. */
  3943. Engine.prototype.resize = function () {
  3944. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3945. };
  3946. /**
  3947. * force a specific size of the canvas
  3948. * @param {number} width - the new canvas' width
  3949. * @param {number} height - the new canvas' height
  3950. */
  3951. Engine.prototype.setSize = function (width, height) {
  3952. this._renderingCanvas.width = width;
  3953. this._renderingCanvas.height = height;
  3954. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3955. };
  3956. Engine.prototype.bindFramebuffer = function (texture) {
  3957. this._currentRenderTarget = texture;
  3958. var gl = this._gl;
  3959. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3960. this._gl.viewport(0, 0, texture._width, texture._height);
  3961. this.wipeCaches();
  3962. };
  3963. Engine.prototype.unBindFramebuffer = function (texture) {
  3964. this._currentRenderTarget = null;
  3965. if (texture.generateMipMaps) {
  3966. var gl = this._gl;
  3967. gl.bindTexture(gl.TEXTURE_2D, texture);
  3968. gl.generateMipmap(gl.TEXTURE_2D);
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. }
  3971. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3972. };
  3973. Engine.prototype.flushFramebuffer = function () {
  3974. this._gl.flush();
  3975. };
  3976. Engine.prototype.restoreDefaultFramebuffer = function () {
  3977. this._currentRenderTarget = null;
  3978. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3979. this.setViewport(this._cachedViewport);
  3980. this.wipeCaches();
  3981. };
  3982. // VBOs
  3983. Engine.prototype._resetVertexBufferBinding = function () {
  3984. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3985. this._cachedVertexBuffers = null;
  3986. };
  3987. Engine.prototype.createVertexBuffer = function (vertices) {
  3988. var vbo = this._gl.createBuffer();
  3989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3991. this._resetVertexBufferBinding();
  3992. vbo.references = 1;
  3993. return vbo;
  3994. };
  3995. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3996. var vbo = this._gl.createBuffer();
  3997. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3998. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3999. this._resetVertexBufferBinding();
  4000. vbo.references = 1;
  4001. return vbo;
  4002. };
  4003. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4004. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4005. if (offset === undefined) {
  4006. offset = 0;
  4007. }
  4008. if (vertices instanceof Float32Array) {
  4009. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4010. }
  4011. else {
  4012. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4013. }
  4014. this._resetVertexBufferBinding();
  4015. };
  4016. Engine.prototype._resetIndexBufferBinding = function () {
  4017. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4018. this._cachedIndexBuffer = null;
  4019. };
  4020. Engine.prototype.createIndexBuffer = function (indices) {
  4021. var vbo = this._gl.createBuffer();
  4022. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4023. // Check for 32 bits indices
  4024. var arrayBuffer;
  4025. var need32Bits = false;
  4026. if (this._caps.uintIndices) {
  4027. for (var index = 0; index < indices.length; index++) {
  4028. if (indices[index] > 65535) {
  4029. need32Bits = true;
  4030. break;
  4031. }
  4032. }
  4033. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4034. }
  4035. else {
  4036. arrayBuffer = new Uint16Array(indices);
  4037. }
  4038. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4039. this._resetIndexBufferBinding();
  4040. vbo.references = 1;
  4041. vbo.is32Bits = need32Bits;
  4042. return vbo;
  4043. };
  4044. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4045. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4046. this._cachedVertexBuffers = vertexBuffer;
  4047. this._cachedEffectForVertexBuffers = effect;
  4048. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4049. var offset = 0;
  4050. for (var index = 0; index < vertexDeclaration.length; index++) {
  4051. var order = effect.getAttributeLocation(index);
  4052. if (order >= 0) {
  4053. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4054. }
  4055. offset += vertexDeclaration[index] * 4;
  4056. }
  4057. }
  4058. if (this._cachedIndexBuffer !== indexBuffer) {
  4059. this._cachedIndexBuffer = indexBuffer;
  4060. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4061. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4062. }
  4063. };
  4064. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4065. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4066. this._cachedVertexBuffers = vertexBuffers;
  4067. this._cachedEffectForVertexBuffers = effect;
  4068. var attributes = effect.getAttributesNames();
  4069. for (var index = 0; index < attributes.length; index++) {
  4070. var order = effect.getAttributeLocation(index);
  4071. if (order >= 0) {
  4072. var vertexBuffer = vertexBuffers[attributes[index]];
  4073. if (!vertexBuffer) {
  4074. continue;
  4075. }
  4076. var stride = vertexBuffer.getStrideSize();
  4077. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4078. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4079. }
  4080. }
  4081. }
  4082. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4083. this._cachedIndexBuffer = indexBuffer;
  4084. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4085. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4086. }
  4087. };
  4088. Engine.prototype._releaseBuffer = function (buffer) {
  4089. buffer.references--;
  4090. if (buffer.references === 0) {
  4091. this._gl.deleteBuffer(buffer);
  4092. return true;
  4093. }
  4094. return false;
  4095. };
  4096. Engine.prototype.createInstancesBuffer = function (capacity) {
  4097. var buffer = this._gl.createBuffer();
  4098. buffer.capacity = capacity;
  4099. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4100. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4101. return buffer;
  4102. };
  4103. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4104. this._gl.deleteBuffer(buffer);
  4105. };
  4106. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4107. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4109. for (var index = 0; index < 4; index++) {
  4110. var offsetLocation = offsetLocations[index];
  4111. this._gl.enableVertexAttribArray(offsetLocation);
  4112. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4113. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4114. }
  4115. };
  4116. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4117. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4118. for (var index = 0; index < 4; index++) {
  4119. var offsetLocation = offsetLocations[index];
  4120. this._gl.disableVertexAttribArray(offsetLocation);
  4121. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4122. }
  4123. };
  4124. Engine.prototype.applyStates = function () {
  4125. this._depthCullingState.apply(this._gl);
  4126. this._alphaState.apply(this._gl);
  4127. };
  4128. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4129. // Apply states
  4130. this.applyStates();
  4131. this._drawCalls++;
  4132. // Render
  4133. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4134. if (instancesCount) {
  4135. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4136. return;
  4137. }
  4138. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4139. };
  4140. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4141. // Apply states
  4142. this.applyStates();
  4143. this._drawCalls++;
  4144. if (instancesCount) {
  4145. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4146. return;
  4147. }
  4148. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4149. };
  4150. // Shaders
  4151. Engine.prototype._releaseEffect = function (effect) {
  4152. if (this._compiledEffects[effect._key]) {
  4153. delete this._compiledEffects[effect._key];
  4154. if (effect.getProgram()) {
  4155. this._gl.deleteProgram(effect.getProgram());
  4156. }
  4157. }
  4158. };
  4159. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4160. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4161. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4162. var name = vertex + "+" + fragment + "@" + defines;
  4163. if (this._compiledEffects[name]) {
  4164. return this._compiledEffects[name];
  4165. }
  4166. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4167. effect._key = name;
  4168. this._compiledEffects[name] = effect;
  4169. return effect;
  4170. };
  4171. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4172. if (uniformsNames === void 0) { uniformsNames = []; }
  4173. if (samplers === void 0) { samplers = []; }
  4174. if (defines === void 0) { defines = ""; }
  4175. return this.createEffect({
  4176. vertex: "particles",
  4177. fragmentElement: fragmentName
  4178. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4179. };
  4180. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4181. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4182. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4183. var shaderProgram = this._gl.createProgram();
  4184. this._gl.attachShader(shaderProgram, vertexShader);
  4185. this._gl.attachShader(shaderProgram, fragmentShader);
  4186. this._gl.linkProgram(shaderProgram);
  4187. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4188. if (!linked) {
  4189. var error = this._gl.getProgramInfoLog(shaderProgram);
  4190. if (error) {
  4191. throw new Error(error);
  4192. }
  4193. }
  4194. this._gl.deleteShader(vertexShader);
  4195. this._gl.deleteShader(fragmentShader);
  4196. return shaderProgram;
  4197. };
  4198. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4199. var results = [];
  4200. for (var index = 0; index < uniformsNames.length; index++) {
  4201. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4202. }
  4203. return results;
  4204. };
  4205. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4206. var results = [];
  4207. for (var index = 0; index < attributesNames.length; index++) {
  4208. try {
  4209. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4210. }
  4211. catch (e) {
  4212. results.push(-1);
  4213. }
  4214. }
  4215. return results;
  4216. };
  4217. Engine.prototype.enableEffect = function (effect) {
  4218. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4219. if (effect && effect.onBind) {
  4220. effect.onBind(effect);
  4221. }
  4222. return;
  4223. }
  4224. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4225. // Use program
  4226. this._gl.useProgram(effect.getProgram());
  4227. for (var i in this._vertexAttribArrays) {
  4228. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4229. continue;
  4230. }
  4231. this._vertexAttribArrays[i] = false;
  4232. this._gl.disableVertexAttribArray(i);
  4233. }
  4234. var attributesCount = effect.getAttributesCount();
  4235. for (var index = 0; index < attributesCount; index++) {
  4236. // Attributes
  4237. var order = effect.getAttributeLocation(index);
  4238. if (order >= 0) {
  4239. this._vertexAttribArrays[order] = true;
  4240. this._gl.enableVertexAttribArray(order);
  4241. }
  4242. }
  4243. this._currentEffect = effect;
  4244. if (effect.onBind) {
  4245. effect.onBind(effect);
  4246. }
  4247. };
  4248. Engine.prototype.setArray = function (uniform, array) {
  4249. if (!uniform)
  4250. return;
  4251. this._gl.uniform1fv(uniform, array);
  4252. };
  4253. Engine.prototype.setArray2 = function (uniform, array) {
  4254. if (!uniform || array.length % 2 !== 0)
  4255. return;
  4256. this._gl.uniform2fv(uniform, array);
  4257. };
  4258. Engine.prototype.setArray3 = function (uniform, array) {
  4259. if (!uniform || array.length % 3 !== 0)
  4260. return;
  4261. this._gl.uniform3fv(uniform, array);
  4262. };
  4263. Engine.prototype.setArray4 = function (uniform, array) {
  4264. if (!uniform || array.length % 4 !== 0)
  4265. return;
  4266. this._gl.uniform4fv(uniform, array);
  4267. };
  4268. Engine.prototype.setMatrices = function (uniform, matrices) {
  4269. if (!uniform)
  4270. return;
  4271. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4272. };
  4273. Engine.prototype.setMatrix = function (uniform, matrix) {
  4274. if (!uniform)
  4275. return;
  4276. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4277. };
  4278. Engine.prototype.setFloat = function (uniform, value) {
  4279. if (!uniform)
  4280. return;
  4281. this._gl.uniform1f(uniform, value);
  4282. };
  4283. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4284. if (!uniform)
  4285. return;
  4286. this._gl.uniform2f(uniform, x, y);
  4287. };
  4288. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4289. if (!uniform)
  4290. return;
  4291. this._gl.uniform3f(uniform, x, y, z);
  4292. };
  4293. Engine.prototype.setBool = function (uniform, bool) {
  4294. if (!uniform)
  4295. return;
  4296. this._gl.uniform1i(uniform, bool);
  4297. };
  4298. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4299. if (!uniform)
  4300. return;
  4301. this._gl.uniform4f(uniform, x, y, z, w);
  4302. };
  4303. Engine.prototype.setColor3 = function (uniform, color3) {
  4304. if (!uniform)
  4305. return;
  4306. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4307. };
  4308. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4309. if (!uniform)
  4310. return;
  4311. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4312. };
  4313. // States
  4314. Engine.prototype.setState = function (culling, force) {
  4315. // Culling
  4316. if (this._depthCullingState.cull !== culling || force) {
  4317. if (culling) {
  4318. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4319. this._depthCullingState.cull = true;
  4320. }
  4321. else {
  4322. this._depthCullingState.cull = false;
  4323. }
  4324. }
  4325. };
  4326. Engine.prototype.setDepthBuffer = function (enable) {
  4327. this._depthCullingState.depthTest = enable;
  4328. };
  4329. Engine.prototype.getDepthWrite = function () {
  4330. return this._depthCullingState.depthMask;
  4331. };
  4332. Engine.prototype.setDepthWrite = function (enable) {
  4333. this._depthCullingState.depthMask = enable;
  4334. };
  4335. Engine.prototype.setColorWrite = function (enable) {
  4336. this._gl.colorMask(enable, enable, enable, enable);
  4337. };
  4338. Engine.prototype.setAlphaMode = function (mode) {
  4339. switch (mode) {
  4340. case Engine.ALPHA_DISABLE:
  4341. this.setDepthWrite(true);
  4342. this._alphaState.alphaBlend = false;
  4343. break;
  4344. case Engine.ALPHA_COMBINE:
  4345. this.setDepthWrite(false);
  4346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4347. this._alphaState.alphaBlend = true;
  4348. break;
  4349. case Engine.ALPHA_ADD:
  4350. this.setDepthWrite(false);
  4351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4352. this._alphaState.alphaBlend = true;
  4353. break;
  4354. }
  4355. this._alphaMode = mode;
  4356. };
  4357. Engine.prototype.getAlphaMode = function () {
  4358. return this._alphaMode;
  4359. };
  4360. Engine.prototype.setAlphaTesting = function (enable) {
  4361. this._alphaTest = enable;
  4362. };
  4363. Engine.prototype.getAlphaTesting = function () {
  4364. return this._alphaTest;
  4365. };
  4366. // Textures
  4367. Engine.prototype.wipeCaches = function () {
  4368. this._activeTexturesCache = [];
  4369. this._currentEffect = null;
  4370. this._depthCullingState.reset();
  4371. this._alphaState.reset();
  4372. this._cachedVertexBuffers = null;
  4373. this._cachedIndexBuffer = null;
  4374. this._cachedEffectForVertexBuffers = null;
  4375. };
  4376. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4377. var gl = this._gl;
  4378. gl.bindTexture(gl.TEXTURE_2D, texture);
  4379. var magFilter = gl.NEAREST;
  4380. var minFilter = gl.NEAREST;
  4381. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4382. magFilter = gl.LINEAR;
  4383. minFilter = gl.LINEAR;
  4384. }
  4385. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4386. magFilter = gl.LINEAR;
  4387. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4388. }
  4389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4391. gl.bindTexture(gl.TEXTURE_2D, null);
  4392. texture.samplingMode = samplingMode;
  4393. };
  4394. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4395. var _this = this;
  4396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4397. if (onLoad === void 0) { onLoad = null; }
  4398. if (onError === void 0) { onError = null; }
  4399. if (buffer === void 0) { buffer = null; }
  4400. var texture = this._gl.createTexture();
  4401. var extension;
  4402. var fromData = false;
  4403. if (url.substr(0, 5) === "data:") {
  4404. fromData = true;
  4405. }
  4406. if (!fromData)
  4407. extension = url.substr(url.length - 4, 4).toLowerCase();
  4408. else {
  4409. var oldUrl = url;
  4410. fromData = oldUrl.split(':');
  4411. url = oldUrl;
  4412. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4413. }
  4414. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4415. var isTGA = (extension === ".tga");
  4416. scene._addPendingData(texture);
  4417. texture.url = url;
  4418. texture.noMipmap = noMipmap;
  4419. texture.references = 1;
  4420. this._loadedTexturesCache.push(texture);
  4421. var onerror = function () {
  4422. scene._removePendingData(texture);
  4423. if (onError) {
  4424. onError();
  4425. }
  4426. };
  4427. if (isTGA) {
  4428. var callback = function (arrayBuffer) {
  4429. var data = new Uint8Array(arrayBuffer);
  4430. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4431. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4432. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4433. if (onLoad) {
  4434. onLoad();
  4435. }
  4436. }, samplingMode);
  4437. };
  4438. if (!(fromData instanceof Array))
  4439. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4440. callback(arrayBuffer);
  4441. }, onerror, scene.database, true);
  4442. else
  4443. callback(buffer);
  4444. }
  4445. else if (isDDS) {
  4446. callback = function (data) {
  4447. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4448. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4449. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4450. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4451. if (onLoad) {
  4452. onLoad();
  4453. }
  4454. }, samplingMode);
  4455. };
  4456. if (!(fromData instanceof Array))
  4457. BABYLON.Tools.LoadFile(url, function (data) {
  4458. callback(data);
  4459. }, onerror, scene.database, true);
  4460. else
  4461. callback(buffer);
  4462. }
  4463. else {
  4464. var onload = function (img) {
  4465. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4466. var isPot = (img.width === potWidth && img.height === potHeight);
  4467. if (!isPot) {
  4468. _this._workingCanvas.width = potWidth;
  4469. _this._workingCanvas.height = potHeight;
  4470. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4471. _this._workingContext.imageSmoothingEnabled = false;
  4472. _this._workingContext.mozImageSmoothingEnabled = false;
  4473. _this._workingContext.oImageSmoothingEnabled = false;
  4474. _this._workingContext.webkitImageSmoothingEnabled = false;
  4475. _this._workingContext.msImageSmoothingEnabled = false;
  4476. }
  4477. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4478. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4479. _this._workingContext.imageSmoothingEnabled = true;
  4480. _this._workingContext.mozImageSmoothingEnabled = true;
  4481. _this._workingContext.oImageSmoothingEnabled = true;
  4482. _this._workingContext.webkitImageSmoothingEnabled = true;
  4483. _this._workingContext.msImageSmoothingEnabled = true;
  4484. }
  4485. }
  4486. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4487. if (onLoad) {
  4488. onLoad();
  4489. }
  4490. }, samplingMode);
  4491. };
  4492. if (!(fromData instanceof Array))
  4493. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4494. else
  4495. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4496. }
  4497. return texture;
  4498. };
  4499. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4500. var texture = this._gl.createTexture();
  4501. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4502. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4503. // Format
  4504. var internalFormat = this._gl.RGBA;
  4505. switch (format) {
  4506. case Engine.TEXTUREFORMAT_ALPHA:
  4507. internalFormat = this._gl.ALPHA;
  4508. break;
  4509. case Engine.TEXTUREFORMAT_LUMINANCE:
  4510. internalFormat = this._gl.LUMINANCE;
  4511. break;
  4512. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4513. internalFormat = this._gl.LUMINANCE_ALPHA;
  4514. break;
  4515. case Engine.TEXTUREFORMAT_RGB:
  4516. internalFormat = this._gl.RGB;
  4517. break;
  4518. case Engine.TEXTUREFORMAT_RGBA:
  4519. internalFormat = this._gl.RGBA;
  4520. break;
  4521. }
  4522. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4523. if (generateMipMaps) {
  4524. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4525. }
  4526. // Filters
  4527. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4530. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4531. this._activeTexturesCache = [];
  4532. texture._baseWidth = width;
  4533. texture._baseHeight = height;
  4534. texture._width = width;
  4535. texture._height = height;
  4536. texture.isReady = true;
  4537. texture.references = 1;
  4538. texture.samplingMode = samplingMode;
  4539. this._loadedTexturesCache.push(texture);
  4540. return texture;
  4541. };
  4542. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4543. var texture = this._gl.createTexture();
  4544. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4545. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4546. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4547. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4550. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4551. this._activeTexturesCache = [];
  4552. texture._baseWidth = width;
  4553. texture._baseHeight = height;
  4554. texture._width = width;
  4555. texture._height = height;
  4556. texture.isReady = false;
  4557. texture.generateMipMaps = generateMipMaps;
  4558. texture.references = 1;
  4559. texture.samplingMode = samplingMode;
  4560. this._loadedTexturesCache.push(texture);
  4561. return texture;
  4562. };
  4563. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4564. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4565. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4566. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4567. if (texture.generateMipMaps) {
  4568. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4569. }
  4570. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4571. this._activeTexturesCache = [];
  4572. texture.isReady = true;
  4573. };
  4574. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4575. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4576. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4577. // Scale the video if it is a NPOT using the current working canvas
  4578. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4579. if (!texture._workingCanvas) {
  4580. texture._workingCanvas = document.createElement("canvas");
  4581. texture._workingContext = texture._workingCanvas.getContext("2d");
  4582. texture._workingCanvas.width = texture._width;
  4583. texture._workingCanvas.height = texture._height;
  4584. }
  4585. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4586. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4587. }
  4588. else {
  4589. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4590. }
  4591. if (texture.generateMipMaps) {
  4592. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4593. }
  4594. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4595. this._activeTexturesCache = [];
  4596. texture.isReady = true;
  4597. };
  4598. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4599. // old version had a "generateMipMaps" arg instead of options.
  4600. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4601. // in the same way, generateDepthBuffer is defaulted to true
  4602. var generateMipMaps = false;
  4603. var generateDepthBuffer = true;
  4604. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4605. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4606. if (options !== undefined) {
  4607. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4608. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4609. type = options.type === undefined ? type : options.type;
  4610. if (options.samplingMode !== undefined) {
  4611. samplingMode = options.samplingMode;
  4612. }
  4613. if (type === Engine.TEXTURETYPE_FLOAT) {
  4614. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4615. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4616. }
  4617. }
  4618. var gl = this._gl;
  4619. var texture = gl.createTexture();
  4620. gl.bindTexture(gl.TEXTURE_2D, texture);
  4621. var width = size.width || size;
  4622. var height = size.height || size;
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4624. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4625. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4626. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4627. }
  4628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4632. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4633. var depthBuffer;
  4634. // Create the depth buffer
  4635. if (generateDepthBuffer) {
  4636. depthBuffer = gl.createRenderbuffer();
  4637. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4638. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4639. }
  4640. // Create the framebuffer
  4641. var framebuffer = gl.createFramebuffer();
  4642. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4644. if (generateDepthBuffer) {
  4645. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4646. }
  4647. // Unbind
  4648. gl.bindTexture(gl.TEXTURE_2D, null);
  4649. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4650. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4651. texture._framebuffer = framebuffer;
  4652. if (generateDepthBuffer) {
  4653. texture._depthBuffer = depthBuffer;
  4654. }
  4655. texture._width = width;
  4656. texture._height = height;
  4657. texture.isReady = true;
  4658. texture.generateMipMaps = generateMipMaps;
  4659. texture.references = 1;
  4660. texture.samplingMode = samplingMode;
  4661. this._activeTexturesCache = [];
  4662. this._loadedTexturesCache.push(texture);
  4663. return texture;
  4664. };
  4665. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4666. var _this = this;
  4667. var gl = this._gl;
  4668. var texture = gl.createTexture();
  4669. texture.isCube = true;
  4670. texture.url = rootUrl;
  4671. texture.references = 1;
  4672. this._loadedTexturesCache.push(texture);
  4673. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4674. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4675. if (isDDS) {
  4676. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4677. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4678. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4679. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4680. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4681. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4682. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4684. }
  4685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4689. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4690. _this._activeTexturesCache = [];
  4691. texture._width = info.width;
  4692. texture._height = info.height;
  4693. texture.isReady = true;
  4694. }, null, null, true);
  4695. }
  4696. else {
  4697. cascadeLoad(rootUrl, scene, function (imgs) {
  4698. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4699. var height = width;
  4700. _this._workingCanvas.width = width;
  4701. _this._workingCanvas.height = height;
  4702. var faces = [
  4703. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4704. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4705. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4706. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4707. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4708. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4709. ];
  4710. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4711. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4712. for (var index = 0; index < faces.length; index++) {
  4713. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4714. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4715. }
  4716. if (!noMipmap) {
  4717. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4718. }
  4719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4723. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4724. _this._activeTexturesCache = [];
  4725. texture._width = width;
  4726. texture._height = height;
  4727. texture.isReady = true;
  4728. }, extensions);
  4729. }
  4730. return texture;
  4731. };
  4732. Engine.prototype._releaseTexture = function (texture) {
  4733. var gl = this._gl;
  4734. if (texture._framebuffer) {
  4735. gl.deleteFramebuffer(texture._framebuffer);
  4736. }
  4737. if (texture._depthBuffer) {
  4738. gl.deleteRenderbuffer(texture._depthBuffer);
  4739. }
  4740. gl.deleteTexture(texture);
  4741. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4742. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4743. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4744. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4745. this._activeTexturesCache[channel] = null;
  4746. }
  4747. var index = this._loadedTexturesCache.indexOf(texture);
  4748. if (index !== -1) {
  4749. this._loadedTexturesCache.splice(index, 1);
  4750. }
  4751. };
  4752. Engine.prototype.bindSamplers = function (effect) {
  4753. this._gl.useProgram(effect.getProgram());
  4754. var samplers = effect.getSamplers();
  4755. for (var index = 0; index < samplers.length; index++) {
  4756. var uniform = effect.getUniform(samplers[index]);
  4757. this._gl.uniform1i(uniform, index);
  4758. }
  4759. this._currentEffect = null;
  4760. };
  4761. Engine.prototype._bindTexture = function (channel, texture) {
  4762. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4763. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4764. this._activeTexturesCache[channel] = null;
  4765. };
  4766. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4767. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4768. };
  4769. Engine.prototype.setTexture = function (channel, texture) {
  4770. if (channel < 0) {
  4771. return;
  4772. }
  4773. // Not ready?
  4774. if (!texture || !texture.isReady()) {
  4775. if (this._activeTexturesCache[channel] != null) {
  4776. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4777. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4778. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4779. this._activeTexturesCache[channel] = null;
  4780. }
  4781. return;
  4782. }
  4783. // Video
  4784. if (texture instanceof BABYLON.VideoTexture) {
  4785. if (texture.update()) {
  4786. this._activeTexturesCache[channel] = null;
  4787. }
  4788. }
  4789. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4790. texture.delayLoad();
  4791. return;
  4792. }
  4793. if (this._activeTexturesCache[channel] === texture) {
  4794. return;
  4795. }
  4796. this._activeTexturesCache[channel] = texture;
  4797. var internalTexture = texture.getInternalTexture();
  4798. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4799. if (internalTexture.isCube) {
  4800. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4801. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4802. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4803. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4804. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4805. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4806. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4807. }
  4808. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4809. }
  4810. else {
  4811. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4812. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4813. internalTexture._cachedWrapU = texture.wrapU;
  4814. switch (texture.wrapU) {
  4815. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4817. break;
  4818. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4820. break;
  4821. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4822. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4823. break;
  4824. }
  4825. }
  4826. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4827. internalTexture._cachedWrapV = texture.wrapV;
  4828. switch (texture.wrapV) {
  4829. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4831. break;
  4832. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4833. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4834. break;
  4835. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4837. break;
  4838. }
  4839. }
  4840. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4841. }
  4842. };
  4843. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4844. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4845. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4846. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4847. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4848. }
  4849. };
  4850. Engine.prototype.readPixels = function (x, y, width, height) {
  4851. var data = new Uint8Array(height * width * 4);
  4852. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4853. return data;
  4854. };
  4855. // Dispose
  4856. Engine.prototype.dispose = function () {
  4857. this.hideLoadingUI();
  4858. this.stopRenderLoop();
  4859. while (this.scenes.length) {
  4860. this.scenes[0].dispose();
  4861. }
  4862. // Release audio engine
  4863. Engine.audioEngine.dispose();
  4864. for (var name in this._compiledEffects) {
  4865. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4866. }
  4867. for (var i in this._vertexAttribArrays) {
  4868. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4869. continue;
  4870. }
  4871. this._gl.disableVertexAttribArray(i);
  4872. }
  4873. // Events
  4874. window.removeEventListener("blur", this._onBlur);
  4875. window.removeEventListener("focus", this._onFocus);
  4876. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4877. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4878. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4879. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4880. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4881. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4882. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4883. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4884. };
  4885. // Loading screen
  4886. Engine.prototype.displayLoadingUI = function () {
  4887. var _this = this;
  4888. this._loadingDiv = document.createElement("div");
  4889. this._loadingDiv.style.opacity = "0";
  4890. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4891. // Loading text
  4892. this._loadingTextDiv = document.createElement("div");
  4893. this._loadingTextDiv.style.position = "absolute";
  4894. this._loadingTextDiv.style.left = "0";
  4895. this._loadingTextDiv.style.top = "50%";
  4896. this._loadingTextDiv.style.marginTop = "80px";
  4897. this._loadingTextDiv.style.width = "100%";
  4898. this._loadingTextDiv.style.height = "20px";
  4899. this._loadingTextDiv.style.fontFamily = "Arial";
  4900. this._loadingTextDiv.style.fontSize = "14px";
  4901. this._loadingTextDiv.style.color = "white";
  4902. this._loadingTextDiv.style.textAlign = "center";
  4903. this._loadingTextDiv.innerHTML = "Loading";
  4904. this._loadingDiv.appendChild(this._loadingTextDiv);
  4905. // Loading img
  4906. var imgBack = new Image();
  4907. 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==";
  4908. imgBack.style.position = "absolute";
  4909. imgBack.style.left = "50%";
  4910. imgBack.style.top = "50%";
  4911. imgBack.style.marginLeft = "-50px";
  4912. imgBack.style.marginTop = "-50px";
  4913. imgBack.style.transition = "transform 1.0s ease";
  4914. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4915. var deg = 360;
  4916. var onTransitionEnd = function () {
  4917. deg += 360;
  4918. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4919. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4920. };
  4921. imgBack.addEventListener("transitionend", onTransitionEnd);
  4922. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4923. this._loadingDiv.appendChild(imgBack);
  4924. // front image
  4925. var imgFront = new Image();
  4926. 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=";
  4927. imgFront.style.position = "absolute";
  4928. imgFront.style.left = "50%";
  4929. imgFront.style.top = "50%";
  4930. imgFront.style.marginLeft = "-50px";
  4931. imgFront.style.marginTop = "-50px";
  4932. this._loadingDiv.appendChild(imgFront);
  4933. // Resize
  4934. this._resizeLoadingUI = function () {
  4935. var canvasRect = _this.getRenderingCanvasClientRect();
  4936. _this._loadingDiv.style.position = "absolute";
  4937. _this._loadingDiv.style.left = canvasRect.left + "px";
  4938. _this._loadingDiv.style.top = canvasRect.top + "px";
  4939. _this._loadingDiv.style.width = canvasRect.width + "px";
  4940. _this._loadingDiv.style.height = canvasRect.height + "px";
  4941. };
  4942. this._resizeLoadingUI();
  4943. window.addEventListener("resize", this._resizeLoadingUI);
  4944. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4945. document.body.appendChild(this._loadingDiv);
  4946. setTimeout(function () {
  4947. _this._loadingDiv.style.opacity = "1";
  4948. imgBack.style.transform = "rotateZ(360deg)";
  4949. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4950. }, 0);
  4951. };
  4952. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4953. set: function (text) {
  4954. if (!this._loadingDiv) {
  4955. return;
  4956. }
  4957. this._loadingTextDiv.innerHTML = text;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4963. get: function () {
  4964. return this._loadingDivBackgroundColor;
  4965. },
  4966. set: function (color) {
  4967. this._loadingDivBackgroundColor = color;
  4968. if (!this._loadingDiv) {
  4969. return;
  4970. }
  4971. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Engine.prototype.hideLoadingUI = function () {
  4977. var _this = this;
  4978. if (!this._loadingDiv) {
  4979. return;
  4980. }
  4981. var onTransitionEnd = function () {
  4982. if (!_this._loadingDiv) {
  4983. return;
  4984. }
  4985. document.body.removeChild(_this._loadingDiv);
  4986. window.removeEventListener("resize", _this._resizeLoadingUI);
  4987. _this._loadingDiv = null;
  4988. };
  4989. this._loadingDiv.style.opacity = "0";
  4990. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4991. };
  4992. // FPS
  4993. Engine.prototype.getFps = function () {
  4994. return this.fps;
  4995. };
  4996. Engine.prototype.getDeltaTime = function () {
  4997. return this.deltaTime;
  4998. };
  4999. Engine.prototype._measureFps = function () {
  5000. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5001. var length = this.previousFramesDuration.length;
  5002. if (length >= 2) {
  5003. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5004. }
  5005. if (length >= this.fpsRange) {
  5006. if (length > this.fpsRange) {
  5007. this.previousFramesDuration.splice(0, 1);
  5008. length = this.previousFramesDuration.length;
  5009. }
  5010. var sum = 0;
  5011. for (var id = 0; id < length - 1; id++) {
  5012. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5013. }
  5014. this.fps = 1000.0 / (sum / (length - 1));
  5015. }
  5016. };
  5017. // Statics
  5018. Engine.isSupported = function () {
  5019. try {
  5020. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5021. if (navigator.isCocoonJS) {
  5022. return true;
  5023. }
  5024. var tempcanvas = document.createElement("canvas");
  5025. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5026. return gl != null && !!window.WebGLRenderingContext;
  5027. }
  5028. catch (e) {
  5029. return false;
  5030. }
  5031. };
  5032. // Const statics
  5033. Engine._ALPHA_DISABLE = 0;
  5034. Engine._ALPHA_ADD = 1;
  5035. Engine._ALPHA_COMBINE = 2;
  5036. Engine._DELAYLOADSTATE_NONE = 0;
  5037. Engine._DELAYLOADSTATE_LOADED = 1;
  5038. Engine._DELAYLOADSTATE_LOADING = 2;
  5039. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5040. Engine._TEXTUREFORMAT_ALPHA = 0;
  5041. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5042. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5043. Engine._TEXTUREFORMAT_RGB = 4;
  5044. Engine._TEXTUREFORMAT_RGBA = 4;
  5045. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5046. Engine._TEXTURETYPE_FLOAT = 1;
  5047. // Updatable statics so stick with vars here
  5048. Engine.Epsilon = 0.001;
  5049. Engine.CollisionsEpsilon = 0.001;
  5050. Engine.ShadersRepository = "Babylon/Shaders/";
  5051. return Engine;
  5052. })();
  5053. BABYLON.Engine = Engine;
  5054. })(BABYLON || (BABYLON = {}));
  5055. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5056. (function (BABYLON) {
  5057. /**
  5058. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5059. */
  5060. var Node = (function () {
  5061. /**
  5062. * @constructor
  5063. * @param {string} name - the name and id to be given to this node
  5064. * @param {BABYLON.Scene} the scene this node will be added to
  5065. */
  5066. function Node(name, scene) {
  5067. this.state = "";
  5068. this.animations = new Array();
  5069. this._childrenFlag = -1;
  5070. this._isEnabled = true;
  5071. this._isReady = true;
  5072. this._currentRenderId = -1;
  5073. this.name = name;
  5074. this.id = name;
  5075. this._scene = scene;
  5076. this._initCache();
  5077. }
  5078. Node.prototype.getScene = function () {
  5079. return this._scene;
  5080. };
  5081. Node.prototype.getEngine = function () {
  5082. return this._scene.getEngine();
  5083. };
  5084. // override it in derived class
  5085. Node.prototype.getWorldMatrix = function () {
  5086. return BABYLON.Matrix.Identity();
  5087. };
  5088. // override it in derived class if you add new variables to the cache
  5089. // and call the parent class method
  5090. Node.prototype._initCache = function () {
  5091. this._cache = {};
  5092. this._cache.parent = undefined;
  5093. };
  5094. Node.prototype.updateCache = function (force) {
  5095. if (!force && this.isSynchronized())
  5096. return;
  5097. this._cache.parent = this.parent;
  5098. this._updateCache();
  5099. };
  5100. // override it in derived class if you add new variables to the cache
  5101. // and call the parent class method if !ignoreParentClass
  5102. Node.prototype._updateCache = function (ignoreParentClass) {
  5103. };
  5104. // override it in derived class if you add new variables to the cache
  5105. Node.prototype._isSynchronized = function () {
  5106. return true;
  5107. };
  5108. Node.prototype.isSynchronizedWithParent = function () {
  5109. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5110. };
  5111. Node.prototype.isSynchronized = function (updateCache) {
  5112. var check = this.hasNewParent();
  5113. check = check || !this.isSynchronizedWithParent();
  5114. check = check || !this._isSynchronized();
  5115. if (updateCache)
  5116. this.updateCache(true);
  5117. return !check;
  5118. };
  5119. Node.prototype.hasNewParent = function (update) {
  5120. if (this._cache.parent === this.parent)
  5121. return false;
  5122. if (update)
  5123. this._cache.parent = this.parent;
  5124. return true;
  5125. };
  5126. /**
  5127. * Is this node ready to be used/rendered
  5128. * @return {boolean} is it ready
  5129. */
  5130. Node.prototype.isReady = function () {
  5131. return this._isReady;
  5132. };
  5133. /**
  5134. * Is this node enabled.
  5135. * If the node has a parent and is enabled, the parent will be inspected as well.
  5136. * @return {boolean} whether this node (and its parent) is enabled.
  5137. * @see setEnabled
  5138. */
  5139. Node.prototype.isEnabled = function () {
  5140. if (!this._isEnabled) {
  5141. return false;
  5142. }
  5143. if (this.parent) {
  5144. return this.parent.isEnabled();
  5145. }
  5146. return true;
  5147. };
  5148. /**
  5149. * Set the enabled state of this node.
  5150. * @param {boolean} value - the new enabled state
  5151. * @see isEnabled
  5152. */
  5153. Node.prototype.setEnabled = function (value) {
  5154. this._isEnabled = value;
  5155. };
  5156. /**
  5157. * Is this node a descendant of the given node.
  5158. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5159. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5160. * @see parent
  5161. */
  5162. Node.prototype.isDescendantOf = function (ancestor) {
  5163. if (this.parent) {
  5164. if (this.parent === ancestor) {
  5165. return true;
  5166. }
  5167. return this.parent.isDescendantOf(ancestor);
  5168. }
  5169. return false;
  5170. };
  5171. Node.prototype._getDescendants = function (list, results) {
  5172. for (var index = 0; index < list.length; index++) {
  5173. var item = list[index];
  5174. if (item.isDescendantOf(this)) {
  5175. results.push(item);
  5176. }
  5177. }
  5178. };
  5179. /**
  5180. * Will return all nodes that have this node as parent.
  5181. * @return {BABYLON.Node[]} all children nodes of all types.
  5182. */
  5183. Node.prototype.getDescendants = function () {
  5184. var results = [];
  5185. this._getDescendants(this._scene.meshes, results);
  5186. this._getDescendants(this._scene.lights, results);
  5187. this._getDescendants(this._scene.cameras, results);
  5188. return results;
  5189. };
  5190. Node.prototype._setReady = function (state) {
  5191. if (state == this._isReady) {
  5192. return;
  5193. }
  5194. if (!state) {
  5195. this._isReady = false;
  5196. return;
  5197. }
  5198. this._isReady = true;
  5199. if (this.onReady) {
  5200. this.onReady(this);
  5201. }
  5202. };
  5203. return Node;
  5204. })();
  5205. BABYLON.Node = Node;
  5206. })(BABYLON || (BABYLON = {}));
  5207. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5208. (function (BABYLON) {
  5209. var BoundingSphere = (function () {
  5210. function BoundingSphere(minimum, maximum) {
  5211. this.minimum = minimum;
  5212. this.maximum = maximum;
  5213. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5214. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5215. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5216. this.radius = distance * 0.5;
  5217. this.centerWorld = BABYLON.Vector3.Zero();
  5218. this._update(BABYLON.Matrix.Identity());
  5219. }
  5220. // Methods
  5221. BoundingSphere.prototype._update = function (world) {
  5222. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5223. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5224. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5225. };
  5226. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5227. for (var i = 0; i < 6; i++) {
  5228. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5229. return false;
  5230. }
  5231. return true;
  5232. };
  5233. BoundingSphere.prototype.intersectsPoint = function (point) {
  5234. var x = this.centerWorld.x - point.x;
  5235. var y = this.centerWorld.y - point.y;
  5236. var z = this.centerWorld.z - point.z;
  5237. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5238. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5239. return false;
  5240. return true;
  5241. };
  5242. // Statics
  5243. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5244. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5245. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5246. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5247. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5248. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5249. return false;
  5250. return true;
  5251. };
  5252. return BoundingSphere;
  5253. })();
  5254. BABYLON.BoundingSphere = BoundingSphere;
  5255. })(BABYLON || (BABYLON = {}));
  5256. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5257. (function (BABYLON) {
  5258. var BoundingBox = (function () {
  5259. function BoundingBox(minimum, maximum) {
  5260. this.minimum = minimum;
  5261. this.maximum = maximum;
  5262. this.vectors = new Array();
  5263. this.vectorsWorld = new Array();
  5264. // Bounding vectors
  5265. this.vectors.push(this.minimum.clone());
  5266. this.vectors.push(this.maximum.clone());
  5267. this.vectors.push(this.minimum.clone());
  5268. this.vectors[2].x = this.maximum.x;
  5269. this.vectors.push(this.minimum.clone());
  5270. this.vectors[3].y = this.maximum.y;
  5271. this.vectors.push(this.minimum.clone());
  5272. this.vectors[4].z = this.maximum.z;
  5273. this.vectors.push(this.maximum.clone());
  5274. this.vectors[5].z = this.minimum.z;
  5275. this.vectors.push(this.maximum.clone());
  5276. this.vectors[6].x = this.minimum.x;
  5277. this.vectors.push(this.maximum.clone());
  5278. this.vectors[7].y = this.minimum.y;
  5279. // OBB
  5280. this.center = this.maximum.add(this.minimum).scale(0.5);
  5281. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5282. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5283. for (var index = 0; index < this.vectors.length; index++) {
  5284. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5285. }
  5286. this.minimumWorld = BABYLON.Vector3.Zero();
  5287. this.maximumWorld = BABYLON.Vector3.Zero();
  5288. this._update(BABYLON.Matrix.Identity());
  5289. }
  5290. // Methods
  5291. BoundingBox.prototype.getWorldMatrix = function () {
  5292. return this._worldMatrix;
  5293. };
  5294. BoundingBox.prototype._update = function (world) {
  5295. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5296. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5297. for (var index = 0; index < this.vectors.length; index++) {
  5298. var v = this.vectorsWorld[index];
  5299. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5300. if (v.x < this.minimumWorld.x)
  5301. this.minimumWorld.x = v.x;
  5302. if (v.y < this.minimumWorld.y)
  5303. this.minimumWorld.y = v.y;
  5304. if (v.z < this.minimumWorld.z)
  5305. this.minimumWorld.z = v.z;
  5306. if (v.x > this.maximumWorld.x)
  5307. this.maximumWorld.x = v.x;
  5308. if (v.y > this.maximumWorld.y)
  5309. this.maximumWorld.y = v.y;
  5310. if (v.z > this.maximumWorld.z)
  5311. this.maximumWorld.z = v.z;
  5312. }
  5313. // OBB
  5314. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5315. this.center.scaleInPlace(0.5);
  5316. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5317. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5318. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5319. this._worldMatrix = world;
  5320. };
  5321. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5322. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5323. };
  5324. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5325. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5326. };
  5327. BoundingBox.prototype.intersectsPoint = function (point) {
  5328. var delta = BABYLON.Engine.Epsilon;
  5329. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5330. return false;
  5331. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5332. return false;
  5333. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5334. return false;
  5335. return true;
  5336. };
  5337. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5338. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5339. };
  5340. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5341. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5342. return false;
  5343. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5344. return false;
  5345. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5346. return false;
  5347. return true;
  5348. };
  5349. // Statics
  5350. BoundingBox.Intersects = function (box0, box1) {
  5351. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5352. return false;
  5353. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5354. return false;
  5355. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5356. return false;
  5357. return true;
  5358. };
  5359. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5360. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5361. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5362. return (num <= (sphereRadius * sphereRadius));
  5363. };
  5364. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5365. for (var p = 0; p < 6; p++) {
  5366. for (var i = 0; i < 8; i++) {
  5367. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5368. return false;
  5369. }
  5370. }
  5371. }
  5372. return true;
  5373. };
  5374. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5375. for (var p = 0; p < 6; p++) {
  5376. var inCount = 8;
  5377. for (var i = 0; i < 8; i++) {
  5378. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5379. --inCount;
  5380. }
  5381. else {
  5382. break;
  5383. }
  5384. }
  5385. if (inCount === 0)
  5386. return false;
  5387. }
  5388. return true;
  5389. };
  5390. return BoundingBox;
  5391. })();
  5392. BABYLON.BoundingBox = BoundingBox;
  5393. })(BABYLON || (BABYLON = {}));
  5394. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5395. (function (BABYLON) {
  5396. var computeBoxExtents = function (axis, box) {
  5397. var p = BABYLON.Vector3.Dot(box.center, axis);
  5398. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5399. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5400. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5401. var r = r0 + r1 + r2;
  5402. return {
  5403. min: p - r,
  5404. max: p + r
  5405. };
  5406. };
  5407. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5408. var axisOverlap = function (axis, box0, box1) {
  5409. var result0 = computeBoxExtents(axis, box0);
  5410. var result1 = computeBoxExtents(axis, box1);
  5411. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5412. };
  5413. var BoundingInfo = (function () {
  5414. function BoundingInfo(minimum, maximum) {
  5415. this.minimum = minimum;
  5416. this.maximum = maximum;
  5417. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5418. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5419. }
  5420. // Methods
  5421. BoundingInfo.prototype._update = function (world) {
  5422. this.boundingBox._update(world);
  5423. this.boundingSphere._update(world);
  5424. };
  5425. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5426. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5427. return false;
  5428. return this.boundingBox.isInFrustum(frustumPlanes);
  5429. };
  5430. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5431. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5432. };
  5433. BoundingInfo.prototype._checkCollision = function (collider) {
  5434. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5435. };
  5436. BoundingInfo.prototype.intersectsPoint = function (point) {
  5437. if (!this.boundingSphere.centerWorld) {
  5438. return false;
  5439. }
  5440. if (!this.boundingSphere.intersectsPoint(point)) {
  5441. return false;
  5442. }
  5443. if (!this.boundingBox.intersectsPoint(point)) {
  5444. return false;
  5445. }
  5446. return true;
  5447. };
  5448. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5449. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5450. return false;
  5451. }
  5452. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5453. return false;
  5454. }
  5455. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5456. return false;
  5457. }
  5458. if (!precise) {
  5459. return true;
  5460. }
  5461. var box0 = this.boundingBox;
  5462. var box1 = boundingInfo.boundingBox;
  5463. if (!axisOverlap(box0.directions[0], box0, box1))
  5464. return false;
  5465. if (!axisOverlap(box0.directions[1], box0, box1))
  5466. return false;
  5467. if (!axisOverlap(box0.directions[2], box0, box1))
  5468. return false;
  5469. if (!axisOverlap(box1.directions[0], box0, box1))
  5470. return false;
  5471. if (!axisOverlap(box1.directions[1], box0, box1))
  5472. return false;
  5473. if (!axisOverlap(box1.directions[2], box0, box1))
  5474. return false;
  5475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5476. return false;
  5477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5478. return false;
  5479. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5480. return false;
  5481. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5482. return false;
  5483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5484. return false;
  5485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5486. return false;
  5487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5488. return false;
  5489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5490. return false;
  5491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5492. return false;
  5493. return true;
  5494. };
  5495. return BoundingInfo;
  5496. })();
  5497. BABYLON.BoundingInfo = BoundingInfo;
  5498. })(BABYLON || (BABYLON = {}));
  5499. //# sourceMappingURL=babylon.boundingInfo.js.map
  5500. var BABYLON;
  5501. (function (BABYLON) {
  5502. var Light = (function (_super) {
  5503. __extends(Light, _super);
  5504. function Light(name, scene) {
  5505. _super.call(this, name, scene);
  5506. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5507. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5508. this.intensity = 1.0;
  5509. this.range = Number.MAX_VALUE;
  5510. this.includedOnlyMeshes = new Array();
  5511. this.excludedMeshes = new Array();
  5512. this._excludedMeshesIds = new Array();
  5513. this._includedOnlyMeshesIds = new Array();
  5514. scene.lights.push(this);
  5515. }
  5516. Light.prototype.getShadowGenerator = function () {
  5517. return this._shadowGenerator;
  5518. };
  5519. Light.prototype.getAbsolutePosition = function () {
  5520. return BABYLON.Vector3.Zero();
  5521. };
  5522. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5523. };
  5524. Light.prototype._getWorldMatrix = function () {
  5525. return BABYLON.Matrix.Identity();
  5526. };
  5527. Light.prototype.canAffectMesh = function (mesh) {
  5528. if (!mesh) {
  5529. return true;
  5530. }
  5531. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5532. return false;
  5533. }
  5534. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5535. return false;
  5536. }
  5537. return true;
  5538. };
  5539. Light.prototype.getWorldMatrix = function () {
  5540. this._currentRenderId = this.getScene().getRenderId();
  5541. var worldMatrix = this._getWorldMatrix();
  5542. if (this.parent && this.parent.getWorldMatrix) {
  5543. if (!this._parentedWorldMatrix) {
  5544. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5545. }
  5546. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5547. return this._parentedWorldMatrix;
  5548. }
  5549. return worldMatrix;
  5550. };
  5551. Light.prototype.dispose = function () {
  5552. if (this._shadowGenerator) {
  5553. this._shadowGenerator.dispose();
  5554. this._shadowGenerator = null;
  5555. }
  5556. // Remove from scene
  5557. var index = this.getScene().lights.indexOf(this);
  5558. this.getScene().lights.splice(index, 1);
  5559. };
  5560. return Light;
  5561. })(BABYLON.Node);
  5562. BABYLON.Light = Light;
  5563. })(BABYLON || (BABYLON = {}));
  5564. //# sourceMappingURL=babylon.light.js.map
  5565. var BABYLON;
  5566. (function (BABYLON) {
  5567. var PointLight = (function (_super) {
  5568. __extends(PointLight, _super);
  5569. function PointLight(name, position, scene) {
  5570. _super.call(this, name, scene);
  5571. this.position = position;
  5572. }
  5573. PointLight.prototype.getAbsolutePosition = function () {
  5574. return this._transformedPosition ? this._transformedPosition : this.position;
  5575. };
  5576. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5577. if (this.parent && this.parent.getWorldMatrix) {
  5578. if (!this._transformedPosition) {
  5579. this._transformedPosition = BABYLON.Vector3.Zero();
  5580. }
  5581. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5582. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5583. return;
  5584. }
  5585. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5586. };
  5587. PointLight.prototype.getShadowGenerator = function () {
  5588. return null;
  5589. };
  5590. PointLight.prototype._getWorldMatrix = function () {
  5591. if (!this._worldMatrix) {
  5592. this._worldMatrix = BABYLON.Matrix.Identity();
  5593. }
  5594. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5595. return this._worldMatrix;
  5596. };
  5597. return PointLight;
  5598. })(BABYLON.Light);
  5599. BABYLON.PointLight = PointLight;
  5600. })(BABYLON || (BABYLON = {}));
  5601. //# sourceMappingURL=babylon.pointLight.js.map
  5602. var BABYLON;
  5603. (function (BABYLON) {
  5604. var SpotLight = (function (_super) {
  5605. __extends(SpotLight, _super);
  5606. function SpotLight(name, position, direction, angle, exponent, scene) {
  5607. _super.call(this, name, scene);
  5608. this.position = position;
  5609. this.direction = direction;
  5610. this.angle = angle;
  5611. this.exponent = exponent;
  5612. }
  5613. SpotLight.prototype.getAbsolutePosition = function () {
  5614. return this.transformedPosition ? this.transformedPosition : this.position;
  5615. };
  5616. SpotLight.prototype.setDirectionToTarget = function (target) {
  5617. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5618. return this.direction;
  5619. };
  5620. SpotLight.prototype.computeTransformedPosition = function () {
  5621. if (this.parent && this.parent.getWorldMatrix) {
  5622. if (!this.transformedPosition) {
  5623. this.transformedPosition = BABYLON.Vector3.Zero();
  5624. }
  5625. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5626. return true;
  5627. }
  5628. return false;
  5629. };
  5630. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5631. var normalizeDirection;
  5632. if (this.parent && this.parent.getWorldMatrix) {
  5633. if (!this._transformedDirection) {
  5634. this._transformedDirection = BABYLON.Vector3.Zero();
  5635. }
  5636. this.computeTransformedPosition();
  5637. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5638. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5639. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5640. }
  5641. else {
  5642. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5643. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5644. }
  5645. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5646. };
  5647. SpotLight.prototype._getWorldMatrix = function () {
  5648. if (!this._worldMatrix) {
  5649. this._worldMatrix = BABYLON.Matrix.Identity();
  5650. }
  5651. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5652. return this._worldMatrix;
  5653. };
  5654. return SpotLight;
  5655. })(BABYLON.Light);
  5656. BABYLON.SpotLight = SpotLight;
  5657. })(BABYLON || (BABYLON = {}));
  5658. //# sourceMappingURL=babylon.spotLight.js.map
  5659. var BABYLON;
  5660. (function (BABYLON) {
  5661. var DirectionalLight = (function (_super) {
  5662. __extends(DirectionalLight, _super);
  5663. function DirectionalLight(name, direction, scene) {
  5664. _super.call(this, name, scene);
  5665. this.direction = direction;
  5666. this.position = direction.scale(-1);
  5667. }
  5668. DirectionalLight.prototype.getAbsolutePosition = function () {
  5669. return this.transformedPosition ? this.transformedPosition : this.position;
  5670. };
  5671. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5672. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5673. return this.direction;
  5674. };
  5675. DirectionalLight.prototype.computeTransformedPosition = function () {
  5676. if (this.parent && this.parent.getWorldMatrix) {
  5677. if (!this.transformedPosition) {
  5678. this.transformedPosition = BABYLON.Vector3.Zero();
  5679. }
  5680. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5681. return true;
  5682. }
  5683. return false;
  5684. };
  5685. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5686. if (this.parent && this.parent.getWorldMatrix) {
  5687. if (!this._transformedDirection) {
  5688. this._transformedDirection = BABYLON.Vector3.Zero();
  5689. }
  5690. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5691. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5692. return;
  5693. }
  5694. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5695. };
  5696. DirectionalLight.prototype._getWorldMatrix = function () {
  5697. if (!this._worldMatrix) {
  5698. this._worldMatrix = BABYLON.Matrix.Identity();
  5699. }
  5700. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5701. return this._worldMatrix;
  5702. };
  5703. return DirectionalLight;
  5704. })(BABYLON.Light);
  5705. BABYLON.DirectionalLight = DirectionalLight;
  5706. })(BABYLON || (BABYLON = {}));
  5707. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5708. (function (BABYLON) {
  5709. var ShadowGenerator = (function () {
  5710. function ShadowGenerator(mapSize, light) {
  5711. var _this = this;
  5712. // Members
  5713. this.filter = ShadowGenerator.FILTER_NONE;
  5714. this._darkness = 0;
  5715. this._transparencyShadow = false;
  5716. this._viewMatrix = BABYLON.Matrix.Zero();
  5717. this._projectionMatrix = BABYLON.Matrix.Zero();
  5718. this._transformMatrix = BABYLON.Matrix.Zero();
  5719. this._worldViewProjection = BABYLON.Matrix.Zero();
  5720. this._light = light;
  5721. this._scene = light.getScene();
  5722. light._shadowGenerator = this;
  5723. // Render target
  5724. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5725. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5726. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5727. this._shadowMap.renderParticles = false;
  5728. // Custom render function
  5729. var renderSubMesh = function (subMesh) {
  5730. var mesh = subMesh.getRenderingMesh();
  5731. var scene = _this._scene;
  5732. var engine = scene.getEngine();
  5733. // Culling
  5734. engine.setState(subMesh.getMaterial().backFaceCulling);
  5735. // Managing instances
  5736. var batch = mesh._getInstancesRenderList(subMesh._id);
  5737. if (batch.mustReturn) {
  5738. return;
  5739. }
  5740. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5741. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5742. engine.enableEffect(_this._effect);
  5743. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5744. var material = subMesh.getMaterial();
  5745. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5746. // Alpha test
  5747. if (material && material.needAlphaTesting()) {
  5748. var alphaTexture = material.getAlphaTestTexture();
  5749. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5750. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5751. }
  5752. // Bones
  5753. if (mesh.useBones) {
  5754. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5755. }
  5756. // Draw
  5757. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5758. }
  5759. else {
  5760. // Need to reset refresh rate of the shadowMap
  5761. _this._shadowMap.resetRefreshCounter();
  5762. }
  5763. };
  5764. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5765. var index;
  5766. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5767. renderSubMesh(opaqueSubMeshes.data[index]);
  5768. }
  5769. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5770. renderSubMesh(alphaTestSubMeshes.data[index]);
  5771. }
  5772. if (_this._transparencyShadow) {
  5773. for (index = 0; index < transparentSubMeshes.length; index++) {
  5774. renderSubMesh(transparentSubMeshes.data[index]);
  5775. }
  5776. }
  5777. };
  5778. }
  5779. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5780. // Static
  5781. get: function () {
  5782. return ShadowGenerator._FILTER_NONE;
  5783. },
  5784. enumerable: true,
  5785. configurable: true
  5786. });
  5787. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5788. get: function () {
  5789. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5790. },
  5791. enumerable: true,
  5792. configurable: true
  5793. });
  5794. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5795. get: function () {
  5796. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5797. },
  5798. enumerable: true,
  5799. configurable: true
  5800. });
  5801. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5802. get: function () {
  5803. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5804. },
  5805. set: function (value) {
  5806. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5807. },
  5808. enumerable: true,
  5809. configurable: true
  5810. });
  5811. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5812. get: function () {
  5813. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5814. },
  5815. set: function (value) {
  5816. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5817. },
  5818. enumerable: true,
  5819. configurable: true
  5820. });
  5821. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5822. var defines = [];
  5823. if (this.useVarianceShadowMap) {
  5824. defines.push("#define VSM");
  5825. }
  5826. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5827. var mesh = subMesh.getMesh();
  5828. var material = subMesh.getMaterial();
  5829. // Alpha test
  5830. if (material && material.needAlphaTesting()) {
  5831. defines.push("#define ALPHATEST");
  5832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5833. attribs.push(BABYLON.VertexBuffer.UVKind);
  5834. defines.push("#define UV1");
  5835. }
  5836. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5837. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5838. defines.push("#define UV2");
  5839. }
  5840. }
  5841. // Bones
  5842. if (mesh.useBones) {
  5843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5845. defines.push("#define BONES");
  5846. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5847. }
  5848. // Instances
  5849. if (useInstances) {
  5850. defines.push("#define INSTANCES");
  5851. attribs.push("world0");
  5852. attribs.push("world1");
  5853. attribs.push("world2");
  5854. attribs.push("world3");
  5855. }
  5856. // Get correct effect
  5857. var join = defines.join("\n");
  5858. if (this._cachedDefines !== join) {
  5859. this._cachedDefines = join;
  5860. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5861. }
  5862. return this._effect.isReady();
  5863. };
  5864. ShadowGenerator.prototype.getShadowMap = function () {
  5865. return this._shadowMap;
  5866. };
  5867. ShadowGenerator.prototype.getLight = function () {
  5868. return this._light;
  5869. };
  5870. // Methods
  5871. ShadowGenerator.prototype.getTransformMatrix = function () {
  5872. var lightPosition = this._light.position;
  5873. var lightDirection = this._light.direction;
  5874. if (this._light.computeTransformedPosition()) {
  5875. lightPosition = this._light.transformedPosition;
  5876. }
  5877. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5878. this._cachedPosition = lightPosition.clone();
  5879. this._cachedDirection = lightDirection.clone();
  5880. var activeCamera = this._scene.activeCamera;
  5881. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5882. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5883. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5884. }
  5885. return this._transformMatrix;
  5886. };
  5887. ShadowGenerator.prototype.getDarkness = function () {
  5888. return this._darkness;
  5889. };
  5890. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5891. if (darkness >= 1.0)
  5892. this._darkness = 1.0;
  5893. else if (darkness <= 0.0)
  5894. this._darkness = 0.0;
  5895. else
  5896. this._darkness = darkness;
  5897. };
  5898. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5899. this._transparencyShadow = hasShadow;
  5900. };
  5901. ShadowGenerator.prototype.dispose = function () {
  5902. this._shadowMap.dispose();
  5903. };
  5904. ShadowGenerator._FILTER_NONE = 0;
  5905. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5906. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5907. return ShadowGenerator;
  5908. })();
  5909. BABYLON.ShadowGenerator = ShadowGenerator;
  5910. })(BABYLON || (BABYLON = {}));
  5911. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5912. var BABYLON;
  5913. (function (BABYLON) {
  5914. var HemisphericLight = (function (_super) {
  5915. __extends(HemisphericLight, _super);
  5916. function HemisphericLight(name, direction, scene) {
  5917. _super.call(this, name, scene);
  5918. this.direction = direction;
  5919. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5920. }
  5921. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5922. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5923. return this.direction;
  5924. };
  5925. HemisphericLight.prototype.getShadowGenerator = function () {
  5926. return null;
  5927. };
  5928. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5929. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5930. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5931. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5932. };
  5933. HemisphericLight.prototype._getWorldMatrix = function () {
  5934. if (!this._worldMatrix) {
  5935. this._worldMatrix = BABYLON.Matrix.Identity();
  5936. }
  5937. return this._worldMatrix;
  5938. };
  5939. return HemisphericLight;
  5940. })(BABYLON.Light);
  5941. BABYLON.HemisphericLight = HemisphericLight;
  5942. })(BABYLON || (BABYLON = {}));
  5943. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5944. (function (BABYLON) {
  5945. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5946. if (boxMin.x > sphereCenter.x + sphereRadius)
  5947. return false;
  5948. if (sphereCenter.x - sphereRadius > boxMax.x)
  5949. return false;
  5950. if (boxMin.y > sphereCenter.y + sphereRadius)
  5951. return false;
  5952. if (sphereCenter.y - sphereRadius > boxMax.y)
  5953. return false;
  5954. if (boxMin.z > sphereCenter.z + sphereRadius)
  5955. return false;
  5956. if (sphereCenter.z - sphereRadius > boxMax.z)
  5957. return false;
  5958. return true;
  5959. };
  5960. var getLowestRoot = function (a, b, c, maxR) {
  5961. var determinant = b * b - 4.0 * a * c;
  5962. var result = { root: 0, found: false };
  5963. if (determinant < 0)
  5964. return result;
  5965. var sqrtD = Math.sqrt(determinant);
  5966. var r1 = (-b - sqrtD) / (2.0 * a);
  5967. var r2 = (-b + sqrtD) / (2.0 * a);
  5968. if (r1 > r2) {
  5969. var temp = r2;
  5970. r2 = r1;
  5971. r1 = temp;
  5972. }
  5973. if (r1 > 0 && r1 < maxR) {
  5974. result.root = r1;
  5975. result.found = true;
  5976. return result;
  5977. }
  5978. if (r2 > 0 && r2 < maxR) {
  5979. result.root = r2;
  5980. result.found = true;
  5981. return result;
  5982. }
  5983. return result;
  5984. };
  5985. var Collider = (function () {
  5986. function Collider() {
  5987. this.radius = new BABYLON.Vector3(1, 1, 1);
  5988. this.retry = 0;
  5989. this.basePointWorld = BABYLON.Vector3.Zero();
  5990. this.velocityWorld = BABYLON.Vector3.Zero();
  5991. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5992. this._collisionPoint = BABYLON.Vector3.Zero();
  5993. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5994. this._tempVector = BABYLON.Vector3.Zero();
  5995. this._tempVector2 = BABYLON.Vector3.Zero();
  5996. this._tempVector3 = BABYLON.Vector3.Zero();
  5997. this._tempVector4 = BABYLON.Vector3.Zero();
  5998. this._edge = BABYLON.Vector3.Zero();
  5999. this._baseToVertex = BABYLON.Vector3.Zero();
  6000. this._destinationPoint = BABYLON.Vector3.Zero();
  6001. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6002. this._displacementVector = BABYLON.Vector3.Zero();
  6003. }
  6004. // Methods
  6005. Collider.prototype._initialize = function (source, dir, e) {
  6006. this.velocity = dir;
  6007. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6008. this.basePoint = source;
  6009. source.multiplyToRef(this.radius, this.basePointWorld);
  6010. dir.multiplyToRef(this.radius, this.velocityWorld);
  6011. this.velocityWorldLength = this.velocityWorld.length();
  6012. this.epsilon = e;
  6013. this.collisionFound = false;
  6014. };
  6015. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6016. pa.subtractToRef(point, this._tempVector);
  6017. pb.subtractToRef(point, this._tempVector2);
  6018. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6019. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6020. if (d < 0)
  6021. return false;
  6022. pc.subtractToRef(point, this._tempVector3);
  6023. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6024. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6025. if (d < 0)
  6026. return false;
  6027. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6028. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6029. return d >= 0;
  6030. };
  6031. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6032. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6033. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6034. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6035. return false;
  6036. }
  6037. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6038. return false;
  6039. return true;
  6040. };
  6041. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6042. var t0;
  6043. var embeddedInPlane = false;
  6044. if (!subMesh._trianglePlanes) {
  6045. subMesh._trianglePlanes = [];
  6046. }
  6047. if (!subMesh._trianglePlanes[faceIndex]) {
  6048. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6049. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6050. }
  6051. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6052. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6053. return;
  6054. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6055. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6056. if (normalDotVelocity == 0) {
  6057. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6058. return;
  6059. embeddedInPlane = true;
  6060. t0 = 0;
  6061. }
  6062. else {
  6063. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6064. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6065. if (t0 > t1) {
  6066. var temp = t1;
  6067. t1 = t0;
  6068. t0 = temp;
  6069. }
  6070. if (t0 > 1.0 || t1 < 0.0)
  6071. return;
  6072. if (t0 < 0)
  6073. t0 = 0;
  6074. if (t0 > 1.0)
  6075. t0 = 1.0;
  6076. }
  6077. this._collisionPoint.copyFromFloats(0, 0, 0);
  6078. var found = false;
  6079. var t = 1.0;
  6080. if (!embeddedInPlane) {
  6081. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6082. this.velocity.scaleToRef(t0, this._tempVector);
  6083. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6084. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6085. found = true;
  6086. t = t0;
  6087. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6088. }
  6089. }
  6090. if (!found) {
  6091. var velocitySquaredLength = this.velocity.lengthSquared();
  6092. var a = velocitySquaredLength;
  6093. this.basePoint.subtractToRef(p1, this._tempVector);
  6094. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6095. var c = this._tempVector.lengthSquared() - 1.0;
  6096. var lowestRoot = getLowestRoot(a, b, c, t);
  6097. if (lowestRoot.found) {
  6098. t = lowestRoot.root;
  6099. found = true;
  6100. this._collisionPoint.copyFrom(p1);
  6101. }
  6102. this.basePoint.subtractToRef(p2, this._tempVector);
  6103. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6104. c = this._tempVector.lengthSquared() - 1.0;
  6105. lowestRoot = getLowestRoot(a, b, c, t);
  6106. if (lowestRoot.found) {
  6107. t = lowestRoot.root;
  6108. found = true;
  6109. this._collisionPoint.copyFrom(p2);
  6110. }
  6111. this.basePoint.subtractToRef(p3, this._tempVector);
  6112. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6113. c = this._tempVector.lengthSquared() - 1.0;
  6114. lowestRoot = getLowestRoot(a, b, c, t);
  6115. if (lowestRoot.found) {
  6116. t = lowestRoot.root;
  6117. found = true;
  6118. this._collisionPoint.copyFrom(p3);
  6119. }
  6120. p2.subtractToRef(p1, this._edge);
  6121. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6122. var edgeSquaredLength = this._edge.lengthSquared();
  6123. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6124. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6125. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6126. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6127. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6128. lowestRoot = getLowestRoot(a, b, c, t);
  6129. if (lowestRoot.found) {
  6130. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6131. if (f >= 0.0 && f <= 1.0) {
  6132. t = lowestRoot.root;
  6133. found = true;
  6134. this._edge.scaleInPlace(f);
  6135. p1.addToRef(this._edge, this._collisionPoint);
  6136. }
  6137. }
  6138. p3.subtractToRef(p2, this._edge);
  6139. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6140. edgeSquaredLength = this._edge.lengthSquared();
  6141. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6142. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6143. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6144. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6145. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6146. lowestRoot = getLowestRoot(a, b, c, t);
  6147. if (lowestRoot.found) {
  6148. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6149. if (f >= 0.0 && f <= 1.0) {
  6150. t = lowestRoot.root;
  6151. found = true;
  6152. this._edge.scaleInPlace(f);
  6153. p2.addToRef(this._edge, this._collisionPoint);
  6154. }
  6155. }
  6156. p1.subtractToRef(p3, this._edge);
  6157. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6158. edgeSquaredLength = this._edge.lengthSquared();
  6159. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6160. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6161. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6162. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6163. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6164. lowestRoot = getLowestRoot(a, b, c, t);
  6165. if (lowestRoot.found) {
  6166. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6167. if (f >= 0.0 && f <= 1.0) {
  6168. t = lowestRoot.root;
  6169. found = true;
  6170. this._edge.scaleInPlace(f);
  6171. p3.addToRef(this._edge, this._collisionPoint);
  6172. }
  6173. }
  6174. }
  6175. if (found) {
  6176. var distToCollision = t * this.velocity.length();
  6177. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6178. if (!this.intersectionPoint) {
  6179. this.intersectionPoint = this._collisionPoint.clone();
  6180. }
  6181. else {
  6182. this.intersectionPoint.copyFrom(this._collisionPoint);
  6183. }
  6184. this.nearestDistance = distToCollision;
  6185. this.collisionFound = true;
  6186. this.collidedMesh = subMesh.getMesh();
  6187. }
  6188. }
  6189. };
  6190. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6191. for (var i = indexStart; i < indexEnd; i += 3) {
  6192. var p1 = pts[indices[i] - decal];
  6193. var p2 = pts[indices[i + 1] - decal];
  6194. var p3 = pts[indices[i + 2] - decal];
  6195. this._testTriangle(i, subMesh, p3, p2, p1);
  6196. }
  6197. };
  6198. Collider.prototype._getResponse = function (pos, vel) {
  6199. pos.addToRef(vel, this._destinationPoint);
  6200. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6201. this.basePoint.addToRef(vel, pos);
  6202. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6203. this._slidePlaneNormal.normalize();
  6204. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6205. pos.addInPlace(this._displacementVector);
  6206. this.intersectionPoint.addInPlace(this._displacementVector);
  6207. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6208. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6209. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6210. };
  6211. return Collider;
  6212. })();
  6213. BABYLON.Collider = Collider;
  6214. })(BABYLON || (BABYLON = {}));
  6215. //# sourceMappingURL=babylon.collider.js.map
  6216. var BABYLON;
  6217. (function (BABYLON) {
  6218. var Camera = (function (_super) {
  6219. __extends(Camera, _super);
  6220. function Camera(name, position, scene) {
  6221. _super.call(this, name, scene);
  6222. this.position = position;
  6223. // Members
  6224. this.upVector = BABYLON.Vector3.Up();
  6225. this.orthoLeft = null;
  6226. this.orthoRight = null;
  6227. this.orthoBottom = null;
  6228. this.orthoTop = null;
  6229. this.fov = 0.8;
  6230. this.minZ = 1.0;
  6231. this.maxZ = 10000.0;
  6232. this.inertia = 0.9;
  6233. this.mode = Camera.PERSPECTIVE_CAMERA;
  6234. this.isIntermediate = false;
  6235. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6236. this.subCameras = [];
  6237. this.layerMask = 0xFFFFFFFF;
  6238. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6239. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6240. this._projectionMatrix = new BABYLON.Matrix();
  6241. this._postProcesses = new Array();
  6242. this._postProcessesTakenIndices = [];
  6243. scene.cameras.push(this);
  6244. if (!scene.activeCamera) {
  6245. scene.activeCamera = this;
  6246. }
  6247. }
  6248. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6249. get: function () {
  6250. return Camera._PERSPECTIVE_CAMERA;
  6251. },
  6252. enumerable: true,
  6253. configurable: true
  6254. });
  6255. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6256. get: function () {
  6257. return Camera._ORTHOGRAPHIC_CAMERA;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6263. get: function () {
  6264. return Camera._FOVMODE_VERTICAL_FIXED;
  6265. },
  6266. enumerable: true,
  6267. configurable: true
  6268. });
  6269. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6270. get: function () {
  6271. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6272. },
  6273. enumerable: true,
  6274. configurable: true
  6275. });
  6276. //Cache
  6277. Camera.prototype._initCache = function () {
  6278. _super.prototype._initCache.call(this);
  6279. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6280. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6281. this._cache.mode = undefined;
  6282. this._cache.minZ = undefined;
  6283. this._cache.maxZ = undefined;
  6284. this._cache.fov = undefined;
  6285. this._cache.aspectRatio = undefined;
  6286. this._cache.orthoLeft = undefined;
  6287. this._cache.orthoRight = undefined;
  6288. this._cache.orthoBottom = undefined;
  6289. this._cache.orthoTop = undefined;
  6290. this._cache.renderWidth = undefined;
  6291. this._cache.renderHeight = undefined;
  6292. };
  6293. Camera.prototype._updateCache = function (ignoreParentClass) {
  6294. if (!ignoreParentClass) {
  6295. _super.prototype._updateCache.call(this);
  6296. }
  6297. var engine = this.getEngine();
  6298. this._cache.position.copyFrom(this.position);
  6299. this._cache.upVector.copyFrom(this.upVector);
  6300. this._cache.mode = this.mode;
  6301. this._cache.minZ = this.minZ;
  6302. this._cache.maxZ = this.maxZ;
  6303. this._cache.fov = this.fov;
  6304. this._cache.aspectRatio = engine.getAspectRatio(this);
  6305. this._cache.orthoLeft = this.orthoLeft;
  6306. this._cache.orthoRight = this.orthoRight;
  6307. this._cache.orthoBottom = this.orthoBottom;
  6308. this._cache.orthoTop = this.orthoTop;
  6309. this._cache.renderWidth = engine.getRenderWidth();
  6310. this._cache.renderHeight = engine.getRenderHeight();
  6311. };
  6312. Camera.prototype._updateFromScene = function () {
  6313. this.updateCache();
  6314. this._update();
  6315. };
  6316. // Synchronized
  6317. Camera.prototype._isSynchronized = function () {
  6318. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6319. };
  6320. Camera.prototype._isSynchronizedViewMatrix = function () {
  6321. if (!_super.prototype._isSynchronized.call(this))
  6322. return false;
  6323. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6324. };
  6325. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6326. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6327. if (!check) {
  6328. return false;
  6329. }
  6330. var engine = this.getEngine();
  6331. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6332. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6333. }
  6334. else {
  6335. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  6336. }
  6337. return check;
  6338. };
  6339. // Controls
  6340. Camera.prototype.attachControl = function (element) {
  6341. };
  6342. Camera.prototype.detachControl = function (element) {
  6343. };
  6344. Camera.prototype._update = function () {
  6345. };
  6346. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6347. if (insertAt === void 0) { insertAt = null; }
  6348. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6349. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6350. return 0;
  6351. }
  6352. if (insertAt == null || insertAt < 0) {
  6353. this._postProcesses.push(postProcess);
  6354. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6355. return this._postProcesses.length - 1;
  6356. }
  6357. var add = 0;
  6358. if (this._postProcesses[insertAt]) {
  6359. var start = this._postProcesses.length - 1;
  6360. for (var i = start; i >= insertAt + 1; --i) {
  6361. this._postProcesses[i + 1] = this._postProcesses[i];
  6362. }
  6363. add = 1;
  6364. }
  6365. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6366. if (this._postProcessesTakenIndices[i] < insertAt) {
  6367. continue;
  6368. }
  6369. start = this._postProcessesTakenIndices.length - 1;
  6370. for (var j = start; j >= i; --j) {
  6371. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6372. }
  6373. this._postProcessesTakenIndices[i] = insertAt;
  6374. break;
  6375. }
  6376. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6377. this._postProcessesTakenIndices.push(insertAt);
  6378. }
  6379. var result = insertAt + add;
  6380. this._postProcesses[result] = postProcess;
  6381. return result;
  6382. };
  6383. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6384. if (atIndices === void 0) { atIndices = null; }
  6385. var result = [];
  6386. if (!atIndices) {
  6387. var length = this._postProcesses.length;
  6388. for (var i = 0; i < length; i++) {
  6389. if (this._postProcesses[i] !== postProcess) {
  6390. continue;
  6391. }
  6392. delete this._postProcesses[i];
  6393. var index = this._postProcessesTakenIndices.indexOf(i);
  6394. this._postProcessesTakenIndices.splice(index, 1);
  6395. }
  6396. }
  6397. else {
  6398. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6399. for (i = 0; i < atIndices.length; i++) {
  6400. var foundPostProcess = this._postProcesses[atIndices[i]];
  6401. if (foundPostProcess !== postProcess) {
  6402. result.push(i);
  6403. continue;
  6404. }
  6405. delete this._postProcesses[atIndices[i]];
  6406. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6407. this._postProcessesTakenIndices.splice(index, 1);
  6408. }
  6409. }
  6410. return result;
  6411. };
  6412. Camera.prototype.getWorldMatrix = function () {
  6413. if (!this._worldMatrix) {
  6414. this._worldMatrix = BABYLON.Matrix.Identity();
  6415. }
  6416. var viewMatrix = this.getViewMatrix();
  6417. viewMatrix.invertToRef(this._worldMatrix);
  6418. return this._worldMatrix;
  6419. };
  6420. Camera.prototype._getViewMatrix = function () {
  6421. return BABYLON.Matrix.Identity();
  6422. };
  6423. Camera.prototype.getViewMatrix = function () {
  6424. this._computedViewMatrix = this._computeViewMatrix();
  6425. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6426. return this._computedViewMatrix;
  6427. }
  6428. if (!this._worldMatrix) {
  6429. this._worldMatrix = BABYLON.Matrix.Identity();
  6430. }
  6431. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6432. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6433. this._computedViewMatrix.invert();
  6434. this._currentRenderId = this.getScene().getRenderId();
  6435. return this._computedViewMatrix;
  6436. };
  6437. Camera.prototype._computeViewMatrix = function (force) {
  6438. if (!force && this._isSynchronizedViewMatrix()) {
  6439. return this._computedViewMatrix;
  6440. }
  6441. this._computedViewMatrix = this._getViewMatrix();
  6442. if (!this.parent || !this.parent.getWorldMatrix) {
  6443. this._currentRenderId = this.getScene().getRenderId();
  6444. }
  6445. return this._computedViewMatrix;
  6446. };
  6447. Camera.prototype.getProjectionMatrix = function (force) {
  6448. if (!force && this._isSynchronizedProjectionMatrix()) {
  6449. return this._projectionMatrix;
  6450. }
  6451. var engine = this.getEngine();
  6452. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6453. if (this.minZ <= 0) {
  6454. this.minZ = 0.1;
  6455. }
  6456. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6457. return this._projectionMatrix;
  6458. }
  6459. var halfWidth = engine.getRenderWidth() / 2.0;
  6460. var halfHeight = engine.getRenderHeight() / 2.0;
  6461. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6462. return this._projectionMatrix;
  6463. };
  6464. Camera.prototype.dispose = function () {
  6465. // Remove from scene
  6466. var index = this.getScene().cameras.indexOf(this);
  6467. this.getScene().cameras.splice(index, 1);
  6468. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6469. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6470. }
  6471. };
  6472. // Statics
  6473. Camera._PERSPECTIVE_CAMERA = 0;
  6474. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6475. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6476. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6477. return Camera;
  6478. })(BABYLON.Node);
  6479. BABYLON.Camera = Camera;
  6480. })(BABYLON || (BABYLON = {}));
  6481. //# sourceMappingURL=babylon.camera.js.map
  6482. var BABYLON;
  6483. (function (BABYLON) {
  6484. var TargetCamera = (function (_super) {
  6485. __extends(TargetCamera, _super);
  6486. function TargetCamera(name, position, scene) {
  6487. _super.call(this, name, position, scene);
  6488. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6489. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6490. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6491. this.speed = 2.0;
  6492. this.noRotationConstraint = false;
  6493. this.lockedTarget = null;
  6494. this._currentTarget = BABYLON.Vector3.Zero();
  6495. this._viewMatrix = BABYLON.Matrix.Zero();
  6496. this._camMatrix = BABYLON.Matrix.Zero();
  6497. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6498. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6499. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6500. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6501. this._lookAtTemp = BABYLON.Matrix.Zero();
  6502. this._tempMatrix = BABYLON.Matrix.Zero();
  6503. }
  6504. TargetCamera.prototype._getLockedTargetPosition = function () {
  6505. if (!this.lockedTarget) {
  6506. return null;
  6507. }
  6508. return this.lockedTarget.position || this.lockedTarget;
  6509. };
  6510. // Cache
  6511. TargetCamera.prototype._initCache = function () {
  6512. _super.prototype._initCache.call(this);
  6513. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6514. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6515. };
  6516. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6517. if (!ignoreParentClass) {
  6518. _super.prototype._updateCache.call(this);
  6519. }
  6520. var lockedTargetPosition = this._getLockedTargetPosition();
  6521. if (!lockedTargetPosition) {
  6522. this._cache.lockedTarget = null;
  6523. }
  6524. else {
  6525. if (!this._cache.lockedTarget) {
  6526. this._cache.lockedTarget = lockedTargetPosition.clone();
  6527. }
  6528. else {
  6529. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6530. }
  6531. }
  6532. this._cache.rotation.copyFrom(this.rotation);
  6533. };
  6534. // Synchronized
  6535. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6536. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6537. return false;
  6538. }
  6539. var lockedTargetPosition = this._getLockedTargetPosition();
  6540. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6541. };
  6542. // Methods
  6543. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6544. var engine = this.getEngine();
  6545. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6546. };
  6547. // Target
  6548. TargetCamera.prototype.setTarget = function (target) {
  6549. this.upVector.normalize();
  6550. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6551. this._camMatrix.invert();
  6552. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6553. var vDir = target.subtract(this.position);
  6554. if (vDir.x >= 0.0) {
  6555. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6556. }
  6557. else {
  6558. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6559. }
  6560. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6561. if (isNaN(this.rotation.x)) {
  6562. this.rotation.x = 0;
  6563. }
  6564. if (isNaN(this.rotation.y)) {
  6565. this.rotation.y = 0;
  6566. }
  6567. if (isNaN(this.rotation.z)) {
  6568. this.rotation.z = 0;
  6569. }
  6570. };
  6571. TargetCamera.prototype.getTarget = function () {
  6572. return this._currentTarget;
  6573. };
  6574. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6575. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6576. };
  6577. TargetCamera.prototype._updatePosition = function () {
  6578. this.position.addInPlace(this.cameraDirection);
  6579. };
  6580. TargetCamera.prototype._update = function () {
  6581. var needToMove = this._decideIfNeedsToMove();
  6582. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6583. // Move
  6584. if (needToMove) {
  6585. this._updatePosition();
  6586. }
  6587. // Rotate
  6588. if (needToRotate) {
  6589. this.rotation.x += this.cameraRotation.x;
  6590. this.rotation.y += this.cameraRotation.y;
  6591. if (!this.noRotationConstraint) {
  6592. var limit = (Math.PI / 2) * 0.95;
  6593. if (this.rotation.x > limit)
  6594. this.rotation.x = limit;
  6595. if (this.rotation.x < -limit)
  6596. this.rotation.x = -limit;
  6597. }
  6598. }
  6599. // Inertia
  6600. if (needToMove) {
  6601. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6602. this.cameraDirection.x = 0;
  6603. }
  6604. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6605. this.cameraDirection.y = 0;
  6606. }
  6607. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6608. this.cameraDirection.z = 0;
  6609. }
  6610. this.cameraDirection.scaleInPlace(this.inertia);
  6611. }
  6612. if (needToRotate) {
  6613. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6614. this.cameraRotation.x = 0;
  6615. }
  6616. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6617. this.cameraRotation.y = 0;
  6618. }
  6619. this.cameraRotation.scaleInPlace(this.inertia);
  6620. }
  6621. };
  6622. TargetCamera.prototype._getViewMatrix = function () {
  6623. if (!this.lockedTarget) {
  6624. // Compute
  6625. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6626. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6627. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6628. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6629. this._lookAtTemp.invert();
  6630. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6631. }
  6632. else {
  6633. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6634. }
  6635. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6636. // Computing target and final matrix
  6637. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6638. }
  6639. else {
  6640. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6641. }
  6642. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6643. return this._viewMatrix;
  6644. };
  6645. return TargetCamera;
  6646. })(BABYLON.Camera);
  6647. BABYLON.TargetCamera = TargetCamera;
  6648. })(BABYLON || (BABYLON = {}));
  6649. //# sourceMappingURL=babylon.targetCamera.js.map
  6650. var BABYLON;
  6651. (function (BABYLON) {
  6652. var FollowCamera = (function (_super) {
  6653. __extends(FollowCamera, _super);
  6654. function FollowCamera(name, position, scene) {
  6655. _super.call(this, name, position, scene);
  6656. this.radius = 12;
  6657. this.rotationOffset = 0;
  6658. this.heightOffset = 4;
  6659. this.cameraAcceleration = 0.05;
  6660. this.maxCameraSpeed = 20;
  6661. }
  6662. FollowCamera.prototype.getRadians = function (degrees) {
  6663. return degrees * Math.PI / 180;
  6664. };
  6665. FollowCamera.prototype.follow = function (cameraTarget) {
  6666. if (!cameraTarget)
  6667. return;
  6668. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6669. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6670. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6671. var dx = targetX - this.position.x;
  6672. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6673. var dz = (targetZ) - this.position.z;
  6674. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6675. var vy = dy * this.cameraAcceleration;
  6676. var vz = dz * this.cameraAcceleration * 2;
  6677. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6678. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6679. }
  6680. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6681. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6682. }
  6683. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6684. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6685. }
  6686. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6687. this.setTarget(cameraTarget.position);
  6688. };
  6689. FollowCamera.prototype._update = function () {
  6690. _super.prototype._update.call(this);
  6691. this.follow(this.target);
  6692. };
  6693. return FollowCamera;
  6694. })(BABYLON.TargetCamera);
  6695. BABYLON.FollowCamera = FollowCamera;
  6696. })(BABYLON || (BABYLON = {}));
  6697. //# sourceMappingURL=babylon.followCamera.js.map
  6698. var BABYLON;
  6699. (function (BABYLON) {
  6700. var FreeCamera = (function (_super) {
  6701. __extends(FreeCamera, _super);
  6702. function FreeCamera(name, position, scene) {
  6703. _super.call(this, name, position, scene);
  6704. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6705. this.keysUp = [38];
  6706. this.keysDown = [40];
  6707. this.keysLeft = [37];
  6708. this.keysRight = [39];
  6709. this.checkCollisions = false;
  6710. this.applyGravity = false;
  6711. this.angularSensibility = 2000.0;
  6712. this._keys = [];
  6713. this._collider = new BABYLON.Collider();
  6714. this._needMoveForGravity = true;
  6715. this._oldPosition = BABYLON.Vector3.Zero();
  6716. this._diffPosition = BABYLON.Vector3.Zero();
  6717. this._newPosition = BABYLON.Vector3.Zero();
  6718. }
  6719. // Controls
  6720. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6721. var _this = this;
  6722. var previousPosition;
  6723. var engine = this.getEngine();
  6724. if (this._attachedElement) {
  6725. return;
  6726. }
  6727. this._attachedElement = element;
  6728. if (this._onMouseDown === undefined) {
  6729. this._onMouseDown = function (evt) {
  6730. previousPosition = {
  6731. x: evt.clientX,
  6732. y: evt.clientY
  6733. };
  6734. if (!noPreventDefault) {
  6735. evt.preventDefault();
  6736. }
  6737. };
  6738. this._onMouseUp = function (evt) {
  6739. previousPosition = null;
  6740. if (!noPreventDefault) {
  6741. evt.preventDefault();
  6742. }
  6743. };
  6744. this._onMouseOut = function (evt) {
  6745. previousPosition = null;
  6746. _this._keys = [];
  6747. if (!noPreventDefault) {
  6748. evt.preventDefault();
  6749. }
  6750. };
  6751. this._onMouseMove = function (evt) {
  6752. if (!previousPosition && !engine.isPointerLock) {
  6753. return;
  6754. }
  6755. var offsetX;
  6756. var offsetY;
  6757. if (!engine.isPointerLock) {
  6758. offsetX = evt.clientX - previousPosition.x;
  6759. offsetY = evt.clientY - previousPosition.y;
  6760. }
  6761. else {
  6762. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6763. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6764. }
  6765. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6766. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6767. previousPosition = {
  6768. x: evt.clientX,
  6769. y: evt.clientY
  6770. };
  6771. if (!noPreventDefault) {
  6772. evt.preventDefault();
  6773. }
  6774. };
  6775. this._onKeyDown = function (evt) {
  6776. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6777. var index = _this._keys.indexOf(evt.keyCode);
  6778. if (index === -1) {
  6779. _this._keys.push(evt.keyCode);
  6780. }
  6781. if (!noPreventDefault) {
  6782. evt.preventDefault();
  6783. }
  6784. }
  6785. };
  6786. this._onKeyUp = function (evt) {
  6787. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6788. var index = _this._keys.indexOf(evt.keyCode);
  6789. if (index >= 0) {
  6790. _this._keys.splice(index, 1);
  6791. }
  6792. if (!noPreventDefault) {
  6793. evt.preventDefault();
  6794. }
  6795. }
  6796. };
  6797. this._onLostFocus = function () {
  6798. _this._keys = [];
  6799. };
  6800. this._reset = function () {
  6801. _this._keys = [];
  6802. previousPosition = null;
  6803. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6804. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6805. };
  6806. }
  6807. element.addEventListener("mousedown", this._onMouseDown, false);
  6808. element.addEventListener("mouseup", this._onMouseUp, false);
  6809. element.addEventListener("mouseout", this._onMouseOut, false);
  6810. element.addEventListener("mousemove", this._onMouseMove, false);
  6811. BABYLON.Tools.RegisterTopRootEvents([
  6812. { name: "keydown", handler: this._onKeyDown },
  6813. { name: "keyup", handler: this._onKeyUp },
  6814. { name: "blur", handler: this._onLostFocus }
  6815. ]);
  6816. };
  6817. FreeCamera.prototype.detachControl = function (element) {
  6818. if (this._attachedElement != element) {
  6819. return;
  6820. }
  6821. element.removeEventListener("mousedown", this._onMouseDown);
  6822. element.removeEventListener("mouseup", this._onMouseUp);
  6823. element.removeEventListener("mouseout", this._onMouseOut);
  6824. element.removeEventListener("mousemove", this._onMouseMove);
  6825. BABYLON.Tools.UnregisterTopRootEvents([
  6826. { name: "keydown", handler: this._onKeyDown },
  6827. { name: "keyup", handler: this._onKeyUp },
  6828. { name: "blur", handler: this._onLostFocus }
  6829. ]);
  6830. this._attachedElement = null;
  6831. if (this._reset) {
  6832. this._reset();
  6833. }
  6834. };
  6835. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6836. var globalPosition;
  6837. if (this.parent) {
  6838. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6839. }
  6840. else {
  6841. globalPosition = this.position;
  6842. }
  6843. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6844. this._collider.radius = this.ellipsoid;
  6845. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6846. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6847. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6848. this.position.addInPlace(this._diffPosition);
  6849. if (this.onCollide) {
  6850. this.onCollide(this._collider.collidedMesh);
  6851. }
  6852. }
  6853. };
  6854. FreeCamera.prototype._checkInputs = function () {
  6855. if (!this._localDirection) {
  6856. this._localDirection = BABYLON.Vector3.Zero();
  6857. this._transformedDirection = BABYLON.Vector3.Zero();
  6858. }
  6859. for (var index = 0; index < this._keys.length; index++) {
  6860. var keyCode = this._keys[index];
  6861. var speed = this._computeLocalCameraSpeed();
  6862. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6863. this._localDirection.copyFromFloats(-speed, 0, 0);
  6864. }
  6865. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6866. this._localDirection.copyFromFloats(0, 0, speed);
  6867. }
  6868. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6869. this._localDirection.copyFromFloats(speed, 0, 0);
  6870. }
  6871. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6872. this._localDirection.copyFromFloats(0, 0, -speed);
  6873. }
  6874. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6875. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6876. this.cameraDirection.addInPlace(this._transformedDirection);
  6877. }
  6878. };
  6879. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6880. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6881. };
  6882. FreeCamera.prototype._updatePosition = function () {
  6883. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6884. this._collideWithWorld(this.cameraDirection);
  6885. if (this.applyGravity) {
  6886. var oldPosition = this.position;
  6887. this._collideWithWorld(this.getScene().gravity);
  6888. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6889. }
  6890. }
  6891. else {
  6892. this.position.addInPlace(this.cameraDirection);
  6893. }
  6894. };
  6895. FreeCamera.prototype._update = function () {
  6896. this._checkInputs();
  6897. _super.prototype._update.call(this);
  6898. };
  6899. return FreeCamera;
  6900. })(BABYLON.TargetCamera);
  6901. BABYLON.FreeCamera = FreeCamera;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.freeCamera.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. // We're mainly based on the logic defined into the FreeCamera code
  6907. var TouchCamera = (function (_super) {
  6908. __extends(TouchCamera, _super);
  6909. function TouchCamera(name, position, scene) {
  6910. _super.call(this, name, position, scene);
  6911. this._offsetX = null;
  6912. this._offsetY = null;
  6913. this._pointerCount = 0;
  6914. this._pointerPressed = [];
  6915. this.angularSensibility = 200000.0;
  6916. this.moveSensibility = 500.0;
  6917. }
  6918. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6919. var _this = this;
  6920. var previousPosition;
  6921. if (this._attachedCanvas) {
  6922. return;
  6923. }
  6924. this._attachedCanvas = canvas;
  6925. if (this._onPointerDown === undefined) {
  6926. this._onPointerDown = function (evt) {
  6927. if (!noPreventDefault) {
  6928. evt.preventDefault();
  6929. }
  6930. _this._pointerPressed.push(evt.pointerId);
  6931. if (_this._pointerPressed.length !== 1) {
  6932. return;
  6933. }
  6934. previousPosition = {
  6935. x: evt.clientX,
  6936. y: evt.clientY
  6937. };
  6938. };
  6939. this._onPointerUp = function (evt) {
  6940. if (!noPreventDefault) {
  6941. evt.preventDefault();
  6942. }
  6943. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6944. if (index === -1) {
  6945. return;
  6946. }
  6947. _this._pointerPressed.splice(index, 1);
  6948. if (index != 0) {
  6949. return;
  6950. }
  6951. previousPosition = null;
  6952. _this._offsetX = null;
  6953. _this._offsetY = null;
  6954. };
  6955. this._onPointerMove = function (evt) {
  6956. if (!noPreventDefault) {
  6957. evt.preventDefault();
  6958. }
  6959. if (!previousPosition) {
  6960. return;
  6961. }
  6962. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6963. if (index != 0) {
  6964. return;
  6965. }
  6966. _this._offsetX = evt.clientX - previousPosition.x;
  6967. _this._offsetY = -(evt.clientY - previousPosition.y);
  6968. };
  6969. this._onLostFocus = function () {
  6970. _this._offsetX = null;
  6971. _this._offsetY = null;
  6972. };
  6973. }
  6974. canvas.addEventListener("pointerdown", this._onPointerDown);
  6975. canvas.addEventListener("pointerup", this._onPointerUp);
  6976. canvas.addEventListener("pointerout", this._onPointerUp);
  6977. canvas.addEventListener("pointermove", this._onPointerMove);
  6978. BABYLON.Tools.RegisterTopRootEvents([
  6979. { name: "blur", handler: this._onLostFocus }
  6980. ]);
  6981. };
  6982. TouchCamera.prototype.detachControl = function (canvas) {
  6983. if (this._attachedCanvas != canvas) {
  6984. return;
  6985. }
  6986. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6987. canvas.removeEventListener("pointerup", this._onPointerUp);
  6988. canvas.removeEventListener("pointerout", this._onPointerUp);
  6989. canvas.removeEventListener("pointermove", this._onPointerMove);
  6990. BABYLON.Tools.UnregisterTopRootEvents([
  6991. { name: "blur", handler: this._onLostFocus }
  6992. ]);
  6993. this._attachedCanvas = null;
  6994. };
  6995. TouchCamera.prototype._checkInputs = function () {
  6996. if (!this._offsetX) {
  6997. return;
  6998. }
  6999. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7000. if (this._pointerPressed.length > 1) {
  7001. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7002. }
  7003. else {
  7004. var speed = this._computeLocalCameraSpeed();
  7005. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7006. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7007. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7008. }
  7009. };
  7010. return TouchCamera;
  7011. })(BABYLON.FreeCamera);
  7012. BABYLON.TouchCamera = TouchCamera;
  7013. })(BABYLON || (BABYLON = {}));
  7014. //# sourceMappingURL=babylon.touchCamera.js.map
  7015. var BABYLON;
  7016. (function (BABYLON) {
  7017. // We're mainly based on the logic defined into the FreeCamera code
  7018. var DeviceOrientationCamera = (function (_super) {
  7019. __extends(DeviceOrientationCamera, _super);
  7020. function DeviceOrientationCamera(name, position, scene) {
  7021. var _this = this;
  7022. _super.call(this, name, position, scene);
  7023. this._offsetX = null;
  7024. this._offsetY = null;
  7025. this._orientationGamma = 0;
  7026. this._orientationBeta = 0;
  7027. this._initialOrientationGamma = 0;
  7028. this._initialOrientationBeta = 0;
  7029. this.angularSensibility = 10000.0;
  7030. this.moveSensibility = 50.0;
  7031. window.addEventListener("resize", function () {
  7032. _this._initialOrientationGamma = null;
  7033. }, false);
  7034. }
  7035. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7036. var _this = this;
  7037. if (this._attachedCanvas) {
  7038. return;
  7039. }
  7040. this._attachedCanvas = canvas;
  7041. if (!this._orientationChanged) {
  7042. this._orientationChanged = function (evt) {
  7043. if (!_this._initialOrientationGamma) {
  7044. _this._initialOrientationGamma = evt.gamma;
  7045. _this._initialOrientationBeta = evt.beta;
  7046. }
  7047. _this._orientationGamma = evt.gamma;
  7048. _this._orientationBeta = evt.beta;
  7049. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7050. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7051. };
  7052. }
  7053. window.addEventListener("deviceorientation", this._orientationChanged);
  7054. };
  7055. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7056. if (this._attachedCanvas != canvas) {
  7057. return;
  7058. }
  7059. window.removeEventListener("deviceorientation", this._orientationChanged);
  7060. this._attachedCanvas = null;
  7061. this._orientationGamma = 0;
  7062. this._orientationBeta = 0;
  7063. this._initialOrientationGamma = 0;
  7064. this._initialOrientationBeta = 0;
  7065. };
  7066. DeviceOrientationCamera.prototype._checkInputs = function () {
  7067. if (!this._offsetX) {
  7068. return;
  7069. }
  7070. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7071. var speed = this._computeLocalCameraSpeed();
  7072. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7073. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7074. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7075. };
  7076. return DeviceOrientationCamera;
  7077. })(BABYLON.FreeCamera);
  7078. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7079. })(BABYLON || (BABYLON = {}));
  7080. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7081. var BABYLON;
  7082. (function (BABYLON) {
  7083. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7084. var ArcRotateCamera = (function (_super) {
  7085. __extends(ArcRotateCamera, _super);
  7086. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7087. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7088. this.alpha = alpha;
  7089. this.beta = beta;
  7090. this.radius = radius;
  7091. this.target = target;
  7092. this.inertialAlphaOffset = 0;
  7093. this.inertialBetaOffset = 0;
  7094. this.inertialRadiusOffset = 0;
  7095. this.lowerAlphaLimit = null;
  7096. this.upperAlphaLimit = null;
  7097. this.lowerBetaLimit = 0.01;
  7098. this.upperBetaLimit = Math.PI;
  7099. this.lowerRadiusLimit = null;
  7100. this.upperRadiusLimit = null;
  7101. this.angularSensibility = 1000.0;
  7102. this.wheelPrecision = 3.0;
  7103. this.keysUp = [38];
  7104. this.keysDown = [40];
  7105. this.keysLeft = [37];
  7106. this.keysRight = [39];
  7107. this.zoomOnFactor = 1;
  7108. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7109. this._keys = [];
  7110. this._viewMatrix = new BABYLON.Matrix();
  7111. this.checkCollisions = false;
  7112. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7113. this._collider = new BABYLON.Collider();
  7114. this._previousPosition = BABYLON.Vector3.Zero();
  7115. this._collisionVelocity = BABYLON.Vector3.Zero();
  7116. this._newPosition = BABYLON.Vector3.Zero();
  7117. // Pinch
  7118. // value for pinch step scaling
  7119. // set to 20 by default
  7120. this.pinchPrecision = 20;
  7121. this.getViewMatrix();
  7122. }
  7123. ArcRotateCamera.prototype._getTargetPosition = function () {
  7124. return this.target.position || this.target;
  7125. };
  7126. // Cache
  7127. ArcRotateCamera.prototype._initCache = function () {
  7128. _super.prototype._initCache.call(this);
  7129. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7130. this._cache.alpha = undefined;
  7131. this._cache.beta = undefined;
  7132. this._cache.radius = undefined;
  7133. this._cache.targetScreenOffset = undefined;
  7134. };
  7135. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7136. if (!ignoreParentClass) {
  7137. _super.prototype._updateCache.call(this);
  7138. }
  7139. this._cache.target.copyFrom(this._getTargetPosition());
  7140. this._cache.alpha = this.alpha;
  7141. this._cache.beta = this.beta;
  7142. this._cache.radius = this.radius;
  7143. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7144. };
  7145. // Synchronized
  7146. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7147. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7148. return false;
  7149. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  7150. };
  7151. // Methods
  7152. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7153. var _this = this;
  7154. var previousPosition;
  7155. var pointerId;
  7156. // to know if pinch started
  7157. var pinchStarted = false;
  7158. // two pinch point on X
  7159. // that will use for find if user action is pinch open or pinch close
  7160. var pinchPointX1, pinchPointX2;
  7161. if (this._attachedElement) {
  7162. return;
  7163. }
  7164. this._attachedElement = element;
  7165. var engine = this.getEngine();
  7166. if (this._onPointerDown === undefined) {
  7167. this._onPointerDown = function (evt) {
  7168. if (pointerId) {
  7169. return;
  7170. }
  7171. pointerId = evt.pointerId;
  7172. previousPosition = {
  7173. x: evt.clientX,
  7174. y: evt.clientY
  7175. };
  7176. if (!noPreventDefault) {
  7177. evt.preventDefault();
  7178. }
  7179. };
  7180. this._onPointerUp = function (evt) {
  7181. previousPosition = null;
  7182. pointerId = null;
  7183. if (!noPreventDefault) {
  7184. evt.preventDefault();
  7185. }
  7186. };
  7187. this._onPointerMove = function (evt) {
  7188. if (!previousPosition) {
  7189. return;
  7190. }
  7191. if (pointerId !== evt.pointerId) {
  7192. return;
  7193. }
  7194. // return pinch is started
  7195. if (pinchStarted) {
  7196. return;
  7197. }
  7198. var offsetX = evt.clientX - previousPosition.x;
  7199. var offsetY = evt.clientY - previousPosition.y;
  7200. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7201. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7202. previousPosition = {
  7203. x: evt.clientX,
  7204. y: evt.clientY
  7205. };
  7206. if (!noPreventDefault) {
  7207. evt.preventDefault();
  7208. }
  7209. };
  7210. this._onMouseMove = function (evt) {
  7211. if (!engine.isPointerLock) {
  7212. return;
  7213. }
  7214. // return pinch is started
  7215. if (pinchStarted) {
  7216. return;
  7217. }
  7218. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7219. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7220. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7221. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7222. if (!noPreventDefault) {
  7223. evt.preventDefault();
  7224. }
  7225. };
  7226. this._wheel = function (event) {
  7227. var delta = 0;
  7228. if (event.wheelDelta) {
  7229. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7230. }
  7231. else if (event.detail) {
  7232. delta = -event.detail / _this.wheelPrecision;
  7233. }
  7234. if (delta)
  7235. _this.inertialRadiusOffset += delta;
  7236. if (event.preventDefault) {
  7237. if (!noPreventDefault) {
  7238. event.preventDefault();
  7239. }
  7240. }
  7241. };
  7242. this._onKeyDown = function (evt) {
  7243. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7244. var index = _this._keys.indexOf(evt.keyCode);
  7245. if (index === -1) {
  7246. _this._keys.push(evt.keyCode);
  7247. }
  7248. if (evt.preventDefault) {
  7249. if (!noPreventDefault) {
  7250. evt.preventDefault();
  7251. }
  7252. }
  7253. }
  7254. };
  7255. this._onKeyUp = function (evt) {
  7256. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7257. var index = _this._keys.indexOf(evt.keyCode);
  7258. if (index >= 0) {
  7259. _this._keys.splice(index, 1);
  7260. }
  7261. if (evt.preventDefault) {
  7262. if (!noPreventDefault) {
  7263. evt.preventDefault();
  7264. }
  7265. }
  7266. }
  7267. };
  7268. this._onLostFocus = function () {
  7269. _this._keys = [];
  7270. pointerId = null;
  7271. };
  7272. this._onGestureStart = function (e) {
  7273. if (window.MSGesture === undefined) {
  7274. return;
  7275. }
  7276. if (!_this._MSGestureHandler) {
  7277. _this._MSGestureHandler = new MSGesture();
  7278. _this._MSGestureHandler.target = element;
  7279. }
  7280. _this._MSGestureHandler.addPointer(e.pointerId);
  7281. };
  7282. this._onGesture = function (e) {
  7283. _this.radius *= e.scale;
  7284. if (e.preventDefault) {
  7285. if (!noPreventDefault) {
  7286. e.stopPropagation();
  7287. e.preventDefault();
  7288. }
  7289. }
  7290. };
  7291. this._reset = function () {
  7292. _this._keys = [];
  7293. _this.inertialAlphaOffset = 0;
  7294. _this.inertialBetaOffset = 0;
  7295. _this.inertialRadiusOffset = 0;
  7296. previousPosition = null;
  7297. pointerId = null;
  7298. };
  7299. this._touchStart = function (event) {
  7300. if (event.touches.length === 2) {
  7301. //-- start pinch if two fingers on the screen
  7302. pinchStarted = true;
  7303. _this._pinchStart(event);
  7304. }
  7305. };
  7306. this._touchMove = function (event) {
  7307. if (pinchStarted) {
  7308. //-- make scaling
  7309. _this._pinchMove(event);
  7310. }
  7311. };
  7312. this._touchEnd = function (event) {
  7313. if (pinchStarted) {
  7314. //-- end of pinch
  7315. _this._pinchEnd(event);
  7316. }
  7317. };
  7318. this._pinchStart = function (event) {
  7319. // save origin touch point
  7320. pinchPointX1 = event.touches[0].clientX;
  7321. pinchPointX2 = event.touches[1].clientX;
  7322. // block the camera
  7323. // if not it rotate around target during pinch
  7324. pinchStarted = true;
  7325. };
  7326. this._pinchMove = function (event) {
  7327. // variable for new camera's radius
  7328. var delta = 0;
  7329. // variables to know if pinch open or pinch close
  7330. var direction = 1;
  7331. var distanceXOrigine, distanceXNow;
  7332. if (event.touches.length !== 2)
  7333. return;
  7334. // calculate absolute distances of the two fingers
  7335. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7336. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7337. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7338. if (distanceXNow < distanceXOrigine) {
  7339. direction = -1;
  7340. }
  7341. // calculate new radius
  7342. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7343. // set new radius
  7344. _this.inertialRadiusOffset -= delta;
  7345. // save origin touch point
  7346. pinchPointX1 = event.touches[0].clientX;
  7347. pinchPointX2 = event.touches[1].clientX;
  7348. };
  7349. this._pinchEnd = function (event) {
  7350. // cancel pinch and deblock camera rotation
  7351. pinchStarted = false;
  7352. };
  7353. }
  7354. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7355. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7356. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7357. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7358. element.addEventListener("mousemove", this._onMouseMove, false);
  7359. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7360. element.addEventListener("MSGestureChange", this._onGesture, false);
  7361. element.addEventListener('mousewheel', this._wheel, false);
  7362. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7363. // pinch
  7364. element.addEventListener('touchstart', this._touchStart, false);
  7365. element.addEventListener('touchmove', this._touchMove, false);
  7366. element.addEventListener('touchend', this._touchEnd, false);
  7367. BABYLON.Tools.RegisterTopRootEvents([
  7368. { name: "keydown", handler: this._onKeyDown },
  7369. { name: "keyup", handler: this._onKeyUp },
  7370. { name: "blur", handler: this._onLostFocus }
  7371. ]);
  7372. };
  7373. ArcRotateCamera.prototype.detachControl = function (element) {
  7374. if (this._attachedElement != element) {
  7375. return;
  7376. }
  7377. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7378. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7379. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7380. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7381. element.removeEventListener("mousemove", this._onMouseMove);
  7382. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7383. element.removeEventListener("MSGestureChange", this._onGesture);
  7384. element.removeEventListener('mousewheel', this._wheel);
  7385. element.removeEventListener('DOMMouseScroll', this._wheel);
  7386. // pinch
  7387. element.removeEventListener('touchstart', this._touchStart);
  7388. element.removeEventListener('touchmove', this._touchMove);
  7389. element.removeEventListener('touchend', this._touchEnd);
  7390. BABYLON.Tools.UnregisterTopRootEvents([
  7391. { name: "keydown", handler: this._onKeyDown },
  7392. { name: "keyup", handler: this._onKeyUp },
  7393. { name: "blur", handler: this._onLostFocus }
  7394. ]);
  7395. this._MSGestureHandler = null;
  7396. this._attachedElement = null;
  7397. if (this._reset) {
  7398. this._reset();
  7399. }
  7400. };
  7401. ArcRotateCamera.prototype._update = function () {
  7402. for (var index = 0; index < this._keys.length; index++) {
  7403. var keyCode = this._keys[index];
  7404. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7405. this.inertialAlphaOffset -= 0.01;
  7406. }
  7407. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7408. this.inertialBetaOffset -= 0.01;
  7409. }
  7410. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7411. this.inertialAlphaOffset += 0.01;
  7412. }
  7413. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7414. this.inertialBetaOffset += 0.01;
  7415. }
  7416. }
  7417. // Inertia
  7418. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7419. this.alpha += this.inertialAlphaOffset;
  7420. this.beta += this.inertialBetaOffset;
  7421. this.radius -= this.inertialRadiusOffset;
  7422. this.inertialAlphaOffset *= this.inertia;
  7423. this.inertialBetaOffset *= this.inertia;
  7424. this.inertialRadiusOffset *= this.inertia;
  7425. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7426. this.inertialAlphaOffset = 0;
  7427. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7428. this.inertialBetaOffset = 0;
  7429. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7430. this.inertialRadiusOffset = 0;
  7431. }
  7432. // Limits
  7433. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7434. this.alpha = this.lowerAlphaLimit;
  7435. }
  7436. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7437. this.alpha = this.upperAlphaLimit;
  7438. }
  7439. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7440. this.beta = this.lowerBetaLimit;
  7441. }
  7442. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7443. this.beta = this.upperBetaLimit;
  7444. }
  7445. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7446. this.radius = this.lowerRadiusLimit;
  7447. }
  7448. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7449. this.radius = this.upperRadiusLimit;
  7450. }
  7451. };
  7452. ArcRotateCamera.prototype.setPosition = function (position) {
  7453. var radiusv3 = position.subtract(this._getTargetPosition());
  7454. this.radius = radiusv3.length();
  7455. // Alpha
  7456. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7457. if (radiusv3.z < 0) {
  7458. this.alpha = 2 * Math.PI - this.alpha;
  7459. }
  7460. // Beta
  7461. this.beta = Math.acos(radiusv3.y / this.radius);
  7462. };
  7463. ArcRotateCamera.prototype._getViewMatrix = function () {
  7464. // Compute
  7465. var cosa = Math.cos(this.alpha);
  7466. var sina = Math.sin(this.alpha);
  7467. var cosb = Math.cos(this.beta);
  7468. var sinb = Math.sin(this.beta);
  7469. var target = this._getTargetPosition();
  7470. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7471. if (this.checkCollisions) {
  7472. this._collider.radius = this.collisionRadius;
  7473. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7474. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7475. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7476. this.position.copyFrom(this._previousPosition);
  7477. this.alpha = this._previousAlpha;
  7478. this.beta = this._previousBeta;
  7479. this.radius = this._previousRadius;
  7480. if (this.onCollide) {
  7481. this.onCollide(this._collider.collidedMesh);
  7482. }
  7483. }
  7484. }
  7485. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7486. this._previousAlpha = this.alpha;
  7487. this._previousBeta = this.beta;
  7488. this._previousRadius = this.radius;
  7489. this._previousPosition.copyFrom(this.position);
  7490. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7491. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7492. return this._viewMatrix;
  7493. };
  7494. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7495. meshes = meshes || this.getScene().meshes;
  7496. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7497. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7498. this.radius = distance * this.zoomOnFactor;
  7499. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7500. };
  7501. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7502. var meshesOrMinMaxVector;
  7503. var distance;
  7504. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7505. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7506. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7507. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7508. }
  7509. else {
  7510. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7511. distance = meshesOrMinMaxVectorAndDistance.distance;
  7512. }
  7513. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7514. this.maxZ = distance * 2;
  7515. };
  7516. return ArcRotateCamera;
  7517. })(BABYLON.Camera);
  7518. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7519. })(BABYLON || (BABYLON = {}));
  7520. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7521. (function (BABYLON) {
  7522. /**
  7523. * Represents a scene to be rendered by the engine.
  7524. * @see http://doc.babylonjs.com/page.php?p=21911
  7525. */
  7526. var Scene = (function () {
  7527. /**
  7528. * @constructor
  7529. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7530. */
  7531. function Scene(engine) {
  7532. // Members
  7533. this.autoClear = true;
  7534. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7535. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7536. this.forceWireframe = false;
  7537. this.forcePointsCloud = false;
  7538. this.forceShowBoundingBoxes = false;
  7539. this.animationsEnabled = true;
  7540. 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
  7541. // Fog
  7542. /**
  7543. * is fog enabled on this scene.
  7544. * @type {boolean}
  7545. */
  7546. this.fogEnabled = true;
  7547. this.fogMode = Scene.FOGMODE_NONE;
  7548. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7549. this.fogDensity = 0.1;
  7550. this.fogStart = 0;
  7551. this.fogEnd = 1000.0;
  7552. // Lights
  7553. /**
  7554. * is shadow enabled on this scene.
  7555. * @type {boolean}
  7556. */
  7557. this.shadowsEnabled = true;
  7558. /**
  7559. * is light enabled on this scene.
  7560. * @type {boolean}
  7561. */
  7562. this.lightsEnabled = true;
  7563. /**
  7564. * All of the lights added to this scene.
  7565. * @see BABYLON.Light
  7566. * @type {BABYLON.Light[]}
  7567. */
  7568. this.lights = new Array();
  7569. // Cameras
  7570. /**
  7571. * All of the cameras added to this scene.
  7572. * @see BABYLON.Camera
  7573. * @type {BABYLON.Camera[]}
  7574. */
  7575. this.cameras = new Array();
  7576. this.activeCameras = new Array();
  7577. // Meshes
  7578. /**
  7579. * All of the (abstract) meshes added to this scene.
  7580. * @see BABYLON.AbstractMesh
  7581. * @type {BABYLON.AbstractMesh[]}
  7582. */
  7583. this.meshes = new Array();
  7584. // Geometries
  7585. this._geometries = new Array();
  7586. this.materials = new Array();
  7587. this.multiMaterials = new Array();
  7588. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7589. // Textures
  7590. this.texturesEnabled = true;
  7591. this.textures = new Array();
  7592. // Particles
  7593. this.particlesEnabled = true;
  7594. this.particleSystems = new Array();
  7595. // Sprites
  7596. this.spriteManagers = new Array();
  7597. // Layers
  7598. this.layers = new Array();
  7599. // Skeletons
  7600. this.skeletonsEnabled = true;
  7601. this.skeletons = new Array();
  7602. // Lens flares
  7603. this.lensFlaresEnabled = true;
  7604. this.lensFlareSystems = new Array();
  7605. // Collisions
  7606. this.collisionsEnabled = true;
  7607. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7608. // Postprocesses
  7609. this.postProcessesEnabled = true;
  7610. // Customs render targets
  7611. this.renderTargetsEnabled = true;
  7612. this.customRenderTargets = new Array();
  7613. // Imported meshes
  7614. this.importedMeshesFiles = new Array();
  7615. this._actionManagers = new Array();
  7616. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7617. // Procedural textures
  7618. this.proceduralTexturesEnabled = true;
  7619. this._proceduralTextures = new Array();
  7620. this.soundTracks = new Array();
  7621. this._totalVertices = 0;
  7622. this._activeVertices = 0;
  7623. this._activeParticles = 0;
  7624. this._lastFrameDuration = 0;
  7625. this._evaluateActiveMeshesDuration = 0;
  7626. this._renderTargetsDuration = 0;
  7627. this._particlesDuration = 0;
  7628. this._renderDuration = 0;
  7629. this._spritesDuration = 0;
  7630. this._animationRatio = 0;
  7631. this._renderId = 0;
  7632. this._executeWhenReadyTimeoutId = -1;
  7633. this._toBeDisposed = new BABYLON.SmartArray(256);
  7634. this._onReadyCallbacks = new Array();
  7635. this._pendingData = []; //ANY
  7636. this._onBeforeRenderCallbacks = new Array();
  7637. this._onAfterRenderCallbacks = new Array();
  7638. this._activeMeshes = new BABYLON.SmartArray(256);
  7639. this._processedMaterials = new BABYLON.SmartArray(256);
  7640. this._renderTargets = new BABYLON.SmartArray(256);
  7641. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7642. this._activeSkeletons = new BABYLON.SmartArray(32);
  7643. this._activeBones = 0;
  7644. this._activeAnimatables = new Array();
  7645. this._transformMatrix = BABYLON.Matrix.Zero();
  7646. this._scaledPosition = BABYLON.Vector3.Zero();
  7647. this._scaledVelocity = BABYLON.Vector3.Zero();
  7648. this._engine = engine;
  7649. engine.scenes.push(this);
  7650. this._renderingManager = new BABYLON.RenderingManager(this);
  7651. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7652. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7653. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7654. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7655. this.attachControl();
  7656. this._debugLayer = new BABYLON.DebugLayer(this);
  7657. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7658. }
  7659. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7660. get: function () {
  7661. return Scene._FOGMODE_NONE;
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7667. get: function () {
  7668. return Scene._FOGMODE_EXP;
  7669. },
  7670. enumerable: true,
  7671. configurable: true
  7672. });
  7673. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7674. get: function () {
  7675. return Scene._FOGMODE_EXP2;
  7676. },
  7677. enumerable: true,
  7678. configurable: true
  7679. });
  7680. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7681. get: function () {
  7682. return Scene._FOGMODE_LINEAR;
  7683. },
  7684. enumerable: true,
  7685. configurable: true
  7686. });
  7687. Object.defineProperty(Scene.prototype, "debugLayer", {
  7688. // Properties
  7689. get: function () {
  7690. return this._debugLayer;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7696. /**
  7697. * The mesh that is currently under the pointer.
  7698. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7699. */
  7700. get: function () {
  7701. return this._meshUnderPointer;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Scene.prototype, "pointerX", {
  7707. /**
  7708. * Current on-screen X position of the pointer
  7709. * @return {number} X position of the pointer
  7710. */
  7711. get: function () {
  7712. return this._pointerX;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(Scene.prototype, "pointerY", {
  7718. /**
  7719. * Current on-screen Y position of the pointer
  7720. * @return {number} Y position of the pointer
  7721. */
  7722. get: function () {
  7723. return this._pointerY;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Scene.prototype.getCachedMaterial = function () {
  7729. return this._cachedMaterial;
  7730. };
  7731. Scene.prototype.getBoundingBoxRenderer = function () {
  7732. return this._boundingBoxRenderer;
  7733. };
  7734. Scene.prototype.getOutlineRenderer = function () {
  7735. return this._outlineRenderer;
  7736. };
  7737. Scene.prototype.getEngine = function () {
  7738. return this._engine;
  7739. };
  7740. Scene.prototype.getTotalVertices = function () {
  7741. return this._totalVertices;
  7742. };
  7743. Scene.prototype.getActiveVertices = function () {
  7744. return this._activeVertices;
  7745. };
  7746. Scene.prototype.getActiveParticles = function () {
  7747. return this._activeParticles;
  7748. };
  7749. Scene.prototype.getActiveBones = function () {
  7750. return this._activeBones;
  7751. };
  7752. // Stats
  7753. Scene.prototype.getLastFrameDuration = function () {
  7754. return this._lastFrameDuration;
  7755. };
  7756. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7757. return this._evaluateActiveMeshesDuration;
  7758. };
  7759. Scene.prototype.getActiveMeshes = function () {
  7760. return this._activeMeshes;
  7761. };
  7762. Scene.prototype.getRenderTargetsDuration = function () {
  7763. return this._renderTargetsDuration;
  7764. };
  7765. Scene.prototype.getRenderDuration = function () {
  7766. return this._renderDuration;
  7767. };
  7768. Scene.prototype.getParticlesDuration = function () {
  7769. return this._particlesDuration;
  7770. };
  7771. Scene.prototype.getSpritesDuration = function () {
  7772. return this._spritesDuration;
  7773. };
  7774. Scene.prototype.getAnimationRatio = function () {
  7775. return this._animationRatio;
  7776. };
  7777. Scene.prototype.getRenderId = function () {
  7778. return this._renderId;
  7779. };
  7780. Scene.prototype.incrementRenderId = function () {
  7781. this._renderId++;
  7782. };
  7783. Scene.prototype._updatePointerPosition = function (evt) {
  7784. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7785. this._pointerX = evt.clientX - canvasRect.left;
  7786. this._pointerY = evt.clientY - canvasRect.top;
  7787. if (this.cameraToUseForPointers) {
  7788. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7789. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7790. }
  7791. };
  7792. // Pointers handling
  7793. Scene.prototype.attachControl = function () {
  7794. var _this = this;
  7795. this._onPointerMove = function (evt) {
  7796. var canvas = _this._engine.getRenderingCanvas();
  7797. _this._updatePointerPosition(evt);
  7798. 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);
  7799. if (pickResult.hit) {
  7800. _this._meshUnderPointer = pickResult.pickedMesh;
  7801. _this.setPointerOverMesh(pickResult.pickedMesh);
  7802. canvas.style.cursor = "pointer";
  7803. }
  7804. else {
  7805. _this.setPointerOverMesh(null);
  7806. canvas.style.cursor = "";
  7807. _this._meshUnderPointer = null;
  7808. }
  7809. };
  7810. this._onPointerDown = function (evt) {
  7811. var predicate = null;
  7812. if (!_this.onPointerDown) {
  7813. predicate = function (mesh) {
  7814. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7815. };
  7816. }
  7817. _this._updatePointerPosition(evt);
  7818. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7819. if (pickResult.hit) {
  7820. if (pickResult.pickedMesh.actionManager) {
  7821. switch (evt.button) {
  7822. case 0:
  7823. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7824. break;
  7825. case 1:
  7826. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7827. break;
  7828. case 2:
  7829. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7830. break;
  7831. }
  7832. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7833. }
  7834. }
  7835. if (_this.onPointerDown) {
  7836. _this.onPointerDown(evt, pickResult);
  7837. }
  7838. };
  7839. this._onKeyDown = function (evt) {
  7840. if (_this.actionManager) {
  7841. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7842. }
  7843. };
  7844. this._onKeyUp = function (evt) {
  7845. if (_this.actionManager) {
  7846. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7847. }
  7848. };
  7849. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7850. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7851. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7852. BABYLON.Tools.RegisterTopRootEvents([
  7853. { name: "keydown", handler: this._onKeyDown },
  7854. { name: "keyup", handler: this._onKeyUp }
  7855. ]);
  7856. };
  7857. Scene.prototype.detachControl = function () {
  7858. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7859. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7860. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7861. BABYLON.Tools.UnregisterTopRootEvents([
  7862. { name: "keydown", handler: this._onKeyDown },
  7863. { name: "keyup", handler: this._onKeyUp }
  7864. ]);
  7865. };
  7866. // Ready
  7867. Scene.prototype.isReady = function () {
  7868. if (this._pendingData.length > 0) {
  7869. return false;
  7870. }
  7871. for (var index = 0; index < this._geometries.length; index++) {
  7872. var geometry = this._geometries[index];
  7873. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7874. return false;
  7875. }
  7876. }
  7877. for (index = 0; index < this.meshes.length; index++) {
  7878. var mesh = this.meshes[index];
  7879. if (!mesh.isReady()) {
  7880. return false;
  7881. }
  7882. var mat = mesh.material;
  7883. if (mat) {
  7884. if (!mat.isReady(mesh)) {
  7885. return false;
  7886. }
  7887. }
  7888. }
  7889. return true;
  7890. };
  7891. Scene.prototype.resetCachedMaterial = function () {
  7892. this._cachedMaterial = null;
  7893. };
  7894. Scene.prototype.registerBeforeRender = function (func) {
  7895. this._onBeforeRenderCallbacks.push(func);
  7896. };
  7897. Scene.prototype.unregisterBeforeRender = function (func) {
  7898. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7899. if (index > -1) {
  7900. this._onBeforeRenderCallbacks.splice(index, 1);
  7901. }
  7902. };
  7903. Scene.prototype.registerAfterRender = function (func) {
  7904. this._onAfterRenderCallbacks.push(func);
  7905. };
  7906. Scene.prototype.unregisterAfterRender = function (func) {
  7907. var index = this._onAfterRenderCallbacks.indexOf(func);
  7908. if (index > -1) {
  7909. this._onAfterRenderCallbacks.splice(index, 1);
  7910. }
  7911. };
  7912. Scene.prototype._addPendingData = function (data) {
  7913. this._pendingData.push(data);
  7914. };
  7915. Scene.prototype._removePendingData = function (data) {
  7916. var index = this._pendingData.indexOf(data);
  7917. if (index !== -1) {
  7918. this._pendingData.splice(index, 1);
  7919. }
  7920. };
  7921. Scene.prototype.getWaitingItemsCount = function () {
  7922. return this._pendingData.length;
  7923. };
  7924. /**
  7925. * Registers a function to be executed when the scene is ready.
  7926. * @param {Function} func - the function to be executed.
  7927. */
  7928. Scene.prototype.executeWhenReady = function (func) {
  7929. var _this = this;
  7930. this._onReadyCallbacks.push(func);
  7931. if (this._executeWhenReadyTimeoutId !== -1) {
  7932. return;
  7933. }
  7934. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7935. _this._checkIsReady();
  7936. }, 150);
  7937. };
  7938. Scene.prototype._checkIsReady = function () {
  7939. var _this = this;
  7940. if (this.isReady()) {
  7941. this._onReadyCallbacks.forEach(function (func) {
  7942. func();
  7943. });
  7944. this._onReadyCallbacks = [];
  7945. this._executeWhenReadyTimeoutId = -1;
  7946. return;
  7947. }
  7948. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7949. _this._checkIsReady();
  7950. }, 150);
  7951. };
  7952. // Animations
  7953. /**
  7954. * Will start the animation sequence of a given target
  7955. * @param target - the target
  7956. * @param {number} from - from which frame should animation start
  7957. * @param {number} to - till which frame should animation run.
  7958. * @param {boolean} [loop] - should the animation loop
  7959. * @param {number} [speedRatio] - the speed in which to run the animation
  7960. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7961. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7962. * @return {BABYLON.Animatable} the animatable object created for this animation
  7963. * @see BABYLON.Animatable
  7964. * @see http://doc.babylonjs.com/page.php?p=22081
  7965. */
  7966. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7967. if (speedRatio === undefined) {
  7968. speedRatio = 1.0;
  7969. }
  7970. this.stopAnimation(target);
  7971. if (!animatable) {
  7972. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7973. }
  7974. // Local animations
  7975. if (target.animations) {
  7976. animatable.appendAnimations(target, target.animations);
  7977. }
  7978. // Children animations
  7979. if (target.getAnimatables) {
  7980. var animatables = target.getAnimatables();
  7981. for (var index = 0; index < animatables.length; index++) {
  7982. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7983. }
  7984. }
  7985. return animatable;
  7986. };
  7987. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7988. if (speedRatio === undefined) {
  7989. speedRatio = 1.0;
  7990. }
  7991. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7992. return animatable;
  7993. };
  7994. Scene.prototype.getAnimatableByTarget = function (target) {
  7995. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7996. if (this._activeAnimatables[index].target === target) {
  7997. return this._activeAnimatables[index];
  7998. }
  7999. }
  8000. return null;
  8001. };
  8002. /**
  8003. * Will stop the animation of the given target
  8004. * @param target - the target
  8005. * @see beginAnimation
  8006. */
  8007. Scene.prototype.stopAnimation = function (target) {
  8008. var animatable = this.getAnimatableByTarget(target);
  8009. if (animatable) {
  8010. animatable.stop();
  8011. }
  8012. };
  8013. Scene.prototype._animate = function () {
  8014. if (!this.animationsEnabled) {
  8015. return;
  8016. }
  8017. if (!this._animationStartDate) {
  8018. this._animationStartDate = BABYLON.Tools.Now;
  8019. }
  8020. // Getting time
  8021. var now = BABYLON.Tools.Now;
  8022. var delay = now - this._animationStartDate;
  8023. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8024. if (!this._activeAnimatables[index]._animate(delay)) {
  8025. this._activeAnimatables.splice(index, 1);
  8026. index--;
  8027. }
  8028. }
  8029. };
  8030. // Matrix
  8031. Scene.prototype.getViewMatrix = function () {
  8032. return this._viewMatrix;
  8033. };
  8034. Scene.prototype.getProjectionMatrix = function () {
  8035. return this._projectionMatrix;
  8036. };
  8037. Scene.prototype.getTransformMatrix = function () {
  8038. return this._transformMatrix;
  8039. };
  8040. Scene.prototype.setTransformMatrix = function (view, projection) {
  8041. this._viewMatrix = view;
  8042. this._projectionMatrix = projection;
  8043. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8044. };
  8045. // Methods
  8046. /**
  8047. * sets the active camera of the scene using its ID
  8048. * @param {string} id - the camera's ID
  8049. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8050. * @see activeCamera
  8051. */
  8052. Scene.prototype.setActiveCameraByID = function (id) {
  8053. var camera = this.getCameraByID(id);
  8054. if (camera) {
  8055. this.activeCamera = camera;
  8056. return camera;
  8057. }
  8058. return null;
  8059. };
  8060. /**
  8061. * sets the active camera of the scene using its name
  8062. * @param {string} name - the camera's name
  8063. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8064. * @see activeCamera
  8065. */
  8066. Scene.prototype.setActiveCameraByName = function (name) {
  8067. var camera = this.getCameraByName(name);
  8068. if (camera) {
  8069. this.activeCamera = camera;
  8070. return camera;
  8071. }
  8072. return null;
  8073. };
  8074. /**
  8075. * get a material using its id
  8076. * @param {string} the material's ID
  8077. * @return {BABYLON.Material|null} the material or null if none found.
  8078. */
  8079. Scene.prototype.getMaterialByID = function (id) {
  8080. for (var index = 0; index < this.materials.length; index++) {
  8081. if (this.materials[index].id === id) {
  8082. return this.materials[index];
  8083. }
  8084. }
  8085. return null;
  8086. };
  8087. /**
  8088. * get a material using its name
  8089. * @param {string} the material's name
  8090. * @return {BABYLON.Material|null} the material or null if none found.
  8091. */
  8092. Scene.prototype.getMaterialByName = function (name) {
  8093. for (var index = 0; index < this.materials.length; index++) {
  8094. if (this.materials[index].name === name) {
  8095. return this.materials[index];
  8096. }
  8097. }
  8098. return null;
  8099. };
  8100. Scene.prototype.getCameraByID = function (id) {
  8101. for (var index = 0; index < this.cameras.length; index++) {
  8102. if (this.cameras[index].id === id) {
  8103. return this.cameras[index];
  8104. }
  8105. }
  8106. return null;
  8107. };
  8108. /**
  8109. * get a camera using its name
  8110. * @param {string} the camera's name
  8111. * @return {BABYLON.Camera|null} the camera or null if none found.
  8112. */
  8113. Scene.prototype.getCameraByName = function (name) {
  8114. for (var index = 0; index < this.cameras.length; index++) {
  8115. if (this.cameras[index].name === name) {
  8116. return this.cameras[index];
  8117. }
  8118. }
  8119. return null;
  8120. };
  8121. /**
  8122. * get a light node using its name
  8123. * @param {string} the light's name
  8124. * @return {BABYLON.Light|null} the light or null if none found.
  8125. */
  8126. Scene.prototype.getLightByName = function (name) {
  8127. for (var index = 0; index < this.lights.length; index++) {
  8128. if (this.lights[index].name === name) {
  8129. return this.lights[index];
  8130. }
  8131. }
  8132. return null;
  8133. };
  8134. /**
  8135. * get a light node using its ID
  8136. * @param {string} the light's id
  8137. * @return {BABYLON.Light|null} the light or null if none found.
  8138. */
  8139. Scene.prototype.getLightByID = function (id) {
  8140. for (var index = 0; index < this.lights.length; index++) {
  8141. if (this.lights[index].id === id) {
  8142. return this.lights[index];
  8143. }
  8144. }
  8145. return null;
  8146. };
  8147. /**
  8148. * get a geometry using its ID
  8149. * @param {string} the geometry's id
  8150. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8151. */
  8152. Scene.prototype.getGeometryByID = function (id) {
  8153. for (var index = 0; index < this._geometries.length; index++) {
  8154. if (this._geometries[index].id === id) {
  8155. return this._geometries[index];
  8156. }
  8157. }
  8158. return null;
  8159. };
  8160. /**
  8161. * add a new geometry to this scene.
  8162. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8163. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8164. * @return {boolean} was the geometry added or not
  8165. */
  8166. Scene.prototype.pushGeometry = function (geometry, force) {
  8167. if (!force && this.getGeometryByID(geometry.id)) {
  8168. return false;
  8169. }
  8170. this._geometries.push(geometry);
  8171. return true;
  8172. };
  8173. Scene.prototype.getGeometries = function () {
  8174. return this._geometries;
  8175. };
  8176. /**
  8177. * Get a the first added mesh found of a given ID
  8178. * @param {string} id - the id to search for
  8179. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8180. */
  8181. Scene.prototype.getMeshByID = function (id) {
  8182. for (var index = 0; index < this.meshes.length; index++) {
  8183. if (this.meshes[index].id === id) {
  8184. return this.meshes[index];
  8185. }
  8186. }
  8187. return null;
  8188. };
  8189. /**
  8190. * Get a the last added mesh found of a given ID
  8191. * @param {string} id - the id to search for
  8192. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8193. */
  8194. Scene.prototype.getLastMeshByID = function (id) {
  8195. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8196. if (this.meshes[index].id === id) {
  8197. return this.meshes[index];
  8198. }
  8199. }
  8200. return null;
  8201. };
  8202. /**
  8203. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8204. * @param {string} id - the id to search for
  8205. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8206. */
  8207. Scene.prototype.getLastEntryByID = function (id) {
  8208. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8209. if (this.meshes[index].id === id) {
  8210. return this.meshes[index];
  8211. }
  8212. }
  8213. for (index = this.cameras.length - 1; index >= 0; index--) {
  8214. if (this.cameras[index].id === id) {
  8215. return this.cameras[index];
  8216. }
  8217. }
  8218. for (index = this.lights.length - 1; index >= 0; index--) {
  8219. if (this.lights[index].id === id) {
  8220. return this.lights[index];
  8221. }
  8222. }
  8223. return null;
  8224. };
  8225. Scene.prototype.getNodeByName = function (name) {
  8226. var mesh = this.getMeshByName(name);
  8227. if (mesh) {
  8228. return mesh;
  8229. }
  8230. var light = this.getLightByName(name);
  8231. if (light) {
  8232. return light;
  8233. }
  8234. return this.getCameraByName(name);
  8235. };
  8236. Scene.prototype.getMeshByName = function (name) {
  8237. for (var index = 0; index < this.meshes.length; index++) {
  8238. if (this.meshes[index].name === name) {
  8239. return this.meshes[index];
  8240. }
  8241. }
  8242. return null;
  8243. };
  8244. Scene.prototype.getSoundByName = function (name) {
  8245. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8246. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8247. return this.mainSoundTrack.soundCollection[index];
  8248. }
  8249. }
  8250. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8251. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8252. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8253. return this.soundTracks[sdIndex].soundCollection[index];
  8254. }
  8255. }
  8256. }
  8257. return null;
  8258. };
  8259. Scene.prototype.getLastSkeletonByID = function (id) {
  8260. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8261. if (this.skeletons[index].id === id) {
  8262. return this.skeletons[index];
  8263. }
  8264. }
  8265. return null;
  8266. };
  8267. Scene.prototype.getSkeletonById = function (id) {
  8268. for (var index = 0; index < this.skeletons.length; index++) {
  8269. if (this.skeletons[index].id === id) {
  8270. return this.skeletons[index];
  8271. }
  8272. }
  8273. return null;
  8274. };
  8275. Scene.prototype.getSkeletonByName = function (name) {
  8276. for (var index = 0; index < this.skeletons.length; index++) {
  8277. if (this.skeletons[index].name === name) {
  8278. return this.skeletons[index];
  8279. }
  8280. }
  8281. return null;
  8282. };
  8283. Scene.prototype.isActiveMesh = function (mesh) {
  8284. return (this._activeMeshes.indexOf(mesh) !== -1);
  8285. };
  8286. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8287. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8288. var material = subMesh.getMaterial();
  8289. if (mesh.showSubMeshesBoundingBox) {
  8290. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8291. }
  8292. if (material) {
  8293. // Render targets
  8294. if (material.getRenderTargetTextures) {
  8295. if (this._processedMaterials.indexOf(material) === -1) {
  8296. this._processedMaterials.push(material);
  8297. this._renderTargets.concat(material.getRenderTargetTextures());
  8298. }
  8299. }
  8300. // Dispatch
  8301. this._activeVertices += subMesh.indexCount;
  8302. this._renderingManager.dispatch(subMesh);
  8303. }
  8304. }
  8305. };
  8306. Scene.prototype._evaluateActiveMeshes = function () {
  8307. this._activeMeshes.reset();
  8308. this._renderingManager.reset();
  8309. this._processedMaterials.reset();
  8310. this._activeParticleSystems.reset();
  8311. this._activeSkeletons.reset();
  8312. this._boundingBoxRenderer.reset();
  8313. if (!this._frustumPlanes) {
  8314. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8315. }
  8316. else {
  8317. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8318. }
  8319. // Meshes
  8320. var meshes;
  8321. var len;
  8322. if (this._selectionOctree) {
  8323. var selection = this._selectionOctree.select(this._frustumPlanes);
  8324. meshes = selection.data;
  8325. len = selection.length;
  8326. }
  8327. else {
  8328. len = this.meshes.length;
  8329. meshes = this.meshes;
  8330. }
  8331. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8332. var mesh = meshes[meshIndex];
  8333. if (mesh.isBlocked) {
  8334. continue;
  8335. }
  8336. this._totalVertices += mesh.getTotalVertices();
  8337. if (!mesh.isReady()) {
  8338. continue;
  8339. }
  8340. mesh.computeWorldMatrix();
  8341. // Intersections
  8342. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8343. this._meshesForIntersections.pushNoDuplicate(mesh);
  8344. }
  8345. // Switch to current LOD
  8346. var meshLOD = mesh.getLOD(this.activeCamera);
  8347. if (!meshLOD) {
  8348. continue;
  8349. }
  8350. mesh._preActivate();
  8351. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8352. this._activeMeshes.push(mesh);
  8353. mesh._activate(this._renderId);
  8354. this._activeMesh(meshLOD);
  8355. }
  8356. }
  8357. // Particle systems
  8358. var beforeParticlesDate = BABYLON.Tools.Now;
  8359. if (this.particlesEnabled) {
  8360. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8361. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8362. var particleSystem = this.particleSystems[particleIndex];
  8363. if (!particleSystem.isStarted()) {
  8364. continue;
  8365. }
  8366. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8367. this._activeParticleSystems.push(particleSystem);
  8368. particleSystem.animate();
  8369. }
  8370. }
  8371. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8372. }
  8373. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8374. };
  8375. Scene.prototype._activeMesh = function (mesh) {
  8376. if (mesh.skeleton && this.skeletonsEnabled) {
  8377. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8378. }
  8379. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8380. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8381. }
  8382. if (mesh && mesh.subMeshes) {
  8383. // Submeshes Octrees
  8384. var len;
  8385. var subMeshes;
  8386. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8387. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8388. len = intersections.length;
  8389. subMeshes = intersections.data;
  8390. }
  8391. else {
  8392. subMeshes = mesh.subMeshes;
  8393. len = subMeshes.length;
  8394. }
  8395. for (var subIndex = 0; subIndex < len; subIndex++) {
  8396. var subMesh = subMeshes[subIndex];
  8397. this._evaluateSubMesh(subMesh, mesh);
  8398. }
  8399. }
  8400. };
  8401. Scene.prototype.updateTransformMatrix = function (force) {
  8402. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8403. };
  8404. Scene.prototype._renderForCamera = function (camera) {
  8405. var engine = this._engine;
  8406. this.activeCamera = camera;
  8407. if (!this.activeCamera)
  8408. throw new Error("Active camera not set");
  8409. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8410. // Viewport
  8411. engine.setViewport(this.activeCamera.viewport);
  8412. // Camera
  8413. this._renderId++;
  8414. this.updateTransformMatrix();
  8415. if (this.beforeCameraRender) {
  8416. this.beforeCameraRender(this.activeCamera);
  8417. }
  8418. // Meshes
  8419. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8420. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8421. this._evaluateActiveMeshes();
  8422. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8423. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8424. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8425. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8426. skeleton.prepare();
  8427. this._activeBones += skeleton.bones.length;
  8428. }
  8429. // Render targets
  8430. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8431. if (this.renderTargetsEnabled) {
  8432. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8433. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8434. var renderTarget = this._renderTargets.data[renderIndex];
  8435. if (renderTarget._shouldRender()) {
  8436. this._renderId++;
  8437. renderTarget.render();
  8438. }
  8439. }
  8440. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8441. this._renderId++;
  8442. }
  8443. if (this._renderTargets.length > 0) {
  8444. engine.restoreDefaultFramebuffer();
  8445. }
  8446. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8447. // Prepare Frame
  8448. this.postProcessManager._prepareFrame();
  8449. var beforeRenderDate = BABYLON.Tools.Now;
  8450. // Backgrounds
  8451. if (this.layers.length) {
  8452. engine.setDepthBuffer(false);
  8453. var layerIndex;
  8454. var layer;
  8455. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8456. layer = this.layers[layerIndex];
  8457. if (layer.isBackground) {
  8458. layer.render();
  8459. }
  8460. }
  8461. engine.setDepthBuffer(true);
  8462. }
  8463. // Render
  8464. BABYLON.Tools.StartPerformanceCounter("Main render");
  8465. this._renderingManager.render(null, null, true, true);
  8466. BABYLON.Tools.EndPerformanceCounter("Main render");
  8467. // Bounding boxes
  8468. this._boundingBoxRenderer.render();
  8469. // Lens flares
  8470. if (this.lensFlaresEnabled) {
  8471. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8472. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8473. this.lensFlareSystems[lensFlareSystemIndex].render();
  8474. }
  8475. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8476. }
  8477. // Foregrounds
  8478. if (this.layers.length) {
  8479. engine.setDepthBuffer(false);
  8480. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8481. layer = this.layers[layerIndex];
  8482. if (!layer.isBackground) {
  8483. layer.render();
  8484. }
  8485. }
  8486. engine.setDepthBuffer(true);
  8487. }
  8488. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8489. // Finalize frame
  8490. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8491. // Update camera
  8492. this.activeCamera._updateFromScene();
  8493. // Reset some special arrays
  8494. this._renderTargets.reset();
  8495. if (this.afterCameraRender) {
  8496. this.afterCameraRender(this.activeCamera);
  8497. }
  8498. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8499. };
  8500. Scene.prototype._processSubCameras = function (camera) {
  8501. if (camera.subCameras.length === 0) {
  8502. this._renderForCamera(camera);
  8503. return;
  8504. }
  8505. for (var index = 0; index < camera.subCameras.length; index++) {
  8506. this._renderForCamera(camera.subCameras[index]);
  8507. }
  8508. this.activeCamera = camera;
  8509. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8510. // Update camera
  8511. this.activeCamera._updateFromScene();
  8512. };
  8513. Scene.prototype._checkIntersections = function () {
  8514. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8515. var sourceMesh = this._meshesForIntersections.data[index];
  8516. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8517. var action = sourceMesh.actionManager.actions[actionIndex];
  8518. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8519. var parameters = action.getTriggerParameter();
  8520. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8521. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8522. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8523. if (areIntersecting && currentIntersectionInProgress === -1) {
  8524. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8525. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8526. sourceMesh._intersectionsInProgress.push(otherMesh);
  8527. }
  8528. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8529. sourceMesh._intersectionsInProgress.push(otherMesh);
  8530. }
  8531. }
  8532. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8533. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8534. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8535. if (indexOfOther > -1) {
  8536. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8537. }
  8538. }
  8539. }
  8540. }
  8541. }
  8542. };
  8543. Scene.prototype.render = function () {
  8544. var startDate = BABYLON.Tools.Now;
  8545. this._particlesDuration = 0;
  8546. this._spritesDuration = 0;
  8547. this._activeParticles = 0;
  8548. this._renderDuration = 0;
  8549. this._renderTargetsDuration = 0;
  8550. this._evaluateActiveMeshesDuration = 0;
  8551. this._totalVertices = 0;
  8552. this._activeVertices = 0;
  8553. this._activeBones = 0;
  8554. this.getEngine().resetDrawCalls();
  8555. this._meshesForIntersections.reset();
  8556. this.resetCachedMaterial();
  8557. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8558. // Actions
  8559. if (this.actionManager) {
  8560. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8561. }
  8562. // Before render
  8563. if (this.beforeRender) {
  8564. this.beforeRender();
  8565. }
  8566. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8567. this._onBeforeRenderCallbacks[callbackIndex]();
  8568. }
  8569. // Animations
  8570. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8571. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8572. this._animate();
  8573. // Physics
  8574. if (this._physicsEngine) {
  8575. BABYLON.Tools.StartPerformanceCounter("Physics");
  8576. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8577. BABYLON.Tools.EndPerformanceCounter("Physics");
  8578. }
  8579. // Customs render targets
  8580. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8581. var engine = this.getEngine();
  8582. var currentActiveCamera = this.activeCamera;
  8583. if (this.renderTargetsEnabled) {
  8584. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8585. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8586. var renderTarget = this.customRenderTargets[customIndex];
  8587. if (renderTarget._shouldRender()) {
  8588. this._renderId++;
  8589. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8590. if (!this.activeCamera)
  8591. throw new Error("Active camera not set");
  8592. // Viewport
  8593. engine.setViewport(this.activeCamera.viewport);
  8594. // Camera
  8595. this.updateTransformMatrix();
  8596. renderTarget.render();
  8597. }
  8598. }
  8599. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8600. this._renderId++;
  8601. }
  8602. if (this.customRenderTargets.length > 0) {
  8603. engine.restoreDefaultFramebuffer();
  8604. }
  8605. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8606. this.activeCamera = currentActiveCamera;
  8607. // Procedural textures
  8608. if (this.proceduralTexturesEnabled) {
  8609. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8610. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8611. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8612. if (proceduralTexture._shouldRender()) {
  8613. proceduralTexture.render();
  8614. }
  8615. }
  8616. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8617. }
  8618. // Clear
  8619. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8620. // Shadows
  8621. if (this.shadowsEnabled) {
  8622. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8623. var light = this.lights[lightIndex];
  8624. var shadowGenerator = light.getShadowGenerator();
  8625. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8626. this._renderTargets.push(shadowGenerator.getShadowMap());
  8627. }
  8628. }
  8629. }
  8630. // Depth renderer
  8631. if (this._depthRenderer) {
  8632. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8633. }
  8634. // RenderPipeline
  8635. this.postProcessRenderPipelineManager.update();
  8636. // Multi-cameras?
  8637. if (this.activeCameras.length > 0) {
  8638. var currentRenderId = this._renderId;
  8639. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8640. this._renderId = currentRenderId;
  8641. this._processSubCameras(this.activeCameras[cameraIndex]);
  8642. }
  8643. }
  8644. else {
  8645. if (!this.activeCamera) {
  8646. throw new Error("No camera defined");
  8647. }
  8648. this._processSubCameras(this.activeCamera);
  8649. }
  8650. // Intersection checks
  8651. this._checkIntersections();
  8652. // Update the audio listener attached to the camera
  8653. this._updateAudioParameters();
  8654. // After render
  8655. if (this.afterRender) {
  8656. this.afterRender();
  8657. }
  8658. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8659. this._onAfterRenderCallbacks[callbackIndex]();
  8660. }
  8661. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8662. this._toBeDisposed.data[index].dispose();
  8663. this._toBeDisposed[index] = null;
  8664. }
  8665. this._toBeDisposed.reset();
  8666. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8667. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8668. };
  8669. Scene.prototype._updateAudioParameters = function () {
  8670. var listeningCamera;
  8671. var audioEngine = BABYLON.Engine.audioEngine;
  8672. if (this.activeCameras.length > 0) {
  8673. listeningCamera = this.activeCameras[0];
  8674. }
  8675. else {
  8676. listeningCamera = this.activeCamera;
  8677. }
  8678. if (listeningCamera && audioEngine.canUseWebAudio) {
  8679. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8680. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8681. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8682. cameraDirection.normalize();
  8683. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8684. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8685. var sound = this.mainSoundTrack.soundCollection[i];
  8686. if (sound.useCustomAttenuation) {
  8687. sound.updateDistanceFromListener();
  8688. }
  8689. }
  8690. for (i = 0; i < this.soundTracks.length; i++) {
  8691. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8692. sound = this.soundTracks[i].soundCollection[j];
  8693. if (sound.useCustomAttenuation) {
  8694. sound.updateDistanceFromListener();
  8695. }
  8696. }
  8697. }
  8698. }
  8699. };
  8700. Scene.prototype.enableDepthRenderer = function () {
  8701. if (this._depthRenderer) {
  8702. return this._depthRenderer;
  8703. }
  8704. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8705. return this._depthRenderer;
  8706. };
  8707. Scene.prototype.disableDepthRenderer = function () {
  8708. if (!this._depthRenderer) {
  8709. return;
  8710. }
  8711. this._depthRenderer.dispose();
  8712. this._depthRenderer = null;
  8713. };
  8714. Scene.prototype.dispose = function () {
  8715. this.beforeRender = null;
  8716. this.afterRender = null;
  8717. this.skeletons = [];
  8718. this._boundingBoxRenderer.dispose();
  8719. if (this._depthRenderer) {
  8720. this._depthRenderer.dispose();
  8721. }
  8722. // Debug layer
  8723. this.debugLayer.hide();
  8724. // Events
  8725. if (this.onDispose) {
  8726. this.onDispose();
  8727. }
  8728. this._onBeforeRenderCallbacks = [];
  8729. this._onAfterRenderCallbacks = [];
  8730. this.detachControl();
  8731. // Release sounds & sounds tracks
  8732. this.mainSoundTrack.dispose();
  8733. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8734. this.soundTracks[scIndex].dispose();
  8735. }
  8736. // Detach cameras
  8737. var canvas = this._engine.getRenderingCanvas();
  8738. var index;
  8739. for (index = 0; index < this.cameras.length; index++) {
  8740. this.cameras[index].detachControl(canvas);
  8741. }
  8742. while (this.lights.length) {
  8743. this.lights[0].dispose();
  8744. }
  8745. while (this.meshes.length) {
  8746. this.meshes[0].dispose(true);
  8747. }
  8748. while (this.cameras.length) {
  8749. this.cameras[0].dispose();
  8750. }
  8751. while (this.materials.length) {
  8752. this.materials[0].dispose();
  8753. }
  8754. while (this.particleSystems.length) {
  8755. this.particleSystems[0].dispose();
  8756. }
  8757. while (this.spriteManagers.length) {
  8758. this.spriteManagers[0].dispose();
  8759. }
  8760. while (this.layers.length) {
  8761. this.layers[0].dispose();
  8762. }
  8763. while (this.textures.length) {
  8764. this.textures[0].dispose();
  8765. }
  8766. // Post-processes
  8767. this.postProcessManager.dispose();
  8768. // Physics
  8769. if (this._physicsEngine) {
  8770. this.disablePhysicsEngine();
  8771. }
  8772. // Remove from engine
  8773. index = this._engine.scenes.indexOf(this);
  8774. if (index > -1) {
  8775. this._engine.scenes.splice(index, 1);
  8776. }
  8777. this._engine.wipeCaches();
  8778. };
  8779. // Collisions
  8780. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8781. if (excludedMesh === void 0) { excludedMesh = null; }
  8782. position.divideToRef(collider.radius, this._scaledPosition);
  8783. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8784. collider.retry = 0;
  8785. collider.initialVelocity = this._scaledVelocity;
  8786. collider.initialPosition = this._scaledPosition;
  8787. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8788. finalPosition.multiplyInPlace(collider.radius);
  8789. };
  8790. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8791. if (excludedMesh === void 0) { excludedMesh = null; }
  8792. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8793. if (collider.retry >= maximumRetry) {
  8794. finalPosition.copyFrom(position);
  8795. return;
  8796. }
  8797. collider._initialize(position, velocity, closeDistance);
  8798. for (var index = 0; index < this.meshes.length; index++) {
  8799. var mesh = this.meshes[index];
  8800. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8801. mesh._checkCollision(collider);
  8802. }
  8803. }
  8804. if (!collider.collisionFound) {
  8805. position.addToRef(velocity, finalPosition);
  8806. return;
  8807. }
  8808. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8809. collider._getResponse(position, velocity);
  8810. }
  8811. if (velocity.length() <= closeDistance) {
  8812. finalPosition.copyFrom(position);
  8813. return;
  8814. }
  8815. collider.retry++;
  8816. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8817. };
  8818. // Octrees
  8819. Scene.prototype.getWorldExtends = function () {
  8820. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8821. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8822. for (var index = 0; index < this.meshes.length; index++) {
  8823. var mesh = this.meshes[index];
  8824. mesh.computeWorldMatrix(true);
  8825. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8826. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8827. BABYLON.Tools.CheckExtends(minBox, min, max);
  8828. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8829. }
  8830. return {
  8831. min: min,
  8832. max: max
  8833. };
  8834. };
  8835. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8836. if (maxCapacity === void 0) { maxCapacity = 64; }
  8837. if (maxDepth === void 0) { maxDepth = 2; }
  8838. if (!this._selectionOctree) {
  8839. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8840. }
  8841. var worldExtends = this.getWorldExtends();
  8842. // Update octree
  8843. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8844. return this._selectionOctree;
  8845. };
  8846. // Picking
  8847. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8848. var engine = this._engine;
  8849. if (!camera) {
  8850. if (!this.activeCamera)
  8851. throw new Error("Active camera not set");
  8852. camera = this.activeCamera;
  8853. }
  8854. var cameraViewport = camera.viewport;
  8855. var viewport = cameraViewport.toGlobal(engine);
  8856. // Moving coordinates to local viewport world
  8857. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8858. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8859. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8860. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8861. };
  8862. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8863. var pickingInfo = null;
  8864. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8865. var mesh = this.meshes[meshIndex];
  8866. if (predicate) {
  8867. if (!predicate(mesh)) {
  8868. continue;
  8869. }
  8870. }
  8871. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8872. continue;
  8873. }
  8874. var world = mesh.getWorldMatrix();
  8875. var ray = rayFunction(world);
  8876. var result = mesh.intersects(ray, fastCheck);
  8877. if (!result || !result.hit)
  8878. continue;
  8879. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8880. continue;
  8881. pickingInfo = result;
  8882. if (fastCheck) {
  8883. break;
  8884. }
  8885. }
  8886. return pickingInfo || new BABYLON.PickingInfo();
  8887. };
  8888. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8889. var _this = this;
  8890. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8891. /// <param name="x">X position on screen</param>
  8892. /// <param name="y">Y position on screen</param>
  8893. /// <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>
  8894. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8895. /// <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>
  8896. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8897. };
  8898. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8899. var _this = this;
  8900. return this._internalPick(function (world) {
  8901. if (!_this._pickWithRayInverseMatrix) {
  8902. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8903. }
  8904. world.invertToRef(_this._pickWithRayInverseMatrix);
  8905. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8906. }, predicate, fastCheck);
  8907. };
  8908. Scene.prototype.setPointerOverMesh = function (mesh) {
  8909. if (this._pointerOverMesh === mesh) {
  8910. return;
  8911. }
  8912. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8913. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8914. }
  8915. this._pointerOverMesh = mesh;
  8916. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8917. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8918. }
  8919. };
  8920. Scene.prototype.getPointerOverMesh = function () {
  8921. return this._pointerOverMesh;
  8922. };
  8923. // Physics
  8924. Scene.prototype.getPhysicsEngine = function () {
  8925. return this._physicsEngine;
  8926. };
  8927. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8928. if (this._physicsEngine) {
  8929. return true;
  8930. }
  8931. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8932. if (!this._physicsEngine.isSupported()) {
  8933. this._physicsEngine = null;
  8934. return false;
  8935. }
  8936. this._physicsEngine._initialize(gravity);
  8937. return true;
  8938. };
  8939. Scene.prototype.disablePhysicsEngine = function () {
  8940. if (!this._physicsEngine) {
  8941. return;
  8942. }
  8943. this._physicsEngine.dispose();
  8944. this._physicsEngine = undefined;
  8945. };
  8946. Scene.prototype.isPhysicsEnabled = function () {
  8947. return this._physicsEngine !== undefined;
  8948. };
  8949. Scene.prototype.setGravity = function (gravity) {
  8950. if (!this._physicsEngine) {
  8951. return;
  8952. }
  8953. this._physicsEngine._setGravity(gravity);
  8954. };
  8955. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8956. if (parts.parts) {
  8957. options = parts;
  8958. parts = parts.parts;
  8959. }
  8960. if (!this._physicsEngine) {
  8961. return null;
  8962. }
  8963. for (var index = 0; index < parts.length; index++) {
  8964. var mesh = parts[index].mesh;
  8965. mesh._physicImpostor = parts[index].impostor;
  8966. mesh._physicsMass = options.mass / parts.length;
  8967. mesh._physicsFriction = options.friction;
  8968. mesh._physicRestitution = options.restitution;
  8969. }
  8970. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8971. };
  8972. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8973. for (var index = 0; index < compound.parts.length; index++) {
  8974. var mesh = compound.parts[index].mesh;
  8975. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8976. this._physicsEngine._unregisterMesh(mesh);
  8977. }
  8978. };
  8979. // Misc.
  8980. Scene.prototype.createDefaultCameraOrLight = function () {
  8981. // Light
  8982. if (this.lights.length === 0) {
  8983. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8984. }
  8985. // Camera
  8986. if (!this.activeCamera) {
  8987. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8988. // Compute position
  8989. var worldExtends = this.getWorldExtends();
  8990. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8991. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8992. camera.setTarget(worldCenter);
  8993. this.activeCamera = camera;
  8994. }
  8995. };
  8996. // Tags
  8997. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8998. if (tagsQuery === undefined) {
  8999. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9000. return list;
  9001. }
  9002. var listByTags = [];
  9003. forEach = forEach || (function (item) {
  9004. return;
  9005. });
  9006. for (var i in list) {
  9007. var item = list[i];
  9008. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9009. listByTags.push(item);
  9010. forEach(item);
  9011. }
  9012. }
  9013. return listByTags;
  9014. };
  9015. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9016. return this._getByTags(this.meshes, tagsQuery, forEach);
  9017. };
  9018. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9019. return this._getByTags(this.cameras, tagsQuery, forEach);
  9020. };
  9021. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9022. return this._getByTags(this.lights, tagsQuery, forEach);
  9023. };
  9024. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9025. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9026. };
  9027. // Statics
  9028. Scene._FOGMODE_NONE = 0;
  9029. Scene._FOGMODE_EXP = 1;
  9030. Scene._FOGMODE_EXP2 = 2;
  9031. Scene._FOGMODE_LINEAR = 3;
  9032. Scene.MinDeltaTime = 1.0;
  9033. Scene.MaxDeltaTime = 1000.0;
  9034. return Scene;
  9035. })();
  9036. BABYLON.Scene = Scene;
  9037. })(BABYLON || (BABYLON = {}));
  9038. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9039. (function (BABYLON) {
  9040. var VertexBuffer = (function () {
  9041. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9042. if (engine instanceof BABYLON.Mesh) {
  9043. this._engine = engine.getScene().getEngine();
  9044. }
  9045. else {
  9046. this._engine = engine;
  9047. }
  9048. this._updatable = updatable;
  9049. this._data = data;
  9050. if (!postponeInternalCreation) {
  9051. this.create();
  9052. }
  9053. this._kind = kind;
  9054. if (stride) {
  9055. this._strideSize = stride;
  9056. return;
  9057. }
  9058. switch (kind) {
  9059. case VertexBuffer.PositionKind:
  9060. this._strideSize = 3;
  9061. break;
  9062. case VertexBuffer.NormalKind:
  9063. this._strideSize = 3;
  9064. break;
  9065. case VertexBuffer.UVKind:
  9066. this._strideSize = 2;
  9067. break;
  9068. case VertexBuffer.UV2Kind:
  9069. this._strideSize = 2;
  9070. break;
  9071. case VertexBuffer.ColorKind:
  9072. this._strideSize = 4;
  9073. break;
  9074. case VertexBuffer.MatricesIndicesKind:
  9075. this._strideSize = 4;
  9076. break;
  9077. case VertexBuffer.MatricesWeightsKind:
  9078. this._strideSize = 4;
  9079. break;
  9080. }
  9081. }
  9082. // Properties
  9083. VertexBuffer.prototype.isUpdatable = function () {
  9084. return this._updatable;
  9085. };
  9086. VertexBuffer.prototype.getData = function () {
  9087. return this._data;
  9088. };
  9089. VertexBuffer.prototype.getBuffer = function () {
  9090. return this._buffer;
  9091. };
  9092. VertexBuffer.prototype.getStrideSize = function () {
  9093. return this._strideSize;
  9094. };
  9095. // Methods
  9096. VertexBuffer.prototype.create = function (data) {
  9097. if (!data && this._buffer) {
  9098. return; // nothing to do
  9099. }
  9100. data = data || this._data;
  9101. if (!this._buffer) {
  9102. if (this._updatable) {
  9103. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9104. }
  9105. else {
  9106. this._buffer = this._engine.createVertexBuffer(data);
  9107. }
  9108. }
  9109. if (this._updatable) {
  9110. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9111. this._data = data;
  9112. }
  9113. };
  9114. VertexBuffer.prototype.update = function (data) {
  9115. this.create(data);
  9116. };
  9117. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9118. if (!this._buffer) {
  9119. return;
  9120. }
  9121. if (this._updatable) {
  9122. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9123. this._data = null;
  9124. }
  9125. };
  9126. VertexBuffer.prototype.dispose = function () {
  9127. if (!this._buffer) {
  9128. return;
  9129. }
  9130. if (this._engine._releaseBuffer(this._buffer)) {
  9131. this._buffer = null;
  9132. }
  9133. };
  9134. Object.defineProperty(VertexBuffer, "PositionKind", {
  9135. get: function () {
  9136. return VertexBuffer._PositionKind;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(VertexBuffer, "NormalKind", {
  9142. get: function () {
  9143. return VertexBuffer._NormalKind;
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(VertexBuffer, "UVKind", {
  9149. get: function () {
  9150. return VertexBuffer._UVKind;
  9151. },
  9152. enumerable: true,
  9153. configurable: true
  9154. });
  9155. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9156. get: function () {
  9157. return VertexBuffer._UV2Kind;
  9158. },
  9159. enumerable: true,
  9160. configurable: true
  9161. });
  9162. Object.defineProperty(VertexBuffer, "ColorKind", {
  9163. get: function () {
  9164. return VertexBuffer._ColorKind;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9170. get: function () {
  9171. return VertexBuffer._MatricesIndicesKind;
  9172. },
  9173. enumerable: true,
  9174. configurable: true
  9175. });
  9176. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9177. get: function () {
  9178. return VertexBuffer._MatricesWeightsKind;
  9179. },
  9180. enumerable: true,
  9181. configurable: true
  9182. });
  9183. // Enums
  9184. VertexBuffer._PositionKind = "position";
  9185. VertexBuffer._NormalKind = "normal";
  9186. VertexBuffer._UVKind = "uv";
  9187. VertexBuffer._UV2Kind = "uv2";
  9188. VertexBuffer._ColorKind = "color";
  9189. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9190. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9191. return VertexBuffer;
  9192. })();
  9193. BABYLON.VertexBuffer = VertexBuffer;
  9194. })(BABYLON || (BABYLON = {}));
  9195. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9196. var BABYLON;
  9197. (function (BABYLON) {
  9198. var AbstractMesh = (function (_super) {
  9199. __extends(AbstractMesh, _super);
  9200. function AbstractMesh(name, scene) {
  9201. _super.call(this, name, scene);
  9202. // Properties
  9203. this.definedFacingForward = true; // orientation for POV movement & rotation
  9204. this.position = new BABYLON.Vector3(0, 0, 0);
  9205. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9206. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9207. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9208. this.visibility = 1.0;
  9209. this.alphaIndex = Number.MAX_VALUE;
  9210. this.infiniteDistance = false;
  9211. this.isVisible = true;
  9212. this.isPickable = true;
  9213. this.showBoundingBox = false;
  9214. this.showSubMeshesBoundingBox = false;
  9215. this.onDispose = null;
  9216. this.checkCollisions = false;
  9217. this.isBlocker = false;
  9218. this.renderingGroupId = 0;
  9219. this.receiveShadows = false;
  9220. this.renderOutline = false;
  9221. this.outlineColor = BABYLON.Color3.Red();
  9222. this.outlineWidth = 0.02;
  9223. this.renderOverlay = false;
  9224. this.overlayColor = BABYLON.Color3.Red();
  9225. this.overlayAlpha = 0.5;
  9226. this.hasVertexAlpha = false;
  9227. this.useVertexColors = true;
  9228. this.applyFog = true;
  9229. this.useOctreeForRenderingSelection = true;
  9230. this.useOctreeForPicking = true;
  9231. this.useOctreeForCollisions = true;
  9232. this.layerMask = 0xFFFFFFFF;
  9233. // Physics
  9234. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9235. // Collisions
  9236. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9237. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9238. this._collider = new BABYLON.Collider();
  9239. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9240. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9241. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9242. // Cache
  9243. this._localScaling = BABYLON.Matrix.Zero();
  9244. this._localRotation = BABYLON.Matrix.Zero();
  9245. this._localTranslation = BABYLON.Matrix.Zero();
  9246. this._localBillboard = BABYLON.Matrix.Zero();
  9247. this._localPivotScaling = BABYLON.Matrix.Zero();
  9248. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9249. this._localWorld = BABYLON.Matrix.Zero();
  9250. this._worldMatrix = BABYLON.Matrix.Zero();
  9251. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9252. this._absolutePosition = BABYLON.Vector3.Zero();
  9253. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9254. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9255. this._isDirty = false;
  9256. this._pivotMatrix = BABYLON.Matrix.Identity();
  9257. this._isDisposed = false;
  9258. this._renderId = 0;
  9259. this._intersectionsInProgress = new Array();
  9260. this._onAfterWorldMatrixUpdate = new Array();
  9261. scene.meshes.push(this);
  9262. }
  9263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9264. get: function () {
  9265. return AbstractMesh._BILLBOARDMODE_NONE;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9271. get: function () {
  9272. return AbstractMesh._BILLBOARDMODE_X;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9278. get: function () {
  9279. return AbstractMesh._BILLBOARDMODE_Y;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9285. get: function () {
  9286. return AbstractMesh._BILLBOARDMODE_Z;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9292. get: function () {
  9293. return AbstractMesh._BILLBOARDMODE_ALL;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9299. // Methods
  9300. get: function () {
  9301. return false;
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. AbstractMesh.prototype.getLOD = function (camera) {
  9307. return this;
  9308. };
  9309. AbstractMesh.prototype.getTotalVertices = function () {
  9310. return 0;
  9311. };
  9312. AbstractMesh.prototype.getIndices = function () {
  9313. return null;
  9314. };
  9315. AbstractMesh.prototype.getVerticesData = function (kind) {
  9316. return null;
  9317. };
  9318. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9319. return false;
  9320. };
  9321. AbstractMesh.prototype.getBoundingInfo = function () {
  9322. if (this._masterMesh) {
  9323. return this._masterMesh.getBoundingInfo();
  9324. }
  9325. if (!this._boundingInfo) {
  9326. this._updateBoundingInfo();
  9327. }
  9328. return this._boundingInfo;
  9329. };
  9330. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9331. get: function () {
  9332. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9333. },
  9334. enumerable: true,
  9335. configurable: true
  9336. });
  9337. AbstractMesh.prototype._preActivate = function () {
  9338. };
  9339. AbstractMesh.prototype._activate = function (renderId) {
  9340. this._renderId = renderId;
  9341. };
  9342. AbstractMesh.prototype.getWorldMatrix = function () {
  9343. if (this._masterMesh) {
  9344. return this._masterMesh.getWorldMatrix();
  9345. }
  9346. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9347. this.computeWorldMatrix();
  9348. }
  9349. return this._worldMatrix;
  9350. };
  9351. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9352. get: function () {
  9353. return this._worldMatrix;
  9354. },
  9355. enumerable: true,
  9356. configurable: true
  9357. });
  9358. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9359. get: function () {
  9360. return this._absolutePosition;
  9361. },
  9362. enumerable: true,
  9363. configurable: true
  9364. });
  9365. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9366. if (!this.rotationQuaternion) {
  9367. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9368. this.rotation = BABYLON.Vector3.Zero();
  9369. }
  9370. if (!space || space == 0 /* LOCAL */) {
  9371. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9372. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9373. }
  9374. else {
  9375. if (this.parent) {
  9376. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9377. invertParentWorldMatrix.invert();
  9378. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9379. }
  9380. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9381. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9382. }
  9383. };
  9384. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9385. var displacementVector = axis.scale(distance);
  9386. if (!space || space == 0 /* LOCAL */) {
  9387. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9388. this.setPositionWithLocalVector(tempV3);
  9389. }
  9390. else {
  9391. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9392. }
  9393. };
  9394. AbstractMesh.prototype.getAbsolutePosition = function () {
  9395. this.computeWorldMatrix();
  9396. return this._absolutePosition;
  9397. };
  9398. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9399. if (!absolutePosition) {
  9400. return;
  9401. }
  9402. var absolutePositionX;
  9403. var absolutePositionY;
  9404. var absolutePositionZ;
  9405. if (absolutePosition.x === undefined) {
  9406. if (arguments.length < 3) {
  9407. return;
  9408. }
  9409. absolutePositionX = arguments[0];
  9410. absolutePositionY = arguments[1];
  9411. absolutePositionZ = arguments[2];
  9412. }
  9413. else {
  9414. absolutePositionX = absolutePosition.x;
  9415. absolutePositionY = absolutePosition.y;
  9416. absolutePositionZ = absolutePosition.z;
  9417. }
  9418. if (this.parent) {
  9419. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9420. invertParentWorldMatrix.invert();
  9421. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9422. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9423. }
  9424. else {
  9425. this.position.x = absolutePositionX;
  9426. this.position.y = absolutePositionY;
  9427. this.position.z = absolutePositionZ;
  9428. }
  9429. };
  9430. // ================================== Point of View Movement =================================
  9431. /**
  9432. * Perform relative position change from the point of view of behind the front of the mesh.
  9433. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9434. * Supports definition of mesh facing forward or backward.
  9435. * @param {number} amountRight
  9436. * @param {number} amountUp
  9437. * @param {number} amountForward
  9438. */
  9439. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9440. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9441. };
  9442. /**
  9443. * Calculate relative position change from the point of view of behind the front of the mesh.
  9444. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9445. * Supports definition of mesh facing forward or backward.
  9446. * @param {number} amountRight
  9447. * @param {number} amountUp
  9448. * @param {number} amountForward
  9449. */
  9450. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9451. var rotMatrix = new BABYLON.Matrix();
  9452. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9453. rotQuaternion.toRotationMatrix(rotMatrix);
  9454. var translationDelta = BABYLON.Vector3.Zero();
  9455. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9456. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9457. return translationDelta;
  9458. };
  9459. // ================================== Point of View Rotation =================================
  9460. /**
  9461. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9462. * Supports definition of mesh facing forward or backward.
  9463. * @param {number} flipBack
  9464. * @param {number} twirlClockwise
  9465. * @param {number} tiltRight
  9466. */
  9467. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9468. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9469. };
  9470. /**
  9471. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9472. * Supports definition of mesh facing forward or backward.
  9473. * @param {number} flipBack
  9474. * @param {number} twirlClockwise
  9475. * @param {number} tiltRight
  9476. */
  9477. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9478. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9479. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9480. };
  9481. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9482. this._pivotMatrix = matrix;
  9483. this._cache.pivotMatrixUpdated = true;
  9484. };
  9485. AbstractMesh.prototype.getPivotMatrix = function () {
  9486. return this._pivotMatrix;
  9487. };
  9488. AbstractMesh.prototype._isSynchronized = function () {
  9489. if (this._isDirty) {
  9490. return false;
  9491. }
  9492. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9493. return false;
  9494. if (this._cache.pivotMatrixUpdated) {
  9495. return false;
  9496. }
  9497. if (this.infiniteDistance) {
  9498. return false;
  9499. }
  9500. if (!this._cache.position.equals(this.position))
  9501. return false;
  9502. if (this.rotationQuaternion) {
  9503. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9504. return false;
  9505. }
  9506. else {
  9507. if (!this._cache.rotation.equals(this.rotation))
  9508. return false;
  9509. }
  9510. if (!this._cache.scaling.equals(this.scaling))
  9511. return false;
  9512. return true;
  9513. };
  9514. AbstractMesh.prototype._initCache = function () {
  9515. _super.prototype._initCache.call(this);
  9516. this._cache.localMatrixUpdated = false;
  9517. this._cache.position = BABYLON.Vector3.Zero();
  9518. this._cache.scaling = BABYLON.Vector3.Zero();
  9519. this._cache.rotation = BABYLON.Vector3.Zero();
  9520. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9521. };
  9522. AbstractMesh.prototype.markAsDirty = function (property) {
  9523. if (property === "rotation") {
  9524. this.rotationQuaternion = null;
  9525. }
  9526. this._currentRenderId = Number.MAX_VALUE;
  9527. this._isDirty = true;
  9528. };
  9529. AbstractMesh.prototype._updateBoundingInfo = function () {
  9530. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9531. this._boundingInfo._update(this.worldMatrixFromCache);
  9532. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9533. };
  9534. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9535. if (!this.subMeshes) {
  9536. return;
  9537. }
  9538. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9539. var subMesh = this.subMeshes[subIndex];
  9540. subMesh.updateBoundingInfo(matrix);
  9541. }
  9542. };
  9543. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9544. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9545. return this._worldMatrix;
  9546. }
  9547. this._cache.position.copyFrom(this.position);
  9548. this._cache.scaling.copyFrom(this.scaling);
  9549. this._cache.pivotMatrixUpdated = false;
  9550. this._currentRenderId = this.getScene().getRenderId();
  9551. this._isDirty = false;
  9552. // Scaling
  9553. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9554. // Rotation
  9555. if (this.rotationQuaternion) {
  9556. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9557. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9558. }
  9559. else {
  9560. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9561. this._cache.rotation.copyFrom(this.rotation);
  9562. }
  9563. // Translation
  9564. if (this.infiniteDistance && !this.parent) {
  9565. var camera = this.getScene().activeCamera;
  9566. var cameraWorldMatrix = camera.getWorldMatrix();
  9567. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9568. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9569. }
  9570. else {
  9571. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9572. }
  9573. // Composing transformations
  9574. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9575. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9576. // Billboarding
  9577. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9578. var localPosition = this.position.clone();
  9579. var zero = this.getScene().activeCamera.position.clone();
  9580. if (this.parent && this.parent.position) {
  9581. localPosition.addInPlace(this.parent.position);
  9582. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9583. }
  9584. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9585. zero = this.getScene().activeCamera.position;
  9586. }
  9587. else {
  9588. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9589. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9590. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9591. zero.y = localPosition.y + 0.001;
  9592. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9593. zero.z = localPosition.z + 0.001;
  9594. }
  9595. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9596. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9597. this._localBillboard.invert();
  9598. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9599. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9600. }
  9601. // Local world
  9602. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9603. // Parent
  9604. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9605. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9606. }
  9607. else {
  9608. this._worldMatrix.copyFrom(this._localWorld);
  9609. }
  9610. // Bounding info
  9611. this._updateBoundingInfo();
  9612. // Absolute position
  9613. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9614. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9615. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9616. }
  9617. return this._worldMatrix;
  9618. };
  9619. /**
  9620. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9621. * @param func: callback function to add
  9622. */
  9623. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9624. this._onAfterWorldMatrixUpdate.push(func);
  9625. };
  9626. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9627. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9628. if (index > -1) {
  9629. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9630. }
  9631. };
  9632. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9633. this.computeWorldMatrix();
  9634. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9635. };
  9636. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9637. this.computeWorldMatrix();
  9638. var invLocalWorldMatrix = this._localWorld.clone();
  9639. invLocalWorldMatrix.invert();
  9640. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9641. };
  9642. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9643. this.computeWorldMatrix();
  9644. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9645. };
  9646. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9647. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9648. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9649. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9650. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9651. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9652. /// <returns>Mesh oriented towards targetMesh</returns>
  9653. yawCor = yawCor || 0; // default to zero if undefined
  9654. pitchCor = pitchCor || 0;
  9655. rollCor = rollCor || 0;
  9656. var dv = targetPoint.subtract(this.position);
  9657. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9658. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9659. var pitch = Math.atan2(dv.y, len);
  9660. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9661. };
  9662. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9663. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9664. return false;
  9665. }
  9666. return true;
  9667. };
  9668. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9669. if (!camera) {
  9670. camera = this.getScene().activeCamera;
  9671. }
  9672. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9673. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9674. return false;
  9675. }
  9676. return true;
  9677. };
  9678. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9679. if (!this._boundingInfo || !mesh._boundingInfo) {
  9680. return false;
  9681. }
  9682. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9683. };
  9684. AbstractMesh.prototype.intersectsPoint = function (point) {
  9685. if (!this._boundingInfo) {
  9686. return false;
  9687. }
  9688. return this._boundingInfo.intersectsPoint(point);
  9689. };
  9690. // Physics
  9691. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9692. var physicsEngine = this.getScene().getPhysicsEngine();
  9693. if (!physicsEngine) {
  9694. return;
  9695. }
  9696. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9697. if (impostor.impostor) {
  9698. // Old API
  9699. options = impostor;
  9700. impostor = impostor.impostor;
  9701. }
  9702. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9703. physicsEngine._unregisterMesh(this);
  9704. return;
  9705. }
  9706. if (!options) {
  9707. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9708. }
  9709. else {
  9710. if (!options.mass && options.mass !== 0)
  9711. options.mass = 0;
  9712. if (!options.friction && options.friction !== 0)
  9713. options.friction = 0.2;
  9714. if (!options.restitution && options.restitution !== 0)
  9715. options.restitution = 0.2;
  9716. }
  9717. this._physicImpostor = impostor;
  9718. this._physicsMass = options.mass;
  9719. this._physicsFriction = options.friction;
  9720. this._physicRestitution = options.restitution;
  9721. return physicsEngine._registerMesh(this, impostor, options);
  9722. };
  9723. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9724. if (!this._physicImpostor) {
  9725. return BABYLON.PhysicsEngine.NoImpostor;
  9726. }
  9727. return this._physicImpostor;
  9728. };
  9729. AbstractMesh.prototype.getPhysicsMass = function () {
  9730. if (!this._physicsMass) {
  9731. return 0;
  9732. }
  9733. return this._physicsMass;
  9734. };
  9735. AbstractMesh.prototype.getPhysicsFriction = function () {
  9736. if (!this._physicsFriction) {
  9737. return 0;
  9738. }
  9739. return this._physicsFriction;
  9740. };
  9741. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9742. if (!this._physicRestitution) {
  9743. return 0;
  9744. }
  9745. return this._physicRestitution;
  9746. };
  9747. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9748. if (!camera) {
  9749. camera = this.getScene().activeCamera;
  9750. }
  9751. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9752. };
  9753. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9754. if (!camera) {
  9755. camera = this.getScene().activeCamera;
  9756. }
  9757. return this.absolutePosition.subtract(camera.position).length();
  9758. };
  9759. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9760. if (!this._physicImpostor) {
  9761. return;
  9762. }
  9763. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9764. };
  9765. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9766. if (!this._physicImpostor) {
  9767. return;
  9768. }
  9769. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9770. };
  9771. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9772. if (!this._physicImpostor) {
  9773. return;
  9774. }
  9775. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9776. };
  9777. // Collisions
  9778. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9779. var globalPosition = this.getAbsolutePosition();
  9780. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9781. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9782. this._collider.radius = this.ellipsoid;
  9783. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9784. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9785. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9786. this.position.addInPlace(this._diffPositionForCollisions);
  9787. }
  9788. };
  9789. // Submeshes octree
  9790. /**
  9791. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9792. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9793. */
  9794. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9795. if (maxCapacity === void 0) { maxCapacity = 64; }
  9796. if (maxDepth === void 0) { maxDepth = 2; }
  9797. if (!this._submeshesOctree) {
  9798. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9799. }
  9800. this.computeWorldMatrix(true);
  9801. // Update octree
  9802. var bbox = this.getBoundingInfo().boundingBox;
  9803. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9804. return this._submeshesOctree;
  9805. };
  9806. // Collisions
  9807. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9808. this._generatePointsArray();
  9809. // Transformation
  9810. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9811. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9812. subMesh._lastColliderWorldVertices = [];
  9813. subMesh._trianglePlanes = [];
  9814. var start = subMesh.verticesStart;
  9815. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9816. for (var i = start; i < end; i++) {
  9817. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9818. }
  9819. }
  9820. // Collide
  9821. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9822. };
  9823. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9824. var subMeshes;
  9825. var len;
  9826. // Octrees
  9827. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9828. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9829. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9830. len = intersections.length;
  9831. subMeshes = intersections.data;
  9832. }
  9833. else {
  9834. subMeshes = this.subMeshes;
  9835. len = subMeshes.length;
  9836. }
  9837. for (var index = 0; index < len; index++) {
  9838. var subMesh = subMeshes[index];
  9839. // Bounding test
  9840. if (len > 1 && !subMesh._checkCollision(collider))
  9841. continue;
  9842. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9843. }
  9844. };
  9845. AbstractMesh.prototype._checkCollision = function (collider) {
  9846. // Bounding box test
  9847. if (!this._boundingInfo._checkCollision(collider))
  9848. return;
  9849. // Transformation matrix
  9850. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9851. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9852. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9853. };
  9854. // Picking
  9855. AbstractMesh.prototype._generatePointsArray = function () {
  9856. return false;
  9857. };
  9858. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9859. var pickingInfo = new BABYLON.PickingInfo();
  9860. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9861. return pickingInfo;
  9862. }
  9863. if (!this._generatePointsArray()) {
  9864. return pickingInfo;
  9865. }
  9866. var intersectInfo = null;
  9867. // Octrees
  9868. var subMeshes;
  9869. var len;
  9870. if (this._submeshesOctree && this.useOctreeForPicking) {
  9871. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9872. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9873. len = intersections.length;
  9874. subMeshes = intersections.data;
  9875. }
  9876. else {
  9877. subMeshes = this.subMeshes;
  9878. len = subMeshes.length;
  9879. }
  9880. for (var index = 0; index < len; index++) {
  9881. var subMesh = subMeshes[index];
  9882. // Bounding test
  9883. if (len > 1 && !subMesh.canIntersects(ray))
  9884. continue;
  9885. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9886. if (currentIntersectInfo) {
  9887. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9888. intersectInfo = currentIntersectInfo;
  9889. intersectInfo.subMeshId = index;
  9890. if (fastCheck) {
  9891. break;
  9892. }
  9893. }
  9894. }
  9895. }
  9896. if (intersectInfo) {
  9897. // Get picked point
  9898. var world = this.getWorldMatrix();
  9899. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9900. var direction = ray.direction.clone();
  9901. direction = direction.scale(intersectInfo.distance);
  9902. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9903. var pickedPoint = worldOrigin.add(worldDirection);
  9904. // Return result
  9905. pickingInfo.hit = true;
  9906. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9907. pickingInfo.pickedPoint = pickedPoint;
  9908. pickingInfo.pickedMesh = this;
  9909. pickingInfo.bu = intersectInfo.bu;
  9910. pickingInfo.bv = intersectInfo.bv;
  9911. pickingInfo.faceId = intersectInfo.faceId;
  9912. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9913. return pickingInfo;
  9914. }
  9915. return pickingInfo;
  9916. };
  9917. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9918. return null;
  9919. };
  9920. AbstractMesh.prototype.releaseSubMeshes = function () {
  9921. if (this.subMeshes) {
  9922. while (this.subMeshes.length) {
  9923. this.subMeshes[0].dispose();
  9924. }
  9925. }
  9926. else {
  9927. this.subMeshes = new Array();
  9928. }
  9929. };
  9930. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9931. // Physics
  9932. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9933. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9934. }
  9935. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9936. var other = this._intersectionsInProgress[index];
  9937. var pos = other._intersectionsInProgress.indexOf(this);
  9938. other._intersectionsInProgress.splice(pos, 1);
  9939. }
  9940. this._intersectionsInProgress = [];
  9941. // SubMeshes
  9942. this.releaseSubMeshes();
  9943. // Remove from scene
  9944. var index = this.getScene().meshes.indexOf(this);
  9945. if (index != -1) {
  9946. // Remove from the scene if mesh found
  9947. this.getScene().meshes.splice(index, 1);
  9948. }
  9949. if (!doNotRecurse) {
  9950. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9951. if (this.getScene().particleSystems[index].emitter == this) {
  9952. this.getScene().particleSystems[index].dispose();
  9953. index--;
  9954. }
  9955. }
  9956. // Children
  9957. var objects = this.getScene().meshes.slice(0);
  9958. for (index = 0; index < objects.length; index++) {
  9959. if (objects[index].parent == this) {
  9960. objects[index].dispose();
  9961. }
  9962. }
  9963. }
  9964. else {
  9965. for (index = 0; index < this.getScene().meshes.length; index++) {
  9966. var obj = this.getScene().meshes[index];
  9967. if (obj.parent === this) {
  9968. obj.parent = null;
  9969. obj.computeWorldMatrix(true);
  9970. }
  9971. }
  9972. }
  9973. this._onAfterWorldMatrixUpdate = [];
  9974. this._isDisposed = true;
  9975. // Callback
  9976. if (this.onDispose) {
  9977. this.onDispose();
  9978. }
  9979. };
  9980. // Statics
  9981. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9982. AbstractMesh._BILLBOARDMODE_X = 1;
  9983. AbstractMesh._BILLBOARDMODE_Y = 2;
  9984. AbstractMesh._BILLBOARDMODE_Z = 4;
  9985. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9986. return AbstractMesh;
  9987. })(BABYLON.Node);
  9988. BABYLON.AbstractMesh = AbstractMesh;
  9989. })(BABYLON || (BABYLON = {}));
  9990. //# sourceMappingURL=babylon.abstractMesh.js.map
  9991. var BABYLON;
  9992. (function (BABYLON) {
  9993. var _InstancesBatch = (function () {
  9994. function _InstancesBatch() {
  9995. this.mustReturn = false;
  9996. this.visibleInstances = new Array();
  9997. this.renderSelf = new Array();
  9998. }
  9999. return _InstancesBatch;
  10000. })();
  10001. BABYLON._InstancesBatch = _InstancesBatch;
  10002. var Mesh = (function (_super) {
  10003. __extends(Mesh, _super);
  10004. /**
  10005. * @constructor
  10006. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10007. * @param {Scene} scene - The scene to add this mesh to.
  10008. * @param {Node} parent - The parent of this mesh, if it has one
  10009. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10010. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10011. * When false, achieved by calling a clone(), also passing False.
  10012. * This will make creation of children, recursive.
  10013. */
  10014. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10015. if (parent === void 0) { parent = null; }
  10016. _super.call(this, name, scene);
  10017. // Members
  10018. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10019. this.instances = new Array();
  10020. this._LODLevels = new Array();
  10021. this._onBeforeRenderCallbacks = new Array();
  10022. this._onAfterRenderCallbacks = new Array();
  10023. this._visibleInstances = {};
  10024. this._renderIdForInstances = new Array();
  10025. this._batchCache = new _InstancesBatch();
  10026. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10027. if (source) {
  10028. // Geometry
  10029. if (source._geometry) {
  10030. source._geometry.applyToMesh(this);
  10031. }
  10032. // Deep copy
  10033. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10034. // Material
  10035. this.material = source.material;
  10036. if (!doNotCloneChildren) {
  10037. for (var index = 0; index < scene.meshes.length; index++) {
  10038. var mesh = scene.meshes[index];
  10039. if (mesh.parent === source) {
  10040. // doNotCloneChildren is always going to be False
  10041. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10042. }
  10043. }
  10044. }
  10045. for (index = 0; index < scene.particleSystems.length; index++) {
  10046. var system = scene.particleSystems[index];
  10047. if (system.emitter === source) {
  10048. system.clone(system.name, this);
  10049. }
  10050. }
  10051. this.computeWorldMatrix(true);
  10052. }
  10053. // Parent
  10054. if (parent !== null) {
  10055. this.parent = parent;
  10056. }
  10057. }
  10058. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10059. // Methods
  10060. get: function () {
  10061. return this._LODLevels.length > 0;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Mesh.prototype._sortLODLevels = function () {
  10067. this._LODLevels.sort(function (a, b) {
  10068. if (a.distance < b.distance) {
  10069. return 1;
  10070. }
  10071. if (a.distance > b.distance) {
  10072. return -1;
  10073. }
  10074. return 0;
  10075. });
  10076. };
  10077. /**
  10078. * Add a mesh as LOD level triggered at the given distance.
  10079. * @param {number} distance - the distance from the center of the object to show this level
  10080. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10081. * @return {BABYLON.Mesh} this mesh (for chaining)
  10082. */
  10083. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10084. if (mesh && mesh._masterMesh) {
  10085. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10086. return this;
  10087. }
  10088. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10089. this._LODLevels.push(level);
  10090. if (mesh) {
  10091. mesh._masterMesh = this;
  10092. }
  10093. this._sortLODLevels();
  10094. return this;
  10095. };
  10096. /**
  10097. * Remove a mesh from the LOD array
  10098. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10099. * @return {BABYLON.Mesh} this mesh (for chaining)
  10100. */
  10101. Mesh.prototype.removeLODLevel = function (mesh) {
  10102. for (var index = 0; index < this._LODLevels.length; index++) {
  10103. if (this._LODLevels[index].mesh === mesh) {
  10104. this._LODLevels.splice(index, 1);
  10105. if (mesh) {
  10106. mesh._masterMesh = null;
  10107. }
  10108. }
  10109. }
  10110. this._sortLODLevels();
  10111. return this;
  10112. };
  10113. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10114. if (!this._LODLevels || this._LODLevels.length === 0) {
  10115. return this;
  10116. }
  10117. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10118. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10119. return this;
  10120. }
  10121. for (var index = 0; index < this._LODLevels.length; index++) {
  10122. var level = this._LODLevels[index];
  10123. if (level.distance < distanceToCamera) {
  10124. if (level.mesh) {
  10125. level.mesh._preActivate();
  10126. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10127. }
  10128. return level.mesh;
  10129. }
  10130. }
  10131. return this;
  10132. };
  10133. Object.defineProperty(Mesh.prototype, "geometry", {
  10134. get: function () {
  10135. return this._geometry;
  10136. },
  10137. enumerable: true,
  10138. configurable: true
  10139. });
  10140. Mesh.prototype.getTotalVertices = function () {
  10141. if (!this._geometry) {
  10142. return 0;
  10143. }
  10144. return this._geometry.getTotalVertices();
  10145. };
  10146. Mesh.prototype.getVerticesData = function (kind) {
  10147. if (!this._geometry) {
  10148. return null;
  10149. }
  10150. return this._geometry.getVerticesData(kind);
  10151. };
  10152. Mesh.prototype.getVertexBuffer = function (kind) {
  10153. if (!this._geometry) {
  10154. return undefined;
  10155. }
  10156. return this._geometry.getVertexBuffer(kind);
  10157. };
  10158. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10159. if (!this._geometry) {
  10160. if (this._delayInfo) {
  10161. return this._delayInfo.indexOf(kind) !== -1;
  10162. }
  10163. return false;
  10164. }
  10165. return this._geometry.isVerticesDataPresent(kind);
  10166. };
  10167. Mesh.prototype.getVerticesDataKinds = function () {
  10168. if (!this._geometry) {
  10169. var result = [];
  10170. if (this._delayInfo) {
  10171. for (var kind in this._delayInfo) {
  10172. result.push(kind);
  10173. }
  10174. }
  10175. return result;
  10176. }
  10177. return this._geometry.getVerticesDataKinds();
  10178. };
  10179. Mesh.prototype.getTotalIndices = function () {
  10180. if (!this._geometry) {
  10181. return 0;
  10182. }
  10183. return this._geometry.getTotalIndices();
  10184. };
  10185. Mesh.prototype.getIndices = function () {
  10186. if (!this._geometry) {
  10187. return [];
  10188. }
  10189. return this._geometry.getIndices();
  10190. };
  10191. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10192. get: function () {
  10193. return this._masterMesh !== null && this._masterMesh !== undefined;
  10194. },
  10195. enumerable: true,
  10196. configurable: true
  10197. });
  10198. Mesh.prototype.isReady = function () {
  10199. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10200. return false;
  10201. }
  10202. return _super.prototype.isReady.call(this);
  10203. };
  10204. Mesh.prototype.isDisposed = function () {
  10205. return this._isDisposed;
  10206. };
  10207. // Methods
  10208. Mesh.prototype._preActivate = function () {
  10209. var sceneRenderId = this.getScene().getRenderId();
  10210. if (this._preActivateId == sceneRenderId) {
  10211. return;
  10212. }
  10213. this._preActivateId = sceneRenderId;
  10214. this._visibleInstances = null;
  10215. };
  10216. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10217. if (!this._visibleInstances) {
  10218. this._visibleInstances = {};
  10219. this._visibleInstances.defaultRenderId = renderId;
  10220. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10221. }
  10222. if (!this._visibleInstances[renderId]) {
  10223. this._visibleInstances[renderId] = new Array();
  10224. }
  10225. this._visibleInstances[renderId].push(instance);
  10226. };
  10227. Mesh.prototype.refreshBoundingInfo = function () {
  10228. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10229. if (data) {
  10230. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10231. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10232. }
  10233. if (this.subMeshes) {
  10234. for (var index = 0; index < this.subMeshes.length; index++) {
  10235. this.subMeshes[index].refreshBoundingInfo();
  10236. }
  10237. }
  10238. this._updateBoundingInfo();
  10239. };
  10240. Mesh.prototype._createGlobalSubMesh = function () {
  10241. var totalVertices = this.getTotalVertices();
  10242. if (!totalVertices || !this.getIndices()) {
  10243. return null;
  10244. }
  10245. this.releaseSubMeshes();
  10246. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10247. };
  10248. Mesh.prototype.subdivide = function (count) {
  10249. if (count < 1) {
  10250. return;
  10251. }
  10252. var totalIndices = this.getTotalIndices();
  10253. var subdivisionSize = (totalIndices / count) | 0;
  10254. var offset = 0;
  10255. while (subdivisionSize % 3 != 0) {
  10256. subdivisionSize++;
  10257. }
  10258. this.releaseSubMeshes();
  10259. for (var index = 0; index < count; index++) {
  10260. if (offset >= totalIndices) {
  10261. break;
  10262. }
  10263. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10264. offset += subdivisionSize;
  10265. }
  10266. this.synchronizeInstances();
  10267. };
  10268. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10269. if (kind instanceof Array) {
  10270. var temp = data;
  10271. data = kind;
  10272. kind = temp;
  10273. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10274. }
  10275. if (!this._geometry) {
  10276. var vertexData = new BABYLON.VertexData();
  10277. vertexData.set(data, kind);
  10278. var scene = this.getScene();
  10279. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10280. }
  10281. else {
  10282. this._geometry.setVerticesData(kind, data, updatable, stride);
  10283. }
  10284. };
  10285. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10286. if (!this._geometry) {
  10287. return;
  10288. }
  10289. if (!makeItUnique) {
  10290. this._geometry.updateVerticesData(kind, data, updateExtends);
  10291. }
  10292. else {
  10293. this.makeGeometryUnique();
  10294. this.updateVerticesData(kind, data, updateExtends, false);
  10295. }
  10296. };
  10297. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10298. if (!this._geometry) {
  10299. return;
  10300. }
  10301. if (!makeItUnique) {
  10302. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10303. }
  10304. else {
  10305. this.makeGeometryUnique();
  10306. this.updateVerticesDataDirectly(kind, data, offset, false);
  10307. }
  10308. };
  10309. Mesh.prototype.makeGeometryUnique = function () {
  10310. if (!this._geometry) {
  10311. return;
  10312. }
  10313. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10314. geometry.applyToMesh(this);
  10315. };
  10316. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10317. if (!this._geometry) {
  10318. var vertexData = new BABYLON.VertexData();
  10319. vertexData.indices = indices;
  10320. var scene = this.getScene();
  10321. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10322. }
  10323. else {
  10324. this._geometry.setIndices(indices, totalVertices);
  10325. }
  10326. };
  10327. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10328. var engine = this.getScene().getEngine();
  10329. // Wireframe
  10330. var indexToBind;
  10331. switch (fillMode) {
  10332. case BABYLON.Material.PointFillMode:
  10333. indexToBind = null;
  10334. break;
  10335. case BABYLON.Material.WireFrameFillMode:
  10336. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10337. break;
  10338. default:
  10339. case BABYLON.Material.TriangleFillMode:
  10340. indexToBind = this._geometry.getIndexBuffer();
  10341. break;
  10342. }
  10343. // VBOs
  10344. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10345. };
  10346. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10347. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10348. return;
  10349. }
  10350. var engine = this.getScene().getEngine();
  10351. switch (fillMode) {
  10352. case BABYLON.Material.PointFillMode:
  10353. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10354. break;
  10355. case BABYLON.Material.WireFrameFillMode:
  10356. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10357. break;
  10358. default:
  10359. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10360. }
  10361. };
  10362. Mesh.prototype.registerBeforeRender = function (func) {
  10363. this._onBeforeRenderCallbacks.push(func);
  10364. };
  10365. Mesh.prototype.unregisterBeforeRender = function (func) {
  10366. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10367. if (index > -1) {
  10368. this._onBeforeRenderCallbacks.splice(index, 1);
  10369. }
  10370. };
  10371. Mesh.prototype.registerAfterRender = function (func) {
  10372. this._onAfterRenderCallbacks.push(func);
  10373. };
  10374. Mesh.prototype.unregisterAfterRender = function (func) {
  10375. var index = this._onAfterRenderCallbacks.indexOf(func);
  10376. if (index > -1) {
  10377. this._onAfterRenderCallbacks.splice(index, 1);
  10378. }
  10379. };
  10380. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10381. var scene = this.getScene();
  10382. this._batchCache.mustReturn = false;
  10383. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10384. this._batchCache.visibleInstances[subMeshId] = null;
  10385. if (this._visibleInstances) {
  10386. var currentRenderId = scene.getRenderId();
  10387. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10388. var selfRenderId = this._renderId;
  10389. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10390. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10391. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10392. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10393. }
  10394. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10395. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10396. this._batchCache.mustReturn = true;
  10397. return this._batchCache;
  10398. }
  10399. if (currentRenderId !== selfRenderId) {
  10400. this._batchCache.renderSelf[subMeshId] = false;
  10401. }
  10402. }
  10403. this._renderIdForInstances[subMeshId] = currentRenderId;
  10404. }
  10405. return this._batchCache;
  10406. };
  10407. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10408. var visibleInstances = batch.visibleInstances[subMesh._id];
  10409. var matricesCount = visibleInstances.length + 1;
  10410. var bufferSize = matricesCount * 16 * 4;
  10411. while (this._instancesBufferSize < bufferSize) {
  10412. this._instancesBufferSize *= 2;
  10413. }
  10414. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10415. if (this._worldMatricesInstancesBuffer) {
  10416. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10417. }
  10418. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10419. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10420. }
  10421. var offset = 0;
  10422. var instancesCount = 0;
  10423. var world = this.getWorldMatrix();
  10424. if (batch.renderSelf[subMesh._id]) {
  10425. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10426. offset += 16;
  10427. instancesCount++;
  10428. }
  10429. if (visibleInstances) {
  10430. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10431. var instance = visibleInstances[instanceIndex];
  10432. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10433. offset += 16;
  10434. instancesCount++;
  10435. }
  10436. }
  10437. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10438. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10439. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10440. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10441. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10442. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10443. this._draw(subMesh, fillMode, instancesCount);
  10444. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10445. };
  10446. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10447. var scene = this.getScene();
  10448. var engine = scene.getEngine();
  10449. if (hardwareInstancedRendering) {
  10450. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10451. }
  10452. else {
  10453. if (batch.renderSelf[subMesh._id]) {
  10454. // Draw
  10455. if (onBeforeDraw) {
  10456. onBeforeDraw(false, this.getWorldMatrix());
  10457. }
  10458. this._draw(subMesh, fillMode);
  10459. }
  10460. if (batch.visibleInstances[subMesh._id]) {
  10461. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10462. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10463. // World
  10464. var world = instance.getWorldMatrix();
  10465. if (onBeforeDraw) {
  10466. onBeforeDraw(true, world);
  10467. }
  10468. // Draw
  10469. this._draw(subMesh, fillMode);
  10470. }
  10471. }
  10472. }
  10473. };
  10474. Mesh.prototype.render = function (subMesh) {
  10475. var scene = this.getScene();
  10476. // Managing instances
  10477. var batch = this._getInstancesRenderList(subMesh._id);
  10478. if (batch.mustReturn) {
  10479. return;
  10480. }
  10481. // Checking geometry state
  10482. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10483. return;
  10484. }
  10485. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10486. this._onBeforeRenderCallbacks[callbackIndex]();
  10487. }
  10488. var engine = scene.getEngine();
  10489. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10490. // Material
  10491. var effectiveMaterial = subMesh.getMaterial();
  10492. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10493. return;
  10494. }
  10495. // Outline - step 1
  10496. var savedDepthWrite = engine.getDepthWrite();
  10497. if (this.renderOutline) {
  10498. engine.setDepthWrite(false);
  10499. scene.getOutlineRenderer().render(subMesh, batch);
  10500. engine.setDepthWrite(savedDepthWrite);
  10501. }
  10502. effectiveMaterial._preBind();
  10503. var effect = effectiveMaterial.getEffect();
  10504. // Bind
  10505. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10506. this._bind(subMesh, effect, fillMode);
  10507. var world = this.getWorldMatrix();
  10508. effectiveMaterial.bind(world, this);
  10509. // Draw
  10510. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10511. if (isInstance) {
  10512. effectiveMaterial.bindOnlyWorldMatrix(world);
  10513. }
  10514. });
  10515. // Unbind
  10516. effectiveMaterial.unbind();
  10517. // Outline - step 2
  10518. if (this.renderOutline && savedDepthWrite) {
  10519. engine.setDepthWrite(true);
  10520. engine.setColorWrite(false);
  10521. scene.getOutlineRenderer().render(subMesh, batch);
  10522. engine.setColorWrite(true);
  10523. }
  10524. // Overlay
  10525. if (this.renderOverlay) {
  10526. var currentMode = engine.getAlphaMode();
  10527. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10528. scene.getOutlineRenderer().render(subMesh, batch, true);
  10529. engine.setAlphaMode(currentMode);
  10530. }
  10531. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10532. this._onAfterRenderCallbacks[callbackIndex]();
  10533. }
  10534. };
  10535. Mesh.prototype.getEmittedParticleSystems = function () {
  10536. var results = new Array();
  10537. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10538. var particleSystem = this.getScene().particleSystems[index];
  10539. if (particleSystem.emitter === this) {
  10540. results.push(particleSystem);
  10541. }
  10542. }
  10543. return results;
  10544. };
  10545. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10546. var results = new Array();
  10547. var descendants = this.getDescendants();
  10548. descendants.push(this);
  10549. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10550. var particleSystem = this.getScene().particleSystems[index];
  10551. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10552. results.push(particleSystem);
  10553. }
  10554. }
  10555. return results;
  10556. };
  10557. Mesh.prototype.getChildren = function () {
  10558. var results = [];
  10559. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10560. var mesh = this.getScene().meshes[index];
  10561. if (mesh.parent === this) {
  10562. results.push(mesh);
  10563. }
  10564. }
  10565. return results;
  10566. };
  10567. Mesh.prototype._checkDelayState = function () {
  10568. var _this = this;
  10569. var that = this;
  10570. var scene = this.getScene();
  10571. if (this._geometry) {
  10572. this._geometry.load(scene);
  10573. }
  10574. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10575. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10576. scene._addPendingData(that);
  10577. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10578. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10579. if (data instanceof ArrayBuffer) {
  10580. _this._delayLoadingFunction(data, _this);
  10581. }
  10582. else {
  10583. _this._delayLoadingFunction(JSON.parse(data), _this);
  10584. }
  10585. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10586. scene._removePendingData(_this);
  10587. }, function () {
  10588. }, scene.database, getBinaryData);
  10589. }
  10590. };
  10591. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10592. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10593. return false;
  10594. }
  10595. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10596. return false;
  10597. }
  10598. this._checkDelayState();
  10599. return true;
  10600. };
  10601. Mesh.prototype.setMaterialByID = function (id) {
  10602. var materials = this.getScene().materials;
  10603. for (var index = 0; index < materials.length; index++) {
  10604. if (materials[index].id === id) {
  10605. this.material = materials[index];
  10606. return;
  10607. }
  10608. }
  10609. // Multi
  10610. var multiMaterials = this.getScene().multiMaterials;
  10611. for (index = 0; index < multiMaterials.length; index++) {
  10612. if (multiMaterials[index].id === id) {
  10613. this.material = multiMaterials[index];
  10614. return;
  10615. }
  10616. }
  10617. };
  10618. Mesh.prototype.getAnimatables = function () {
  10619. var results = [];
  10620. if (this.material) {
  10621. results.push(this.material);
  10622. }
  10623. if (this.skeleton) {
  10624. results.push(this.skeleton);
  10625. }
  10626. return results;
  10627. };
  10628. // Geometry
  10629. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10630. // Position
  10631. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10632. return;
  10633. }
  10634. this._resetPointsArrayCache();
  10635. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10636. var temp = [];
  10637. for (var index = 0; index < data.length; index += 3) {
  10638. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10639. }
  10640. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10641. // Normals
  10642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10643. return;
  10644. }
  10645. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10646. for (index = 0; index < data.length; index += 3) {
  10647. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10648. }
  10649. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10650. };
  10651. // Cache
  10652. Mesh.prototype._resetPointsArrayCache = function () {
  10653. this._positions = null;
  10654. };
  10655. Mesh.prototype._generatePointsArray = function () {
  10656. if (this._positions)
  10657. return true;
  10658. this._positions = [];
  10659. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10660. if (!data) {
  10661. return false;
  10662. }
  10663. for (var index = 0; index < data.length; index += 3) {
  10664. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10665. }
  10666. return true;
  10667. };
  10668. // Clone
  10669. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10670. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10671. };
  10672. // Dispose
  10673. Mesh.prototype.dispose = function (doNotRecurse) {
  10674. if (this._geometry) {
  10675. this._geometry.releaseForMesh(this, true);
  10676. }
  10677. // Instances
  10678. if (this._worldMatricesInstancesBuffer) {
  10679. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10680. this._worldMatricesInstancesBuffer = null;
  10681. }
  10682. while (this.instances.length) {
  10683. this.instances[0].dispose();
  10684. }
  10685. _super.prototype.dispose.call(this, doNotRecurse);
  10686. };
  10687. // Geometric tools
  10688. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10689. var _this = this;
  10690. var scene = this.getScene();
  10691. var onload = function (img) {
  10692. // Getting height map data
  10693. var canvas = document.createElement("canvas");
  10694. var context = canvas.getContext("2d");
  10695. var heightMapWidth = img.width;
  10696. var heightMapHeight = img.height;
  10697. canvas.width = heightMapWidth;
  10698. canvas.height = heightMapHeight;
  10699. context.drawImage(img, 0, 0);
  10700. // Create VertexData from map data
  10701. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  10702. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10703. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10704. //execute success callback, if set
  10705. if (onSuccess) {
  10706. onSuccess(_this);
  10707. }
  10708. };
  10709. BABYLON.Tools.LoadImage(url, onload, function () {
  10710. }, scene.database);
  10711. };
  10712. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10714. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10715. return;
  10716. }
  10717. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10718. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10719. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10720. var position = BABYLON.Vector3.Zero();
  10721. var normal = BABYLON.Vector3.Zero();
  10722. var uv = BABYLON.Vector2.Zero();
  10723. for (var index = 0; index < positions.length; index += 3) {
  10724. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10725. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10726. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10727. // Compute height
  10728. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10729. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10730. var pos = (u + v * heightMapWidth) * 4;
  10731. var r = buffer[pos] / 255.0;
  10732. var g = buffer[pos + 1] / 255.0;
  10733. var b = buffer[pos + 2] / 255.0;
  10734. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10735. normal.normalize();
  10736. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10737. position = position.add(normal);
  10738. position.toArray(positions, index);
  10739. }
  10740. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10741. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10742. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10743. };
  10744. Mesh.prototype.convertToFlatShadedMesh = function () {
  10745. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10746. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10747. var kinds = this.getVerticesDataKinds();
  10748. var vbs = [];
  10749. var data = [];
  10750. var newdata = [];
  10751. var updatableNormals = false;
  10752. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10753. var kind = kinds[kindIndex];
  10754. var vertexBuffer = this.getVertexBuffer(kind);
  10755. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10756. updatableNormals = vertexBuffer.isUpdatable();
  10757. kinds.splice(kindIndex, 1);
  10758. kindIndex--;
  10759. continue;
  10760. }
  10761. vbs[kind] = vertexBuffer;
  10762. data[kind] = vbs[kind].getData();
  10763. newdata[kind] = [];
  10764. }
  10765. // Save previous submeshes
  10766. var previousSubmeshes = this.subMeshes.slice(0);
  10767. var indices = this.getIndices();
  10768. var totalIndices = this.getTotalIndices();
  10769. for (var index = 0; index < totalIndices; index++) {
  10770. var vertexIndex = indices[index];
  10771. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10772. kind = kinds[kindIndex];
  10773. var stride = vbs[kind].getStrideSize();
  10774. for (var offset = 0; offset < stride; offset++) {
  10775. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10776. }
  10777. }
  10778. }
  10779. // Updating faces & normal
  10780. var normals = [];
  10781. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10782. for (index = 0; index < totalIndices; index += 3) {
  10783. indices[index] = index;
  10784. indices[index + 1] = index + 1;
  10785. indices[index + 2] = index + 2;
  10786. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10787. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10788. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10789. var p1p2 = p1.subtract(p2);
  10790. var p3p2 = p3.subtract(p2);
  10791. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10792. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10793. normals.push(normal.x);
  10794. normals.push(normal.y);
  10795. normals.push(normal.z);
  10796. }
  10797. }
  10798. this.setIndices(indices);
  10799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10801. kind = kinds[kindIndex];
  10802. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10803. }
  10804. // Updating submeshes
  10805. this.releaseSubMeshes();
  10806. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10807. var previousOne = previousSubmeshes[submeshIndex];
  10808. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10809. }
  10810. this.synchronizeInstances();
  10811. };
  10812. // Instances
  10813. Mesh.prototype.createInstance = function (name) {
  10814. return new BABYLON.InstancedMesh(name, this);
  10815. };
  10816. Mesh.prototype.synchronizeInstances = function () {
  10817. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10818. var instance = this.instances[instanceIndex];
  10819. instance._syncSubMeshes();
  10820. }
  10821. };
  10822. /**
  10823. * Simplify the mesh according to the given array of settings.
  10824. * Function will return immediately and will simplify async.
  10825. * @param settings a collection of simplification settings.
  10826. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10827. * @param type the type of simplification to run.
  10828. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10829. */
  10830. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10831. var _this = this;
  10832. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10833. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10834. var getSimplifier = function () {
  10835. switch (type) {
  10836. case 0 /* QUADRATIC */:
  10837. default:
  10838. return new BABYLON.QuadraticErrorSimplification(_this);
  10839. }
  10840. };
  10841. if (parallelProcessing) {
  10842. //parallel simplifier
  10843. settings.forEach(function (setting) {
  10844. var simplifier = getSimplifier();
  10845. simplifier.simplify(setting, function (newMesh) {
  10846. _this.addLODLevel(setting.distance, newMesh);
  10847. //check if it is the last
  10848. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10849. //all done, run the success callback.
  10850. successCallback();
  10851. }
  10852. });
  10853. });
  10854. }
  10855. else {
  10856. //single simplifier.
  10857. var simplifier = getSimplifier();
  10858. var runDecimation = function (setting, callback) {
  10859. simplifier.simplify(setting, function (newMesh) {
  10860. _this.addLODLevel(setting.distance, newMesh);
  10861. //run the next quality level
  10862. callback();
  10863. });
  10864. };
  10865. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10866. runDecimation(settings[loop.index], function () {
  10867. loop.executeNext();
  10868. });
  10869. }, function () {
  10870. //execution ended, run the success callback.
  10871. if (successCallback) {
  10872. successCallback();
  10873. }
  10874. });
  10875. }
  10876. };
  10877. // Statics
  10878. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable) {
  10879. var ribbon = new Mesh(name, scene);
  10880. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset);
  10881. vertexData.applyToMesh(ribbon, updatable);
  10882. return ribbon;
  10883. };
  10884. Mesh.CreateBox = function (name, size, scene, updatable) {
  10885. var box = new Mesh(name, scene);
  10886. var vertexData = BABYLON.VertexData.CreateBox(size);
  10887. vertexData.applyToMesh(box, updatable);
  10888. return box;
  10889. };
  10890. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10891. var sphere = new Mesh(name, scene);
  10892. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10893. vertexData.applyToMesh(sphere, updatable);
  10894. return sphere;
  10895. };
  10896. // Cylinder and cone (Code inspired by SharpDX.org)
  10897. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10898. // subdivisions is a new parameter, we need to support old signature
  10899. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10900. if (scene !== undefined) {
  10901. updatable = scene;
  10902. }
  10903. scene = subdivisions;
  10904. subdivisions = 1;
  10905. }
  10906. var cylinder = new Mesh(name, scene);
  10907. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10908. vertexData.applyToMesh(cylinder, updatable);
  10909. return cylinder;
  10910. };
  10911. // Torus (Code from SharpDX.org)
  10912. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10913. var torus = new Mesh(name, scene);
  10914. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10915. vertexData.applyToMesh(torus, updatable);
  10916. return torus;
  10917. };
  10918. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10919. var torusKnot = new Mesh(name, scene);
  10920. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10921. vertexData.applyToMesh(torusKnot, updatable);
  10922. return torusKnot;
  10923. };
  10924. // Lines
  10925. Mesh.CreateLines = function (name, points, scene, updatable) {
  10926. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10927. var vertexData = BABYLON.VertexData.CreateLines(points);
  10928. vertexData.applyToMesh(lines, updatable);
  10929. return lines;
  10930. };
  10931. // Plane & ground
  10932. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10933. var plane = new Mesh(name, scene);
  10934. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10935. vertexData.applyToMesh(plane, updatable);
  10936. return plane;
  10937. };
  10938. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10939. var ground = new BABYLON.GroundMesh(name, scene);
  10940. ground._setReady(false);
  10941. ground._subdivisions = subdivisions;
  10942. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10943. vertexData.applyToMesh(ground, updatable);
  10944. ground._setReady(true);
  10945. return ground;
  10946. };
  10947. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10948. var tiledGround = new Mesh(name, scene);
  10949. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10950. vertexData.applyToMesh(tiledGround, updatable);
  10951. return tiledGround;
  10952. };
  10953. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10954. var ground = new BABYLON.GroundMesh(name, scene);
  10955. ground._subdivisions = subdivisions;
  10956. ground._setReady(false);
  10957. var onload = function (img) {
  10958. // Getting height map data
  10959. var canvas = document.createElement("canvas");
  10960. var context = canvas.getContext("2d");
  10961. var heightMapWidth = img.width;
  10962. var heightMapHeight = img.height;
  10963. canvas.width = heightMapWidth;
  10964. canvas.height = heightMapHeight;
  10965. context.drawImage(img, 0, 0);
  10966. // Create VertexData from map data
  10967. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  10968. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10969. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10970. vertexData.applyToMesh(ground, updatable);
  10971. ground._setReady(true);
  10972. //execute ready callback, if set
  10973. if (onReady) {
  10974. onReady(ground);
  10975. }
  10976. };
  10977. BABYLON.Tools.LoadImage(url, onload, function () {
  10978. }, scene.database);
  10979. return ground;
  10980. };
  10981. // Tools
  10982. Mesh.MinMax = function (meshes) {
  10983. var minVector = null;
  10984. var maxVector = null;
  10985. for (var i in meshes) {
  10986. var mesh = meshes[i];
  10987. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10988. if (!minVector) {
  10989. minVector = boundingBox.minimumWorld;
  10990. maxVector = boundingBox.maximumWorld;
  10991. continue;
  10992. }
  10993. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10994. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10995. }
  10996. return {
  10997. min: minVector,
  10998. max: maxVector
  10999. };
  11000. };
  11001. Mesh.Center = function (meshesOrMinMaxVector) {
  11002. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11003. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11004. };
  11005. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11006. if (disposeSource === void 0) { disposeSource = true; }
  11007. var source = meshes[0];
  11008. var material = source.material;
  11009. var scene = source.getScene();
  11010. if (!allow32BitsIndices) {
  11011. var totalVertices = 0;
  11012. for (var index = 0; index < meshes.length; index++) {
  11013. totalVertices += meshes[index].getTotalVertices();
  11014. if (totalVertices > 65536) {
  11015. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11016. return null;
  11017. }
  11018. }
  11019. }
  11020. // Merge
  11021. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11022. vertexData.transform(source.getWorldMatrix());
  11023. for (index = 1; index < meshes.length; index++) {
  11024. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11025. otherVertexData.transform(meshes[index].getWorldMatrix());
  11026. vertexData.merge(otherVertexData);
  11027. }
  11028. var newMesh = new Mesh(source.name + "_merged", scene);
  11029. vertexData.applyToMesh(newMesh);
  11030. // Setting properties
  11031. newMesh.material = material;
  11032. newMesh.checkCollisions = source.checkCollisions;
  11033. // Cleaning
  11034. if (disposeSource) {
  11035. for (index = 0; index < meshes.length; index++) {
  11036. meshes[index].dispose();
  11037. }
  11038. }
  11039. return newMesh;
  11040. };
  11041. return Mesh;
  11042. })(BABYLON.AbstractMesh);
  11043. BABYLON.Mesh = Mesh;
  11044. })(BABYLON || (BABYLON = {}));
  11045. //# sourceMappingURL=babylon.mesh.js.map
  11046. var BABYLON;
  11047. (function (BABYLON) {
  11048. var GroundMesh = (function (_super) {
  11049. __extends(GroundMesh, _super);
  11050. function GroundMesh(name, scene) {
  11051. _super.call(this, name, scene);
  11052. this.generateOctree = false;
  11053. this._worldInverse = new BABYLON.Matrix();
  11054. }
  11055. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11056. get: function () {
  11057. return this._subdivisions;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. GroundMesh.prototype.optimize = function (chunksCount) {
  11063. this.subdivide(this._subdivisions);
  11064. this.createOrUpdateSubmeshesOctree(32);
  11065. };
  11066. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11067. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11068. this.getWorldMatrix().invertToRef(this._worldInverse);
  11069. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11070. var pickInfo = this.intersects(ray);
  11071. if (pickInfo.hit) {
  11072. return pickInfo.pickedPoint.y;
  11073. }
  11074. return 0;
  11075. };
  11076. return GroundMesh;
  11077. })(BABYLON.Mesh);
  11078. BABYLON.GroundMesh = GroundMesh;
  11079. })(BABYLON || (BABYLON = {}));
  11080. //# sourceMappingURL=babylon.groundMesh.js.map
  11081. var BABYLON;
  11082. (function (BABYLON) {
  11083. /**
  11084. * Creates an instance based on a source mesh.
  11085. */
  11086. var InstancedMesh = (function (_super) {
  11087. __extends(InstancedMesh, _super);
  11088. function InstancedMesh(name, source) {
  11089. _super.call(this, name, source.getScene());
  11090. source.instances.push(this);
  11091. this._sourceMesh = source;
  11092. this.position.copyFrom(source.position);
  11093. this.rotation.copyFrom(source.rotation);
  11094. this.scaling.copyFrom(source.scaling);
  11095. if (source.rotationQuaternion) {
  11096. this.rotationQuaternion = source.rotationQuaternion.clone();
  11097. }
  11098. this.infiniteDistance = source.infiniteDistance;
  11099. this.setPivotMatrix(source.getPivotMatrix());
  11100. this.refreshBoundingInfo();
  11101. this._syncSubMeshes();
  11102. }
  11103. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11104. // Methods
  11105. get: function () {
  11106. return this._sourceMesh.receiveShadows;
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. Object.defineProperty(InstancedMesh.prototype, "material", {
  11112. get: function () {
  11113. return this._sourceMesh.material;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11119. get: function () {
  11120. return this._sourceMesh.visibility;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11126. get: function () {
  11127. return this._sourceMesh.skeleton;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. InstancedMesh.prototype.getTotalVertices = function () {
  11133. return this._sourceMesh.getTotalVertices();
  11134. };
  11135. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11136. get: function () {
  11137. return this._sourceMesh;
  11138. },
  11139. enumerable: true,
  11140. configurable: true
  11141. });
  11142. InstancedMesh.prototype.getVerticesData = function (kind) {
  11143. return this._sourceMesh.getVerticesData(kind);
  11144. };
  11145. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11146. return this._sourceMesh.isVerticesDataPresent(kind);
  11147. };
  11148. InstancedMesh.prototype.getIndices = function () {
  11149. return this._sourceMesh.getIndices();
  11150. };
  11151. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11152. get: function () {
  11153. return this._sourceMesh._positions;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11159. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11160. if (data) {
  11161. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11162. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11163. }
  11164. this._updateBoundingInfo();
  11165. };
  11166. InstancedMesh.prototype._preActivate = function () {
  11167. if (this._currentLOD) {
  11168. this._currentLOD._preActivate();
  11169. }
  11170. };
  11171. InstancedMesh.prototype._activate = function (renderId) {
  11172. if (this._currentLOD) {
  11173. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11174. }
  11175. };
  11176. InstancedMesh.prototype.getLOD = function (camera) {
  11177. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11178. if (this._currentLOD === this.sourceMesh) {
  11179. return this;
  11180. }
  11181. return this._currentLOD;
  11182. };
  11183. InstancedMesh.prototype._syncSubMeshes = function () {
  11184. this.releaseSubMeshes();
  11185. if (this._sourceMesh.subMeshes) {
  11186. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11187. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11188. }
  11189. }
  11190. };
  11191. InstancedMesh.prototype._generatePointsArray = function () {
  11192. return this._sourceMesh._generatePointsArray();
  11193. };
  11194. // Clone
  11195. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11196. var result = this._sourceMesh.createInstance(name);
  11197. // Deep copy
  11198. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11199. // Bounding info
  11200. this.refreshBoundingInfo();
  11201. // Parent
  11202. if (newParent) {
  11203. result.parent = newParent;
  11204. }
  11205. if (!doNotCloneChildren) {
  11206. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11207. var mesh = this.getScene().meshes[index];
  11208. if (mesh.parent === this) {
  11209. mesh.clone(mesh.name, result);
  11210. }
  11211. }
  11212. }
  11213. result.computeWorldMatrix(true);
  11214. return result;
  11215. };
  11216. // Dispoe
  11217. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11218. // Remove from mesh
  11219. var index = this._sourceMesh.instances.indexOf(this);
  11220. this._sourceMesh.instances.splice(index, 1);
  11221. _super.prototype.dispose.call(this, doNotRecurse);
  11222. };
  11223. return InstancedMesh;
  11224. })(BABYLON.AbstractMesh);
  11225. BABYLON.InstancedMesh = InstancedMesh;
  11226. })(BABYLON || (BABYLON = {}));
  11227. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11228. (function (BABYLON) {
  11229. var SubMesh = (function () {
  11230. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11231. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11232. this.materialIndex = materialIndex;
  11233. this.verticesStart = verticesStart;
  11234. this.verticesCount = verticesCount;
  11235. this.indexStart = indexStart;
  11236. this.indexCount = indexCount;
  11237. this._renderId = 0;
  11238. this._mesh = mesh;
  11239. this._renderingMesh = renderingMesh || mesh;
  11240. mesh.subMeshes.push(this);
  11241. this._id = mesh.subMeshes.length - 1;
  11242. if (createBoundingBox) {
  11243. this.refreshBoundingInfo();
  11244. }
  11245. }
  11246. SubMesh.prototype.getBoundingInfo = function () {
  11247. return this._boundingInfo;
  11248. };
  11249. SubMesh.prototype.getMesh = function () {
  11250. return this._mesh;
  11251. };
  11252. SubMesh.prototype.getRenderingMesh = function () {
  11253. return this._renderingMesh;
  11254. };
  11255. SubMesh.prototype.getMaterial = function () {
  11256. var rootMaterial = this._renderingMesh.material;
  11257. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11258. var multiMaterial = rootMaterial;
  11259. return multiMaterial.getSubMaterial(this.materialIndex);
  11260. }
  11261. if (!rootMaterial) {
  11262. return this._mesh.getScene().defaultMaterial;
  11263. }
  11264. return rootMaterial;
  11265. };
  11266. // Methods
  11267. SubMesh.prototype.refreshBoundingInfo = function () {
  11268. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11269. if (!data) {
  11270. this._boundingInfo = this._mesh._boundingInfo;
  11271. return;
  11272. }
  11273. var indices = this._renderingMesh.getIndices();
  11274. var extend;
  11275. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11276. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11277. }
  11278. else {
  11279. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11280. }
  11281. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11282. };
  11283. SubMesh.prototype._checkCollision = function (collider) {
  11284. return this._boundingInfo._checkCollision(collider);
  11285. };
  11286. SubMesh.prototype.updateBoundingInfo = function (world) {
  11287. if (!this._boundingInfo) {
  11288. this.refreshBoundingInfo();
  11289. }
  11290. this._boundingInfo._update(world);
  11291. };
  11292. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11293. return this._boundingInfo.isInFrustum(frustumPlanes);
  11294. };
  11295. SubMesh.prototype.render = function () {
  11296. this._renderingMesh.render(this);
  11297. };
  11298. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11299. if (!this._linesIndexBuffer) {
  11300. var linesIndices = [];
  11301. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11302. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11303. }
  11304. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11305. this.linesIndexCount = linesIndices.length;
  11306. }
  11307. return this._linesIndexBuffer;
  11308. };
  11309. SubMesh.prototype.canIntersects = function (ray) {
  11310. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11311. };
  11312. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11313. var intersectInfo = null;
  11314. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11315. var p0 = positions[indices[index]];
  11316. var p1 = positions[indices[index + 1]];
  11317. var p2 = positions[indices[index + 2]];
  11318. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11319. if (currentIntersectInfo) {
  11320. if (currentIntersectInfo.distance < 0) {
  11321. continue;
  11322. }
  11323. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11324. intersectInfo = currentIntersectInfo;
  11325. intersectInfo.faceId = index / 3;
  11326. if (fastCheck) {
  11327. break;
  11328. }
  11329. }
  11330. }
  11331. }
  11332. return intersectInfo;
  11333. };
  11334. // Clone
  11335. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11336. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11337. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11338. return result;
  11339. };
  11340. // Dispose
  11341. SubMesh.prototype.dispose = function () {
  11342. if (this._linesIndexBuffer) {
  11343. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11344. this._linesIndexBuffer = null;
  11345. }
  11346. // Remove from mesh
  11347. var index = this._mesh.subMeshes.indexOf(this);
  11348. this._mesh.subMeshes.splice(index, 1);
  11349. };
  11350. // Statics
  11351. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11352. var minVertexIndex = Number.MAX_VALUE;
  11353. var maxVertexIndex = -Number.MAX_VALUE;
  11354. renderingMesh = renderingMesh || mesh;
  11355. var indices = renderingMesh.getIndices();
  11356. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11357. var vertexIndex = indices[index];
  11358. if (vertexIndex < minVertexIndex)
  11359. minVertexIndex = vertexIndex;
  11360. if (vertexIndex > maxVertexIndex)
  11361. maxVertexIndex = vertexIndex;
  11362. }
  11363. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11364. };
  11365. return SubMesh;
  11366. })();
  11367. BABYLON.SubMesh = SubMesh;
  11368. })(BABYLON || (BABYLON = {}));
  11369. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11370. (function (BABYLON) {
  11371. var BaseTexture = (function () {
  11372. function BaseTexture(scene) {
  11373. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11374. this.hasAlpha = false;
  11375. this.getAlphaFromRGB = false;
  11376. this.level = 1;
  11377. this.isCube = false;
  11378. this.isRenderTarget = false;
  11379. this.animations = new Array();
  11380. this.coordinatesIndex = 0;
  11381. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11382. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11383. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11384. this.anisotropicFilteringLevel = 4;
  11385. this._scene = scene;
  11386. this._scene.textures.push(this);
  11387. }
  11388. BaseTexture.prototype.getScene = function () {
  11389. return this._scene;
  11390. };
  11391. BaseTexture.prototype.getTextureMatrix = function () {
  11392. return null;
  11393. };
  11394. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11395. return null;
  11396. };
  11397. BaseTexture.prototype.getInternalTexture = function () {
  11398. return this._texture;
  11399. };
  11400. BaseTexture.prototype.isReady = function () {
  11401. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11402. return true;
  11403. }
  11404. if (this._texture) {
  11405. return this._texture.isReady;
  11406. }
  11407. return false;
  11408. };
  11409. BaseTexture.prototype.getSize = function () {
  11410. if (this._texture._width) {
  11411. return { width: this._texture._width, height: this._texture._height };
  11412. }
  11413. if (this._texture._size) {
  11414. return { width: this._texture._size, height: this._texture._size };
  11415. }
  11416. return { width: 0, height: 0 };
  11417. };
  11418. BaseTexture.prototype.getBaseSize = function () {
  11419. if (!this.isReady())
  11420. return { width: 0, height: 0 };
  11421. if (this._texture._size) {
  11422. return { width: this._texture._size, height: this._texture._size };
  11423. }
  11424. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11425. };
  11426. BaseTexture.prototype.scale = function (ratio) {
  11427. };
  11428. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11429. get: function () {
  11430. return false;
  11431. },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11436. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11437. for (var index = 0; index < texturesCache.length; index++) {
  11438. var texturesCacheEntry = texturesCache[index];
  11439. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11440. texturesCache.splice(index, 1);
  11441. return;
  11442. }
  11443. }
  11444. };
  11445. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11446. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11447. for (var index = 0; index < texturesCache.length; index++) {
  11448. var texturesCacheEntry = texturesCache[index];
  11449. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11450. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11451. texturesCacheEntry.references++;
  11452. return texturesCacheEntry;
  11453. }
  11454. }
  11455. }
  11456. return null;
  11457. };
  11458. BaseTexture.prototype.delayLoad = function () {
  11459. };
  11460. BaseTexture.prototype.releaseInternalTexture = function () {
  11461. if (!this._texture) {
  11462. return;
  11463. }
  11464. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11465. this._texture.references--;
  11466. // Final reference ?
  11467. if (this._texture.references === 0) {
  11468. var index = texturesCache.indexOf(this._texture);
  11469. texturesCache.splice(index, 1);
  11470. this._scene.getEngine()._releaseTexture(this._texture);
  11471. delete this._texture;
  11472. }
  11473. };
  11474. BaseTexture.prototype.clone = function () {
  11475. return null;
  11476. };
  11477. BaseTexture.prototype.dispose = function () {
  11478. // Remove from scene
  11479. var index = this._scene.textures.indexOf(this);
  11480. if (index >= 0) {
  11481. this._scene.textures.splice(index, 1);
  11482. }
  11483. if (this._texture === undefined) {
  11484. return;
  11485. }
  11486. this.releaseInternalTexture();
  11487. // Callback
  11488. if (this.onDispose) {
  11489. this.onDispose();
  11490. }
  11491. };
  11492. return BaseTexture;
  11493. })();
  11494. BABYLON.BaseTexture = BaseTexture;
  11495. })(BABYLON || (BABYLON = {}));
  11496. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11497. (function (BABYLON) {
  11498. var RenderingGroup = (function () {
  11499. function RenderingGroup(index, scene) {
  11500. this.index = index;
  11501. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11502. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11503. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11504. this._scene = scene;
  11505. }
  11506. RenderingGroup.prototype.render = function (customRenderFunction) {
  11507. if (customRenderFunction) {
  11508. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11509. return true;
  11510. }
  11511. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11512. return false;
  11513. }
  11514. var engine = this._scene.getEngine();
  11515. // Opaque
  11516. var subIndex;
  11517. var submesh;
  11518. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11519. submesh = this._opaqueSubMeshes.data[subIndex];
  11520. submesh.render();
  11521. }
  11522. // Alpha test
  11523. engine.setAlphaTesting(true);
  11524. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11525. submesh = this._alphaTestSubMeshes.data[subIndex];
  11526. submesh.render();
  11527. }
  11528. engine.setAlphaTesting(false);
  11529. // Transparent
  11530. if (this._transparentSubMeshes.length) {
  11531. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11532. submesh = this._transparentSubMeshes.data[subIndex];
  11533. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11534. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11535. }
  11536. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11537. sortedArray.sort(function (a, b) {
  11538. // Alpha index first
  11539. if (a._alphaIndex > b._alphaIndex) {
  11540. return 1;
  11541. }
  11542. if (a._alphaIndex < b._alphaIndex) {
  11543. return -1;
  11544. }
  11545. // Then distance to camera
  11546. if (a._distanceToCamera < b._distanceToCamera) {
  11547. return 1;
  11548. }
  11549. if (a._distanceToCamera > b._distanceToCamera) {
  11550. return -1;
  11551. }
  11552. return 0;
  11553. });
  11554. // Rendering
  11555. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11556. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11557. submesh = sortedArray[subIndex];
  11558. submesh.render();
  11559. }
  11560. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11561. }
  11562. return true;
  11563. };
  11564. RenderingGroup.prototype.prepare = function () {
  11565. this._opaqueSubMeshes.reset();
  11566. this._transparentSubMeshes.reset();
  11567. this._alphaTestSubMeshes.reset();
  11568. };
  11569. RenderingGroup.prototype.dispatch = function (subMesh) {
  11570. var material = subMesh.getMaterial();
  11571. var mesh = subMesh.getMesh();
  11572. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11573. this._transparentSubMeshes.push(subMesh);
  11574. }
  11575. else if (material.needAlphaTesting()) {
  11576. this._alphaTestSubMeshes.push(subMesh);
  11577. }
  11578. else {
  11579. this._opaqueSubMeshes.push(subMesh); // Opaque
  11580. }
  11581. };
  11582. return RenderingGroup;
  11583. })();
  11584. BABYLON.RenderingGroup = RenderingGroup;
  11585. })(BABYLON || (BABYLON = {}));
  11586. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11587. (function (BABYLON) {
  11588. var RenderingManager = (function () {
  11589. function RenderingManager(scene) {
  11590. this._renderingGroups = new Array();
  11591. this._scene = scene;
  11592. }
  11593. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11594. if (this._scene._activeParticleSystems.length === 0) {
  11595. return;
  11596. }
  11597. // Particles
  11598. var beforeParticlesDate = BABYLON.Tools.Now;
  11599. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11600. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11601. if (particleSystem.renderingGroupId !== index) {
  11602. continue;
  11603. }
  11604. this._clearDepthBuffer();
  11605. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11606. this._scene._activeParticles += particleSystem.render();
  11607. }
  11608. }
  11609. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11610. };
  11611. RenderingManager.prototype._renderSprites = function (index) {
  11612. if (this._scene.spriteManagers.length === 0) {
  11613. return;
  11614. }
  11615. // Sprites
  11616. var beforeSpritessDate = BABYLON.Tools.Now;
  11617. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11618. var spriteManager = this._scene.spriteManagers[id];
  11619. if (spriteManager.renderingGroupId === index) {
  11620. this._clearDepthBuffer();
  11621. spriteManager.render();
  11622. }
  11623. }
  11624. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11625. };
  11626. RenderingManager.prototype._clearDepthBuffer = function () {
  11627. if (this._depthBufferAlreadyCleaned) {
  11628. return;
  11629. }
  11630. this._scene.getEngine().clear(0, false, true);
  11631. this._depthBufferAlreadyCleaned = true;
  11632. };
  11633. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11634. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11635. this._depthBufferAlreadyCleaned = false;
  11636. var renderingGroup = this._renderingGroups[index];
  11637. var needToStepBack = false;
  11638. if (renderingGroup) {
  11639. this._clearDepthBuffer();
  11640. if (!renderingGroup.render(customRenderFunction)) {
  11641. this._renderingGroups.splice(index, 1);
  11642. needToStepBack = true;
  11643. }
  11644. }
  11645. if (renderSprites) {
  11646. this._renderSprites(index);
  11647. }
  11648. if (renderParticles) {
  11649. this._renderParticles(index, activeMeshes);
  11650. }
  11651. if (needToStepBack) {
  11652. index--;
  11653. }
  11654. }
  11655. };
  11656. RenderingManager.prototype.reset = function () {
  11657. for (var index in this._renderingGroups) {
  11658. var renderingGroup = this._renderingGroups[index];
  11659. renderingGroup.prepare();
  11660. }
  11661. };
  11662. RenderingManager.prototype.dispatch = function (subMesh) {
  11663. var mesh = subMesh.getMesh();
  11664. var renderingGroupId = mesh.renderingGroupId || 0;
  11665. if (!this._renderingGroups[renderingGroupId]) {
  11666. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11667. }
  11668. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11669. };
  11670. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11671. return RenderingManager;
  11672. })();
  11673. BABYLON.RenderingManager = RenderingManager;
  11674. })(BABYLON || (BABYLON = {}));
  11675. //# sourceMappingURL=babylon.renderingManager.js.map
  11676. var BABYLON;
  11677. (function (BABYLON) {
  11678. var Texture = (function (_super) {
  11679. __extends(Texture, _super);
  11680. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11681. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11682. if (onLoad === void 0) { onLoad = null; }
  11683. if (onError === void 0) { onError = null; }
  11684. if (buffer === void 0) { buffer = null; }
  11685. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11686. _super.call(this, scene);
  11687. this.uOffset = 0;
  11688. this.vOffset = 0;
  11689. this.uScale = 1.0;
  11690. this.vScale = 1.0;
  11691. this.uAng = 0;
  11692. this.vAng = 0;
  11693. this.wAng = 0;
  11694. this.name = url;
  11695. this.url = url;
  11696. this._noMipmap = noMipmap;
  11697. this._invertY = invertY;
  11698. this._samplingMode = samplingMode;
  11699. this._buffer = buffer;
  11700. this._deleteBuffer = deleteBuffer;
  11701. if (!url) {
  11702. return;
  11703. }
  11704. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11705. if (!this._texture) {
  11706. if (!scene.useDelayedTextureLoading) {
  11707. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11708. if (deleteBuffer) {
  11709. delete this._buffer;
  11710. }
  11711. }
  11712. else {
  11713. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11714. }
  11715. }
  11716. }
  11717. Texture.prototype.delayLoad = function () {
  11718. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11719. return;
  11720. }
  11721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11722. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11723. if (!this._texture) {
  11724. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11725. if (this._deleteBuffer) {
  11726. delete this._buffer;
  11727. }
  11728. }
  11729. };
  11730. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11731. x -= this.uOffset + 0.5;
  11732. y -= this.vOffset + 0.5;
  11733. z -= 0.5;
  11734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11735. t.x *= this.uScale;
  11736. t.y *= this.vScale;
  11737. t.x += 0.5;
  11738. t.y += 0.5;
  11739. t.z += 0.5;
  11740. };
  11741. Texture.prototype.getTextureMatrix = function () {
  11742. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  11743. return this._cachedTextureMatrix;
  11744. }
  11745. this._cachedUOffset = this.uOffset;
  11746. this._cachedVOffset = this.vOffset;
  11747. this._cachedUScale = this.uScale;
  11748. this._cachedVScale = this.vScale;
  11749. this._cachedUAng = this.uAng;
  11750. this._cachedVAng = this.vAng;
  11751. this._cachedWAng = this.wAng;
  11752. if (!this._cachedTextureMatrix) {
  11753. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11754. this._rowGenerationMatrix = new BABYLON.Matrix();
  11755. this._t0 = BABYLON.Vector3.Zero();
  11756. this._t1 = BABYLON.Vector3.Zero();
  11757. this._t2 = BABYLON.Vector3.Zero();
  11758. }
  11759. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11760. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11761. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11762. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11763. this._t1.subtractInPlace(this._t0);
  11764. this._t2.subtractInPlace(this._t0);
  11765. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11766. this._cachedTextureMatrix.m[0] = this._t1.x;
  11767. this._cachedTextureMatrix.m[1] = this._t1.y;
  11768. this._cachedTextureMatrix.m[2] = this._t1.z;
  11769. this._cachedTextureMatrix.m[4] = this._t2.x;
  11770. this._cachedTextureMatrix.m[5] = this._t2.y;
  11771. this._cachedTextureMatrix.m[6] = this._t2.z;
  11772. this._cachedTextureMatrix.m[8] = this._t0.x;
  11773. this._cachedTextureMatrix.m[9] = this._t0.y;
  11774. this._cachedTextureMatrix.m[10] = this._t0.z;
  11775. return this._cachedTextureMatrix;
  11776. };
  11777. Texture.prototype.getReflectionTextureMatrix = function () {
  11778. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11779. return this._cachedTextureMatrix;
  11780. }
  11781. if (!this._cachedTextureMatrix) {
  11782. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11783. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11784. }
  11785. this._cachedCoordinatesMode = this.coordinatesMode;
  11786. switch (this.coordinatesMode) {
  11787. case BABYLON.Texture.SPHERICAL_MODE:
  11788. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11789. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11790. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11791. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11792. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11793. break;
  11794. case BABYLON.Texture.PLANAR_MODE:
  11795. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11796. this._cachedTextureMatrix[0] = this.uScale;
  11797. this._cachedTextureMatrix[5] = this.vScale;
  11798. this._cachedTextureMatrix[12] = this.uOffset;
  11799. this._cachedTextureMatrix[13] = this.vOffset;
  11800. break;
  11801. case BABYLON.Texture.PROJECTION_MODE:
  11802. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11803. this._projectionModeMatrix.m[0] = 0.5;
  11804. this._projectionModeMatrix.m[5] = -0.5;
  11805. this._projectionModeMatrix.m[10] = 0.0;
  11806. this._projectionModeMatrix.m[12] = 0.5;
  11807. this._projectionModeMatrix.m[13] = 0.5;
  11808. this._projectionModeMatrix.m[14] = 1.0;
  11809. this._projectionModeMatrix.m[15] = 1.0;
  11810. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11811. break;
  11812. default:
  11813. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11814. break;
  11815. }
  11816. return this._cachedTextureMatrix;
  11817. };
  11818. Texture.prototype.clone = function () {
  11819. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11820. // Base texture
  11821. newTexture.hasAlpha = this.hasAlpha;
  11822. newTexture.level = this.level;
  11823. newTexture.wrapU = this.wrapU;
  11824. newTexture.wrapV = this.wrapV;
  11825. newTexture.coordinatesIndex = this.coordinatesIndex;
  11826. newTexture.coordinatesMode = this.coordinatesMode;
  11827. // Texture
  11828. newTexture.uOffset = this.uOffset;
  11829. newTexture.vOffset = this.vOffset;
  11830. newTexture.uScale = this.uScale;
  11831. newTexture.vScale = this.vScale;
  11832. newTexture.uAng = this.uAng;
  11833. newTexture.vAng = this.vAng;
  11834. newTexture.wAng = this.wAng;
  11835. return newTexture;
  11836. };
  11837. // Statics
  11838. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11839. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11840. if (onLoad === void 0) { onLoad = null; }
  11841. if (onError === void 0) { onError = null; }
  11842. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11843. };
  11844. // Constants
  11845. Texture.NEAREST_SAMPLINGMODE = 1;
  11846. Texture.BILINEAR_SAMPLINGMODE = 2;
  11847. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11848. Texture.EXPLICIT_MODE = 0;
  11849. Texture.SPHERICAL_MODE = 1;
  11850. Texture.PLANAR_MODE = 2;
  11851. Texture.CUBIC_MODE = 3;
  11852. Texture.PROJECTION_MODE = 4;
  11853. Texture.SKYBOX_MODE = 5;
  11854. Texture.CLAMP_ADDRESSMODE = 0;
  11855. Texture.WRAP_ADDRESSMODE = 1;
  11856. Texture.MIRROR_ADDRESSMODE = 2;
  11857. return Texture;
  11858. })(BABYLON.BaseTexture);
  11859. BABYLON.Texture = Texture;
  11860. })(BABYLON || (BABYLON = {}));
  11861. //# sourceMappingURL=babylon.texture.js.map
  11862. var BABYLON;
  11863. (function (BABYLON) {
  11864. var CubeTexture = (function (_super) {
  11865. __extends(CubeTexture, _super);
  11866. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11867. _super.call(this, scene);
  11868. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11869. this.name = rootUrl;
  11870. this.url = rootUrl;
  11871. this._noMipmap = noMipmap;
  11872. this.hasAlpha = false;
  11873. this._texture = this._getFromCache(rootUrl, noMipmap);
  11874. if (!extensions) {
  11875. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11876. }
  11877. this._extensions = extensions;
  11878. if (!this._texture) {
  11879. if (!scene.useDelayedTextureLoading) {
  11880. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11881. }
  11882. else {
  11883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11884. }
  11885. }
  11886. this.isCube = true;
  11887. this._textureMatrix = BABYLON.Matrix.Identity();
  11888. }
  11889. CubeTexture.prototype.clone = function () {
  11890. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11891. // Base texture
  11892. newTexture.level = this.level;
  11893. newTexture.wrapU = this.wrapU;
  11894. newTexture.wrapV = this.wrapV;
  11895. newTexture.coordinatesIndex = this.coordinatesIndex;
  11896. newTexture.coordinatesMode = this.coordinatesMode;
  11897. return newTexture;
  11898. };
  11899. // Methods
  11900. CubeTexture.prototype.delayLoad = function () {
  11901. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11902. return;
  11903. }
  11904. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11905. this._texture = this._getFromCache(this.url, this._noMipmap);
  11906. if (!this._texture) {
  11907. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11908. }
  11909. };
  11910. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11911. return this._textureMatrix;
  11912. };
  11913. return CubeTexture;
  11914. })(BABYLON.BaseTexture);
  11915. BABYLON.CubeTexture = CubeTexture;
  11916. })(BABYLON || (BABYLON = {}));
  11917. //# sourceMappingURL=babylon.cubeTexture.js.map
  11918. var BABYLON;
  11919. (function (BABYLON) {
  11920. var RenderTargetTexture = (function (_super) {
  11921. __extends(RenderTargetTexture, _super);
  11922. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11923. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11924. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11925. _super.call(this, null, scene, !generateMipMaps);
  11926. this.renderList = new Array();
  11927. this.renderParticles = true;
  11928. this.renderSprites = false;
  11929. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11930. this._currentRefreshId = -1;
  11931. this._refreshRate = 1;
  11932. this.name = name;
  11933. this.isRenderTarget = true;
  11934. this._size = size;
  11935. this._generateMipMaps = generateMipMaps;
  11936. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11937. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11938. // Rendering groups
  11939. this._renderingManager = new BABYLON.RenderingManager(scene);
  11940. }
  11941. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11942. this._currentRefreshId = -1;
  11943. };
  11944. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11945. get: function () {
  11946. return this._refreshRate;
  11947. },
  11948. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11949. set: function (value) {
  11950. this._refreshRate = value;
  11951. this.resetRefreshCounter();
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. RenderTargetTexture.prototype._shouldRender = function () {
  11957. if (this._currentRefreshId === -1) {
  11958. this._currentRefreshId = 1;
  11959. return true;
  11960. }
  11961. if (this.refreshRate === this._currentRefreshId) {
  11962. this._currentRefreshId = 1;
  11963. return true;
  11964. }
  11965. this._currentRefreshId++;
  11966. return false;
  11967. };
  11968. RenderTargetTexture.prototype.isReady = function () {
  11969. if (!this.getScene().renderTargetsEnabled) {
  11970. return false;
  11971. }
  11972. return _super.prototype.isReady.call(this);
  11973. };
  11974. RenderTargetTexture.prototype.getRenderSize = function () {
  11975. return this._size;
  11976. };
  11977. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11978. get: function () {
  11979. return true;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. RenderTargetTexture.prototype.scale = function (ratio) {
  11985. var newSize = this._size * ratio;
  11986. this.resize(newSize, this._generateMipMaps);
  11987. };
  11988. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11989. this.releaseInternalTexture();
  11990. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11991. };
  11992. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11993. var scene = this.getScene();
  11994. var engine = scene.getEngine();
  11995. if (this._waitingRenderList) {
  11996. this.renderList = [];
  11997. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11998. var id = this._waitingRenderList[index];
  11999. this.renderList.push(scene.getMeshByID(id));
  12000. }
  12001. delete this._waitingRenderList;
  12002. }
  12003. if (this.renderList && this.renderList.length === 0) {
  12004. return;
  12005. }
  12006. // Bind
  12007. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12008. engine.bindFramebuffer(this._texture);
  12009. }
  12010. this._renderingManager.reset();
  12011. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12012. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12013. var mesh = currentRenderList[meshIndex];
  12014. if (mesh) {
  12015. if (!mesh.isReady()) {
  12016. // Reset _currentRefreshId
  12017. this.resetRefreshCounter();
  12018. continue;
  12019. }
  12020. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12021. mesh._activate(scene.getRenderId());
  12022. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12023. var subMesh = mesh.subMeshes[subIndex];
  12024. scene._activeVertices += subMesh.indexCount;
  12025. this._renderingManager.dispatch(subMesh);
  12026. }
  12027. }
  12028. }
  12029. }
  12030. if (this.onBeforeRender) {
  12031. this.onBeforeRender();
  12032. }
  12033. // Clear
  12034. engine.clear(scene.clearColor, true, true);
  12035. if (!this._doNotChangeAspectRatio) {
  12036. scene.updateTransformMatrix(true);
  12037. }
  12038. // Render
  12039. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12040. if (useCameraPostProcess) {
  12041. scene.postProcessManager._finalizeFrame(false, this._texture);
  12042. }
  12043. if (!this._doNotChangeAspectRatio) {
  12044. scene.updateTransformMatrix(true);
  12045. }
  12046. if (this.onAfterRender) {
  12047. this.onAfterRender();
  12048. }
  12049. // Unbind
  12050. engine.unBindFramebuffer(this._texture);
  12051. };
  12052. RenderTargetTexture.prototype.clone = function () {
  12053. var textureSize = this.getSize();
  12054. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12055. // Base texture
  12056. newTexture.hasAlpha = this.hasAlpha;
  12057. newTexture.level = this.level;
  12058. // RenderTarget Texture
  12059. newTexture.coordinatesMode = this.coordinatesMode;
  12060. newTexture.renderList = this.renderList.slice(0);
  12061. return newTexture;
  12062. };
  12063. return RenderTargetTexture;
  12064. })(BABYLON.Texture);
  12065. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12066. })(BABYLON || (BABYLON = {}));
  12067. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12068. var BABYLON;
  12069. (function (BABYLON) {
  12070. var ProceduralTexture = (function (_super) {
  12071. __extends(ProceduralTexture, _super);
  12072. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12073. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12074. _super.call(this, null, scene, !generateMipMaps);
  12075. this._currentRefreshId = -1;
  12076. this._refreshRate = 1;
  12077. this._vertexDeclaration = [2];
  12078. this._vertexStrideSize = 2 * 4;
  12079. this._uniforms = new Array();
  12080. this._samplers = new Array();
  12081. this._textures = new Array();
  12082. this._floats = new Array();
  12083. this._floatsArrays = {};
  12084. this._colors3 = new Array();
  12085. this._colors4 = new Array();
  12086. this._vectors2 = new Array();
  12087. this._vectors3 = new Array();
  12088. this._matrices = new Array();
  12089. this._fallbackTextureUsed = false;
  12090. scene._proceduralTextures.push(this);
  12091. this.name = name;
  12092. this.isRenderTarget = true;
  12093. this._size = size;
  12094. this._generateMipMaps = generateMipMaps;
  12095. this.setFragment(fragment);
  12096. this._fallbackTexture = fallbackTexture;
  12097. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12098. // VBO
  12099. var vertices = [];
  12100. vertices.push(1, 1);
  12101. vertices.push(-1, 1);
  12102. vertices.push(-1, -1);
  12103. vertices.push(1, -1);
  12104. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12105. // Indices
  12106. var indices = [];
  12107. indices.push(0);
  12108. indices.push(1);
  12109. indices.push(2);
  12110. indices.push(0);
  12111. indices.push(2);
  12112. indices.push(3);
  12113. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12114. }
  12115. ProceduralTexture.prototype.reset = function () {
  12116. if (this._effect === undefined) {
  12117. return;
  12118. }
  12119. var engine = this.getScene().getEngine();
  12120. engine._releaseEffect(this._effect);
  12121. };
  12122. ProceduralTexture.prototype.isReady = function () {
  12123. var _this = this;
  12124. var engine = this.getScene().getEngine();
  12125. var shaders;
  12126. if (!this._fragment) {
  12127. return false;
  12128. }
  12129. if (this._fallbackTextureUsed) {
  12130. return true;
  12131. }
  12132. if (this._fragment.fragmentElement !== undefined) {
  12133. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12134. }
  12135. else {
  12136. shaders = { vertex: "procedural", fragment: this._fragment };
  12137. }
  12138. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12139. _this.releaseInternalTexture();
  12140. if (_this._fallbackTexture) {
  12141. _this._texture = _this._fallbackTexture._texture;
  12142. _this._texture.references++;
  12143. }
  12144. _this._fallbackTextureUsed = true;
  12145. });
  12146. return this._effect.isReady();
  12147. };
  12148. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12149. this._currentRefreshId = -1;
  12150. };
  12151. ProceduralTexture.prototype.setFragment = function (fragment) {
  12152. this._fragment = fragment;
  12153. };
  12154. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12155. get: function () {
  12156. return this._refreshRate;
  12157. },
  12158. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12159. set: function (value) {
  12160. this._refreshRate = value;
  12161. this.resetRefreshCounter();
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. ProceduralTexture.prototype._shouldRender = function () {
  12167. if (!this.isReady() || !this._texture) {
  12168. return false;
  12169. }
  12170. if (this._fallbackTextureUsed) {
  12171. return false;
  12172. }
  12173. if (this._currentRefreshId === -1) {
  12174. this._currentRefreshId = 1;
  12175. return true;
  12176. }
  12177. if (this.refreshRate === this._currentRefreshId) {
  12178. this._currentRefreshId = 1;
  12179. return true;
  12180. }
  12181. this._currentRefreshId++;
  12182. return false;
  12183. };
  12184. ProceduralTexture.prototype.getRenderSize = function () {
  12185. return this._size;
  12186. };
  12187. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12188. if (this._fallbackTextureUsed) {
  12189. return;
  12190. }
  12191. this.releaseInternalTexture();
  12192. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12193. };
  12194. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12195. if (this._uniforms.indexOf(uniformName) === -1) {
  12196. this._uniforms.push(uniformName);
  12197. }
  12198. };
  12199. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12200. if (this._samplers.indexOf(name) === -1) {
  12201. this._samplers.push(name);
  12202. }
  12203. this._textures[name] = texture;
  12204. return this;
  12205. };
  12206. ProceduralTexture.prototype.setFloat = function (name, value) {
  12207. this._checkUniform(name);
  12208. this._floats[name] = value;
  12209. return this;
  12210. };
  12211. ProceduralTexture.prototype.setFloats = function (name, value) {
  12212. this._checkUniform(name);
  12213. this._floatsArrays[name] = value;
  12214. return this;
  12215. };
  12216. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12217. this._checkUniform(name);
  12218. this._colors3[name] = value;
  12219. return this;
  12220. };
  12221. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12222. this._checkUniform(name);
  12223. this._colors4[name] = value;
  12224. return this;
  12225. };
  12226. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12227. this._checkUniform(name);
  12228. this._vectors2[name] = value;
  12229. return this;
  12230. };
  12231. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12232. this._checkUniform(name);
  12233. this._vectors3[name] = value;
  12234. return this;
  12235. };
  12236. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12237. this._checkUniform(name);
  12238. this._matrices[name] = value;
  12239. return this;
  12240. };
  12241. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12242. var scene = this.getScene();
  12243. var engine = scene.getEngine();
  12244. engine.bindFramebuffer(this._texture);
  12245. // Clear
  12246. engine.clear(scene.clearColor, true, true);
  12247. // Render
  12248. engine.enableEffect(this._effect);
  12249. engine.setState(false);
  12250. for (var name in this._textures) {
  12251. this._effect.setTexture(name, this._textures[name]);
  12252. }
  12253. for (name in this._floats) {
  12254. this._effect.setFloat(name, this._floats[name]);
  12255. }
  12256. for (name in this._floatsArrays) {
  12257. this._effect.setArray(name, this._floatsArrays[name]);
  12258. }
  12259. for (name in this._colors3) {
  12260. this._effect.setColor3(name, this._colors3[name]);
  12261. }
  12262. for (name in this._colors4) {
  12263. var color = this._colors4[name];
  12264. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12265. }
  12266. for (name in this._vectors2) {
  12267. this._effect.setVector2(name, this._vectors2[name]);
  12268. }
  12269. for (name in this._vectors3) {
  12270. this._effect.setVector3(name, this._vectors3[name]);
  12271. }
  12272. for (name in this._matrices) {
  12273. this._effect.setMatrix(name, this._matrices[name]);
  12274. }
  12275. // VBOs
  12276. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12277. // Draw order
  12278. engine.draw(true, 0, 6);
  12279. // Unbind
  12280. engine.unBindFramebuffer(this._texture);
  12281. };
  12282. ProceduralTexture.prototype.clone = function () {
  12283. var textureSize = this.getSize();
  12284. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12285. // Base texture
  12286. newTexture.hasAlpha = this.hasAlpha;
  12287. newTexture.level = this.level;
  12288. // RenderTarget Texture
  12289. newTexture.coordinatesMode = this.coordinatesMode;
  12290. return newTexture;
  12291. };
  12292. ProceduralTexture.prototype.dispose = function () {
  12293. var index = this.getScene()._proceduralTextures.indexOf(this);
  12294. if (index >= 0) {
  12295. this.getScene()._proceduralTextures.splice(index, 1);
  12296. }
  12297. _super.prototype.dispose.call(this);
  12298. };
  12299. return ProceduralTexture;
  12300. })(BABYLON.Texture);
  12301. BABYLON.ProceduralTexture = ProceduralTexture;
  12302. })(BABYLON || (BABYLON = {}));
  12303. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12304. var BABYLON;
  12305. (function (BABYLON) {
  12306. var WoodProceduralTexture = (function (_super) {
  12307. __extends(WoodProceduralTexture, _super);
  12308. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12309. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12310. this._ampScale = 100.0;
  12311. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12312. this.updateShaderUniforms();
  12313. this.refreshRate = 0;
  12314. }
  12315. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12316. this.setFloat("ampScale", this._ampScale);
  12317. this.setColor3("woodColor", this._woodColor);
  12318. };
  12319. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12320. get: function () {
  12321. return this._ampScale;
  12322. },
  12323. set: function (value) {
  12324. this._ampScale = value;
  12325. this.updateShaderUniforms();
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12331. get: function () {
  12332. return this._woodColor;
  12333. },
  12334. set: function (value) {
  12335. this._woodColor = value;
  12336. this.updateShaderUniforms();
  12337. },
  12338. enumerable: true,
  12339. configurable: true
  12340. });
  12341. return WoodProceduralTexture;
  12342. })(BABYLON.ProceduralTexture);
  12343. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12344. var FireProceduralTexture = (function (_super) {
  12345. __extends(FireProceduralTexture, _super);
  12346. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12347. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12348. this._time = 0.0;
  12349. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12350. this._shift = 1.6;
  12351. this._autoGenerateTime = true;
  12352. this._alphaThreshold = 0.5;
  12353. this._fireColors = FireProceduralTexture.RedFireColors;
  12354. this.updateShaderUniforms();
  12355. this.refreshRate = 1;
  12356. }
  12357. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12358. this.setFloat("time", this._time);
  12359. this.setVector2("speed", this._speed);
  12360. this.setFloat("shift", this._shift);
  12361. this.setColor3("c1", this._fireColors[0]);
  12362. this.setColor3("c2", this._fireColors[1]);
  12363. this.setColor3("c3", this._fireColors[2]);
  12364. this.setColor3("c4", this._fireColors[3]);
  12365. this.setColor3("c5", this._fireColors[4]);
  12366. this.setColor3("c6", this._fireColors[5]);
  12367. this.setFloat("alphaThreshold", this._alphaThreshold);
  12368. };
  12369. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12370. if (this._autoGenerateTime) {
  12371. this._time += this.getScene().getAnimationRatio() * 0.03;
  12372. this.updateShaderUniforms();
  12373. }
  12374. _super.prototype.render.call(this, useCameraPostProcess);
  12375. };
  12376. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12377. get: function () {
  12378. return [
  12379. new BABYLON.Color3(0.5, 0.0, 1.0),
  12380. new BABYLON.Color3(0.9, 0.0, 1.0),
  12381. new BABYLON.Color3(0.2, 0.0, 1.0),
  12382. new BABYLON.Color3(1.0, 0.9, 1.0),
  12383. new BABYLON.Color3(0.1, 0.1, 1.0),
  12384. new BABYLON.Color3(0.9, 0.9, 1.0)
  12385. ];
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12391. get: function () {
  12392. return [
  12393. new BABYLON.Color3(0.5, 1.0, 0.0),
  12394. new BABYLON.Color3(0.5, 1.0, 0.0),
  12395. new BABYLON.Color3(0.3, 0.4, 0.0),
  12396. new BABYLON.Color3(0.5, 1.0, 0.0),
  12397. new BABYLON.Color3(0.2, 0.0, 0.0),
  12398. new BABYLON.Color3(0.5, 1.0, 0.0)
  12399. ];
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12405. get: function () {
  12406. return [
  12407. new BABYLON.Color3(0.5, 0.0, 0.1),
  12408. new BABYLON.Color3(0.9, 0.0, 0.0),
  12409. new BABYLON.Color3(0.2, 0.0, 0.0),
  12410. new BABYLON.Color3(1.0, 0.9, 0.0),
  12411. new BABYLON.Color3(0.1, 0.1, 0.1),
  12412. new BABYLON.Color3(0.9, 0.9, 0.9)
  12413. ];
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12419. get: function () {
  12420. return [
  12421. new BABYLON.Color3(0.1, 0.0, 0.5),
  12422. new BABYLON.Color3(0.0, 0.0, 0.5),
  12423. new BABYLON.Color3(0.1, 0.0, 0.2),
  12424. new BABYLON.Color3(0.0, 0.0, 1.0),
  12425. new BABYLON.Color3(0.1, 0.2, 0.3),
  12426. new BABYLON.Color3(0.0, 0.2, 0.9)
  12427. ];
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12433. get: function () {
  12434. return this._fireColors;
  12435. },
  12436. set: function (value) {
  12437. this._fireColors = value;
  12438. this.updateShaderUniforms();
  12439. },
  12440. enumerable: true,
  12441. configurable: true
  12442. });
  12443. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12444. get: function () {
  12445. return this._time;
  12446. },
  12447. set: function (value) {
  12448. this._time = value;
  12449. this.updateShaderUniforms();
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12455. get: function () {
  12456. return this._speed;
  12457. },
  12458. set: function (value) {
  12459. this._speed = value;
  12460. this.updateShaderUniforms();
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12466. get: function () {
  12467. return this._shift;
  12468. },
  12469. set: function (value) {
  12470. this._shift = value;
  12471. this.updateShaderUniforms();
  12472. },
  12473. enumerable: true,
  12474. configurable: true
  12475. });
  12476. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12477. get: function () {
  12478. return this._alphaThreshold;
  12479. },
  12480. set: function (value) {
  12481. this._alphaThreshold = value;
  12482. this.updateShaderUniforms();
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. return FireProceduralTexture;
  12488. })(BABYLON.ProceduralTexture);
  12489. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12490. var CloudProceduralTexture = (function (_super) {
  12491. __extends(CloudProceduralTexture, _super);
  12492. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12493. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12494. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12495. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12496. this.updateShaderUniforms();
  12497. this.refreshRate = 0;
  12498. }
  12499. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12500. this.setColor3("skyColor", this._skyColor);
  12501. this.setColor3("cloudColor", this._cloudColor);
  12502. };
  12503. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12504. get: function () {
  12505. return this._skyColor;
  12506. },
  12507. set: function (value) {
  12508. this._skyColor = value;
  12509. this.updateShaderUniforms();
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12515. get: function () {
  12516. return this._cloudColor;
  12517. },
  12518. set: function (value) {
  12519. this._cloudColor = value;
  12520. this.updateShaderUniforms();
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. return CloudProceduralTexture;
  12526. })(BABYLON.ProceduralTexture);
  12527. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12528. var GrassProceduralTexture = (function (_super) {
  12529. __extends(GrassProceduralTexture, _super);
  12530. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12531. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12532. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12533. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12534. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12535. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12536. this._grassColors = [
  12537. new BABYLON.Color3(0.29, 0.38, 0.02),
  12538. new BABYLON.Color3(0.36, 0.49, 0.09),
  12539. new BABYLON.Color3(0.51, 0.6, 0.28)
  12540. ];
  12541. this.updateShaderUniforms();
  12542. this.refreshRate = 0;
  12543. }
  12544. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12545. this.setColor3("herb1Color", this._grassColors[0]);
  12546. this.setColor3("herb2Color", this._grassColors[1]);
  12547. this.setColor3("herb3Color", this._grassColors[2]);
  12548. this.setColor3("groundColor", this._groundColor);
  12549. };
  12550. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12551. get: function () {
  12552. return this._grassColors;
  12553. },
  12554. set: function (value) {
  12555. this._grassColors = value;
  12556. this.updateShaderUniforms();
  12557. },
  12558. enumerable: true,
  12559. configurable: true
  12560. });
  12561. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12562. get: function () {
  12563. return this._groundColor;
  12564. },
  12565. set: function (value) {
  12566. this.groundColor = value;
  12567. this.updateShaderUniforms();
  12568. },
  12569. enumerable: true,
  12570. configurable: true
  12571. });
  12572. return GrassProceduralTexture;
  12573. })(BABYLON.ProceduralTexture);
  12574. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12575. var RoadProceduralTexture = (function (_super) {
  12576. __extends(RoadProceduralTexture, _super);
  12577. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12578. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12579. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12580. this.updateShaderUniforms();
  12581. this.refreshRate = 0;
  12582. }
  12583. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12584. this.setColor3("roadColor", this._roadColor);
  12585. };
  12586. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12587. get: function () {
  12588. return this._roadColor;
  12589. },
  12590. set: function (value) {
  12591. this._roadColor = value;
  12592. this.updateShaderUniforms();
  12593. },
  12594. enumerable: true,
  12595. configurable: true
  12596. });
  12597. return RoadProceduralTexture;
  12598. })(BABYLON.ProceduralTexture);
  12599. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12600. var BrickProceduralTexture = (function (_super) {
  12601. __extends(BrickProceduralTexture, _super);
  12602. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12603. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12604. this._numberOfBricksHeight = 15;
  12605. this._numberOfBricksWidth = 5;
  12606. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12607. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12608. this.updateShaderUniforms();
  12609. this.refreshRate = 0;
  12610. }
  12611. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12612. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12613. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12614. this.setColor3("brickColor", this._brickColor);
  12615. this.setColor3("jointColor", this._jointColor);
  12616. };
  12617. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12618. get: function () {
  12619. return this._numberOfBricksHeight;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12625. set: function (value) {
  12626. this._numberOfBricksHeight = value;
  12627. this.updateShaderUniforms();
  12628. },
  12629. enumerable: true,
  12630. configurable: true
  12631. });
  12632. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12633. get: function () {
  12634. return this._numberOfBricksWidth;
  12635. },
  12636. set: function (value) {
  12637. this._numberOfBricksHeight = value;
  12638. this.updateShaderUniforms();
  12639. },
  12640. enumerable: true,
  12641. configurable: true
  12642. });
  12643. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12644. get: function () {
  12645. return this._jointColor;
  12646. },
  12647. set: function (value) {
  12648. this._jointColor = value;
  12649. this.updateShaderUniforms();
  12650. },
  12651. enumerable: true,
  12652. configurable: true
  12653. });
  12654. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12655. get: function () {
  12656. return this._brickColor;
  12657. },
  12658. set: function (value) {
  12659. this._brickColor = value;
  12660. this.updateShaderUniforms();
  12661. },
  12662. enumerable: true,
  12663. configurable: true
  12664. });
  12665. return BrickProceduralTexture;
  12666. })(BABYLON.ProceduralTexture);
  12667. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12668. var MarbleProceduralTexture = (function (_super) {
  12669. __extends(MarbleProceduralTexture, _super);
  12670. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12671. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12672. this._numberOfTilesHeight = 3;
  12673. this._numberOfTilesWidth = 3;
  12674. this._amplitude = 9.0;
  12675. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12676. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12677. this.updateShaderUniforms();
  12678. this.refreshRate = 0;
  12679. }
  12680. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12681. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12682. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12683. this.setFloat("amplitude", this._amplitude);
  12684. this.setColor3("marbleColor", this._marbleColor);
  12685. this.setColor3("jointColor", this._jointColor);
  12686. };
  12687. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12688. get: function () {
  12689. return this._numberOfTilesHeight;
  12690. },
  12691. set: function (value) {
  12692. this._numberOfTilesHeight = value;
  12693. this.updateShaderUniforms();
  12694. },
  12695. enumerable: true,
  12696. configurable: true
  12697. });
  12698. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12699. get: function () {
  12700. return this._numberOfTilesWidth;
  12701. },
  12702. set: function (value) {
  12703. this._numberOfTilesWidth = value;
  12704. this.updateShaderUniforms();
  12705. },
  12706. enumerable: true,
  12707. configurable: true
  12708. });
  12709. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12710. get: function () {
  12711. return this._jointColor;
  12712. },
  12713. set: function (value) {
  12714. this._jointColor = value;
  12715. this.updateShaderUniforms();
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12721. get: function () {
  12722. return this._marbleColor;
  12723. },
  12724. set: function (value) {
  12725. this._marbleColor = value;
  12726. this.updateShaderUniforms();
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. return MarbleProceduralTexture;
  12732. })(BABYLON.ProceduralTexture);
  12733. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12734. })(BABYLON || (BABYLON = {}));
  12735. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12736. var BABYLON;
  12737. (function (BABYLON) {
  12738. var CustomProceduralTexture = (function (_super) {
  12739. __extends(CustomProceduralTexture, _super);
  12740. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12741. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12742. this._animate = true;
  12743. this._time = 0;
  12744. this._texturePath = texturePath;
  12745. //Try to load json
  12746. this.loadJson(texturePath);
  12747. this.refreshRate = 1;
  12748. }
  12749. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12750. var _this = this;
  12751. var that = this;
  12752. function noConfigFile() {
  12753. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  12754. try {
  12755. that.setFragment(that._texturePath);
  12756. }
  12757. catch (ex) {
  12758. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12759. }
  12760. }
  12761. var configFileUrl = jsonUrl + "/config.json";
  12762. var xhr = new XMLHttpRequest();
  12763. xhr.open("GET", configFileUrl, true);
  12764. xhr.addEventListener("load", function () {
  12765. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12766. try {
  12767. _this._config = JSON.parse(xhr.response);
  12768. _this.updateShaderUniforms();
  12769. _this.updateTextures();
  12770. _this.setFragment(_this._texturePath + "/custom");
  12771. _this._animate = _this._config.animate;
  12772. _this.refreshRate = _this._config.refreshrate;
  12773. }
  12774. catch (ex) {
  12775. noConfigFile();
  12776. }
  12777. }
  12778. else {
  12779. noConfigFile();
  12780. }
  12781. }, false);
  12782. xhr.addEventListener("error", function () {
  12783. noConfigFile();
  12784. }, false);
  12785. try {
  12786. xhr.send();
  12787. }
  12788. catch (ex) {
  12789. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12790. }
  12791. };
  12792. CustomProceduralTexture.prototype.isReady = function () {
  12793. if (!_super.prototype.isReady.call(this)) {
  12794. return false;
  12795. }
  12796. for (var name in this._textures) {
  12797. var texture = this._textures[name];
  12798. if (!texture.isReady()) {
  12799. return false;
  12800. }
  12801. }
  12802. return true;
  12803. };
  12804. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12805. if (this._animate) {
  12806. this._time += this.getScene().getAnimationRatio() * 0.03;
  12807. this.updateShaderUniforms();
  12808. }
  12809. _super.prototype.render.call(this, useCameraPostProcess);
  12810. };
  12811. CustomProceduralTexture.prototype.updateTextures = function () {
  12812. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12813. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12814. }
  12815. };
  12816. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12817. if (this._config) {
  12818. for (var j = 0; j < this._config.uniforms.length; j++) {
  12819. var uniform = this._config.uniforms[j];
  12820. switch (uniform.type) {
  12821. case "float":
  12822. this.setFloat(uniform.name, uniform.value);
  12823. break;
  12824. case "color3":
  12825. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12826. break;
  12827. case "color4":
  12828. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12829. break;
  12830. case "vector2":
  12831. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12832. break;
  12833. case "vector3":
  12834. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12835. break;
  12836. }
  12837. }
  12838. }
  12839. this.setFloat("time", this._time);
  12840. };
  12841. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12842. get: function () {
  12843. return this._animate;
  12844. },
  12845. set: function (value) {
  12846. this._animate = value;
  12847. },
  12848. enumerable: true,
  12849. configurable: true
  12850. });
  12851. return CustomProceduralTexture;
  12852. })(BABYLON.ProceduralTexture);
  12853. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12854. })(BABYLON || (BABYLON = {}));
  12855. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12856. var BABYLON;
  12857. (function (BABYLON) {
  12858. var MirrorTexture = (function (_super) {
  12859. __extends(MirrorTexture, _super);
  12860. function MirrorTexture(name, size, scene, generateMipMaps) {
  12861. var _this = this;
  12862. _super.call(this, name, size, scene, generateMipMaps, true);
  12863. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12864. this._transformMatrix = BABYLON.Matrix.Zero();
  12865. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12866. this.onBeforeRender = function () {
  12867. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12868. _this._savedViewMatrix = scene.getViewMatrix();
  12869. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12870. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12871. scene.clipPlane = _this.mirrorPlane;
  12872. scene.getEngine().cullBackFaces = false;
  12873. };
  12874. this.onAfterRender = function () {
  12875. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12876. scene.getEngine().cullBackFaces = true;
  12877. delete scene.clipPlane;
  12878. };
  12879. }
  12880. MirrorTexture.prototype.clone = function () {
  12881. var textureSize = this.getSize();
  12882. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12883. // Base texture
  12884. newTexture.hasAlpha = this.hasAlpha;
  12885. newTexture.level = this.level;
  12886. // Mirror Texture
  12887. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12888. newTexture.renderList = this.renderList.slice(0);
  12889. return newTexture;
  12890. };
  12891. return MirrorTexture;
  12892. })(BABYLON.RenderTargetTexture);
  12893. BABYLON.MirrorTexture = MirrorTexture;
  12894. })(BABYLON || (BABYLON = {}));
  12895. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12896. var BABYLON;
  12897. (function (BABYLON) {
  12898. var DynamicTexture = (function (_super) {
  12899. __extends(DynamicTexture, _super);
  12900. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12902. _super.call(this, null, scene, !generateMipMaps);
  12903. this.name = name;
  12904. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12905. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12906. this._generateMipMaps = generateMipMaps;
  12907. if (options.getContext) {
  12908. this._canvas = options;
  12909. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12910. }
  12911. else {
  12912. this._canvas = document.createElement("canvas");
  12913. if (options.width) {
  12914. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12915. }
  12916. else {
  12917. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12918. }
  12919. }
  12920. var textureSize = this.getSize();
  12921. this._canvas.width = textureSize.width;
  12922. this._canvas.height = textureSize.height;
  12923. this._context = this._canvas.getContext("2d");
  12924. }
  12925. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12926. get: function () {
  12927. return true;
  12928. },
  12929. enumerable: true,
  12930. configurable: true
  12931. });
  12932. DynamicTexture.prototype.scale = function (ratio) {
  12933. var textureSize = this.getSize();
  12934. textureSize.width *= ratio;
  12935. textureSize.height *= ratio;
  12936. this._canvas.width = textureSize.width;
  12937. this._canvas.height = textureSize.height;
  12938. this.releaseInternalTexture();
  12939. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12940. };
  12941. DynamicTexture.prototype.getContext = function () {
  12942. return this._context;
  12943. };
  12944. DynamicTexture.prototype.clear = function () {
  12945. var size = this.getSize();
  12946. this._context.fillRect(0, 0, size.width, size.height);
  12947. };
  12948. DynamicTexture.prototype.update = function (invertY) {
  12949. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12950. };
  12951. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12952. if (update === void 0) { update = true; }
  12953. var size = this.getSize();
  12954. if (clearColor) {
  12955. this._context.fillStyle = clearColor;
  12956. this._context.fillRect(0, 0, size.width, size.height);
  12957. }
  12958. this._context.font = font;
  12959. if (x === null) {
  12960. var textSize = this._context.measureText(text);
  12961. x = (size.width - textSize.width) / 2;
  12962. }
  12963. this._context.fillStyle = color;
  12964. this._context.fillText(text, x, y);
  12965. if (update) {
  12966. this.update(invertY);
  12967. }
  12968. };
  12969. DynamicTexture.prototype.clone = function () {
  12970. var textureSize = this.getSize();
  12971. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12972. // Base texture
  12973. newTexture.hasAlpha = this.hasAlpha;
  12974. newTexture.level = this.level;
  12975. // Dynamic Texture
  12976. newTexture.wrapU = this.wrapU;
  12977. newTexture.wrapV = this.wrapV;
  12978. return newTexture;
  12979. };
  12980. return DynamicTexture;
  12981. })(BABYLON.Texture);
  12982. BABYLON.DynamicTexture = DynamicTexture;
  12983. })(BABYLON || (BABYLON = {}));
  12984. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12985. var BABYLON;
  12986. (function (BABYLON) {
  12987. var VideoTexture = (function (_super) {
  12988. __extends(VideoTexture, _super);
  12989. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12990. var _this = this;
  12991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12992. _super.call(this, null, scene, !generateMipMaps, invertY);
  12993. this._autoLaunch = true;
  12994. this.name = name;
  12995. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12996. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12997. var requiredWidth = size.width || size;
  12998. var requiredHeight = size.height || size;
  12999. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13000. var textureSize = this.getSize();
  13001. this.video = document.createElement("video");
  13002. this.video.width = textureSize.width;
  13003. this.video.height = textureSize.height;
  13004. this.video.autoplay = false;
  13005. this.video.loop = true;
  13006. this.video.addEventListener("canplaythrough", function () {
  13007. if (_this._texture) {
  13008. _this._texture.isReady = true;
  13009. }
  13010. });
  13011. urls.forEach(function (url) {
  13012. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13013. var source = document.createElement("source");
  13014. source.src = url;
  13015. _this.video.appendChild(source);
  13016. });
  13017. this._lastUpdate = BABYLON.Tools.Now;
  13018. }
  13019. VideoTexture.prototype.update = function () {
  13020. if (this._autoLaunch) {
  13021. this._autoLaunch = false;
  13022. this.video.play();
  13023. }
  13024. var now = BABYLON.Tools.Now;
  13025. if (now - this._lastUpdate < 15) {
  13026. return false;
  13027. }
  13028. this._lastUpdate = now;
  13029. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13030. return true;
  13031. };
  13032. return VideoTexture;
  13033. })(BABYLON.Texture);
  13034. BABYLON.VideoTexture = VideoTexture;
  13035. })(BABYLON || (BABYLON = {}));
  13036. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13037. (function (BABYLON) {
  13038. var EffectFallbacks = (function () {
  13039. function EffectFallbacks() {
  13040. this._defines = {};
  13041. this._currentRank = 32;
  13042. this._maxRank = -1;
  13043. }
  13044. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13045. if (!this._defines[rank]) {
  13046. if (rank < this._currentRank) {
  13047. this._currentRank = rank;
  13048. }
  13049. if (rank > this._maxRank) {
  13050. this._maxRank = rank;
  13051. }
  13052. this._defines[rank] = new Array();
  13053. }
  13054. this._defines[rank].push(define);
  13055. };
  13056. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13057. get: function () {
  13058. return this._currentRank <= this._maxRank;
  13059. },
  13060. enumerable: true,
  13061. configurable: true
  13062. });
  13063. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13064. var currentFallbacks = this._defines[this._currentRank];
  13065. for (var index = 0; index < currentFallbacks.length; index++) {
  13066. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13067. }
  13068. this._currentRank++;
  13069. return currentDefines;
  13070. };
  13071. return EffectFallbacks;
  13072. })();
  13073. BABYLON.EffectFallbacks = EffectFallbacks;
  13074. var Effect = (function () {
  13075. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13076. var _this = this;
  13077. this._isReady = false;
  13078. this._compilationError = "";
  13079. this._valueCache = [];
  13080. this._engine = engine;
  13081. this.name = baseName;
  13082. this.defines = defines;
  13083. this._uniformsNames = uniformsNames.concat(samplers);
  13084. this._samplers = samplers;
  13085. this._attributesNames = attributesNames;
  13086. this.onError = onError;
  13087. this.onCompiled = onCompiled;
  13088. var vertexSource;
  13089. var fragmentSource;
  13090. if (baseName.vertexElement) {
  13091. vertexSource = document.getElementById(baseName.vertexElement);
  13092. if (!vertexSource) {
  13093. vertexSource = baseName.vertexElement;
  13094. }
  13095. }
  13096. else {
  13097. vertexSource = baseName.vertex || baseName;
  13098. }
  13099. if (baseName.fragmentElement) {
  13100. fragmentSource = document.getElementById(baseName.fragmentElement);
  13101. if (!fragmentSource) {
  13102. fragmentSource = baseName.fragmentElement;
  13103. }
  13104. }
  13105. else {
  13106. fragmentSource = baseName.fragment || baseName;
  13107. }
  13108. this._loadVertexShader(vertexSource, function (vertexCode) {
  13109. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13110. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13111. });
  13112. });
  13113. }
  13114. // Properties
  13115. Effect.prototype.isReady = function () {
  13116. return this._isReady;
  13117. };
  13118. Effect.prototype.getProgram = function () {
  13119. return this._program;
  13120. };
  13121. Effect.prototype.getAttributesNames = function () {
  13122. return this._attributesNames;
  13123. };
  13124. Effect.prototype.getAttributeLocation = function (index) {
  13125. return this._attributes[index];
  13126. };
  13127. Effect.prototype.getAttributeLocationByName = function (name) {
  13128. var index = this._attributesNames.indexOf(name);
  13129. return this._attributes[index];
  13130. };
  13131. Effect.prototype.getAttributesCount = function () {
  13132. return this._attributes.length;
  13133. };
  13134. Effect.prototype.getUniformIndex = function (uniformName) {
  13135. return this._uniformsNames.indexOf(uniformName);
  13136. };
  13137. Effect.prototype.getUniform = function (uniformName) {
  13138. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13139. };
  13140. Effect.prototype.getSamplers = function () {
  13141. return this._samplers;
  13142. };
  13143. Effect.prototype.getCompilationError = function () {
  13144. return this._compilationError;
  13145. };
  13146. // Methods
  13147. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13148. // DOM element ?
  13149. if (vertex instanceof HTMLElement) {
  13150. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13151. callback(vertexCode);
  13152. return;
  13153. }
  13154. // Is in local store ?
  13155. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13156. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13157. return;
  13158. }
  13159. var vertexShaderUrl;
  13160. if (vertex[0] === ".") {
  13161. vertexShaderUrl = vertex;
  13162. }
  13163. else {
  13164. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13165. }
  13166. // Vertex shader
  13167. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13168. };
  13169. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13170. // DOM element ?
  13171. if (fragment instanceof HTMLElement) {
  13172. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13173. callback(fragmentCode);
  13174. return;
  13175. }
  13176. // Is in local store ?
  13177. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13178. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13179. return;
  13180. }
  13181. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13182. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13183. return;
  13184. }
  13185. var fragmentShaderUrl;
  13186. if (fragment[0] === ".") {
  13187. fragmentShaderUrl = fragment;
  13188. }
  13189. else {
  13190. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13191. }
  13192. // Fragment shader
  13193. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13194. };
  13195. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13196. try {
  13197. var engine = this._engine;
  13198. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13199. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13200. this._attributes = engine.getAttributes(this._program, attributesNames);
  13201. for (var index = 0; index < this._samplers.length; index++) {
  13202. var sampler = this.getUniform(this._samplers[index]);
  13203. if (sampler == null) {
  13204. this._samplers.splice(index, 1);
  13205. index--;
  13206. }
  13207. }
  13208. engine.bindSamplers(this);
  13209. this._isReady = true;
  13210. if (this.onCompiled) {
  13211. this.onCompiled(this);
  13212. }
  13213. }
  13214. catch (e) {
  13215. // Is it a problem with precision?
  13216. if (e.message.indexOf("highp") !== -1) {
  13217. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13218. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13219. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13220. return;
  13221. }
  13222. // Let's go through fallbacks then
  13223. if (fallbacks && fallbacks.isMoreFallbacks) {
  13224. defines = fallbacks.reduce(defines);
  13225. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13226. }
  13227. else {
  13228. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13229. BABYLON.Tools.Error("Defines: " + defines);
  13230. BABYLON.Tools.Error("Error: " + e.message);
  13231. this._compilationError = e.message;
  13232. if (this.onError) {
  13233. this.onError(this, this._compilationError);
  13234. }
  13235. }
  13236. }
  13237. };
  13238. Effect.prototype._bindTexture = function (channel, texture) {
  13239. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13240. };
  13241. Effect.prototype.setTexture = function (channel, texture) {
  13242. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13243. };
  13244. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13245. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13246. };
  13247. //public _cacheMatrix(uniformName, matrix) {
  13248. // if (!this._valueCache[uniformName]) {
  13249. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13250. // }
  13251. // for (var index = 0; index < 16; index++) {
  13252. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13253. // }
  13254. //};
  13255. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13256. if (!this._valueCache[uniformName]) {
  13257. this._valueCache[uniformName] = [x, y];
  13258. return;
  13259. }
  13260. this._valueCache[uniformName][0] = x;
  13261. this._valueCache[uniformName][1] = y;
  13262. };
  13263. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13264. if (!this._valueCache[uniformName]) {
  13265. this._valueCache[uniformName] = [x, y, z];
  13266. return;
  13267. }
  13268. this._valueCache[uniformName][0] = x;
  13269. this._valueCache[uniformName][1] = y;
  13270. this._valueCache[uniformName][2] = z;
  13271. };
  13272. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13273. if (!this._valueCache[uniformName]) {
  13274. this._valueCache[uniformName] = [x, y, z, w];
  13275. return;
  13276. }
  13277. this._valueCache[uniformName][0] = x;
  13278. this._valueCache[uniformName][1] = y;
  13279. this._valueCache[uniformName][2] = z;
  13280. this._valueCache[uniformName][3] = w;
  13281. };
  13282. Effect.prototype.setArray = function (uniformName, array) {
  13283. this._engine.setArray(this.getUniform(uniformName), array);
  13284. return this;
  13285. };
  13286. Effect.prototype.setArray2 = function (uniformName, array) {
  13287. this._engine.setArray2(this.getUniform(uniformName), array);
  13288. return this;
  13289. };
  13290. Effect.prototype.setArray3 = function (uniformName, array) {
  13291. this._engine.setArray3(this.getUniform(uniformName), array);
  13292. return this;
  13293. };
  13294. Effect.prototype.setArray4 = function (uniformName, array) {
  13295. this._engine.setArray4(this.getUniform(uniformName), array);
  13296. return this;
  13297. };
  13298. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13299. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13300. return this;
  13301. };
  13302. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13303. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13304. // return;
  13305. //this._cacheMatrix(uniformName, matrix);
  13306. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13307. return this;
  13308. };
  13309. Effect.prototype.setFloat = function (uniformName, value) {
  13310. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13311. return this;
  13312. this._valueCache[uniformName] = value;
  13313. this._engine.setFloat(this.getUniform(uniformName), value);
  13314. return this;
  13315. };
  13316. Effect.prototype.setBool = function (uniformName, bool) {
  13317. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13318. return this;
  13319. this._valueCache[uniformName] = bool;
  13320. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13321. return this;
  13322. };
  13323. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13324. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13325. return this;
  13326. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13327. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13328. return this;
  13329. };
  13330. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13331. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13332. return this;
  13333. this._cacheFloat2(uniformName, x, y);
  13334. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13335. return this;
  13336. };
  13337. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13338. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13339. return this;
  13340. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13341. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13342. return this;
  13343. };
  13344. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13345. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13346. return this;
  13347. this._cacheFloat3(uniformName, x, y, z);
  13348. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13349. return this;
  13350. };
  13351. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13352. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13353. return this;
  13354. this._cacheFloat4(uniformName, x, y, z, w);
  13355. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13356. return this;
  13357. };
  13358. Effect.prototype.setColor3 = function (uniformName, color3) {
  13359. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13360. return this;
  13361. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13362. this._engine.setColor3(this.getUniform(uniformName), color3);
  13363. return this;
  13364. };
  13365. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13366. 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)
  13367. return this;
  13368. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13369. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13370. return this;
  13371. };
  13372. // Statics
  13373. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  13374. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  13375. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  13376. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  13377. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  13378. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13379. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  13380. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  13381. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.0 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13382. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  13383. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13384. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13385. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  13386. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  13387. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  13388. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  13389. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  13390. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13391. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13392. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13393. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  13394. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13395. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  13396. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  13397. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  13398. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  13399. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13400. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  13401. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  13402. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  13403. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13404. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13405. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  13406. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  13407. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13408. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13409. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  13410. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  13411. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13412. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13413. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13414. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13415. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  13416. };
  13417. return Effect;
  13418. })();
  13419. BABYLON.Effect = Effect;
  13420. })(BABYLON || (BABYLON = {}));
  13421. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13422. (function (BABYLON) {
  13423. var Material = (function () {
  13424. function Material(name, scene, doNotAdd) {
  13425. this.name = name;
  13426. this.checkReadyOnEveryCall = true;
  13427. this.checkReadyOnlyOnce = false;
  13428. this.state = "";
  13429. this.alpha = 1.0;
  13430. this.backFaceCulling = true;
  13431. this._wasPreviouslyReady = false;
  13432. this._fillMode = Material.TriangleFillMode;
  13433. this.pointSize = 1.0;
  13434. this.id = name;
  13435. this._scene = scene;
  13436. if (!doNotAdd) {
  13437. scene.materials.push(this);
  13438. }
  13439. }
  13440. Object.defineProperty(Material, "TriangleFillMode", {
  13441. get: function () {
  13442. return Material._TriangleFillMode;
  13443. },
  13444. enumerable: true,
  13445. configurable: true
  13446. });
  13447. Object.defineProperty(Material, "WireFrameFillMode", {
  13448. get: function () {
  13449. return Material._WireFrameFillMode;
  13450. },
  13451. enumerable: true,
  13452. configurable: true
  13453. });
  13454. Object.defineProperty(Material, "PointFillMode", {
  13455. get: function () {
  13456. return Material._PointFillMode;
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. Object.defineProperty(Material.prototype, "wireframe", {
  13462. get: function () {
  13463. return this._fillMode === Material.WireFrameFillMode;
  13464. },
  13465. set: function (value) {
  13466. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13467. },
  13468. enumerable: true,
  13469. configurable: true
  13470. });
  13471. Object.defineProperty(Material.prototype, "pointsCloud", {
  13472. get: function () {
  13473. return this._fillMode === Material.PointFillMode;
  13474. },
  13475. set: function (value) {
  13476. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13477. },
  13478. enumerable: true,
  13479. configurable: true
  13480. });
  13481. Object.defineProperty(Material.prototype, "fillMode", {
  13482. get: function () {
  13483. return this._fillMode;
  13484. },
  13485. set: function (value) {
  13486. this._fillMode = value;
  13487. },
  13488. enumerable: true,
  13489. configurable: true
  13490. });
  13491. Material.prototype.isReady = function (mesh, useInstances) {
  13492. return true;
  13493. };
  13494. Material.prototype.getEffect = function () {
  13495. return this._effect;
  13496. };
  13497. Material.prototype.getScene = function () {
  13498. return this._scene;
  13499. };
  13500. Material.prototype.needAlphaBlending = function () {
  13501. return (this.alpha < 1.0);
  13502. };
  13503. Material.prototype.needAlphaTesting = function () {
  13504. return false;
  13505. };
  13506. Material.prototype.getAlphaTestTexture = function () {
  13507. return null;
  13508. };
  13509. Material.prototype.trackCreation = function (onCompiled, onError) {
  13510. };
  13511. Material.prototype._preBind = function () {
  13512. var engine = this._scene.getEngine();
  13513. engine.enableEffect(this._effect);
  13514. engine.setState(this.backFaceCulling);
  13515. };
  13516. Material.prototype.bind = function (world, mesh) {
  13517. this._scene._cachedMaterial = this;
  13518. if (this.onBind) {
  13519. this.onBind(this);
  13520. }
  13521. };
  13522. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13523. };
  13524. Material.prototype.unbind = function () {
  13525. };
  13526. Material.prototype.dispose = function (forceDisposeEffect) {
  13527. // Remove from scene
  13528. var index = this._scene.materials.indexOf(this);
  13529. this._scene.materials.splice(index, 1);
  13530. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13531. if (forceDisposeEffect && this._effect) {
  13532. this._scene.getEngine()._releaseEffect(this._effect);
  13533. this._effect = null;
  13534. }
  13535. // Callback
  13536. if (this.onDispose) {
  13537. this.onDispose();
  13538. }
  13539. };
  13540. Material._TriangleFillMode = 0;
  13541. Material._WireFrameFillMode = 1;
  13542. Material._PointFillMode = 2;
  13543. return Material;
  13544. })();
  13545. BABYLON.Material = Material;
  13546. })(BABYLON || (BABYLON = {}));
  13547. //# sourceMappingURL=babylon.material.js.map
  13548. var BABYLON;
  13549. (function (BABYLON) {
  13550. var maxSimultaneousLights = 4;
  13551. var FresnelParameters = (function () {
  13552. function FresnelParameters() {
  13553. this.isEnabled = true;
  13554. this.leftColor = BABYLON.Color3.White();
  13555. this.rightColor = BABYLON.Color3.Black();
  13556. this.bias = 0;
  13557. this.power = 1;
  13558. }
  13559. return FresnelParameters;
  13560. })();
  13561. BABYLON.FresnelParameters = FresnelParameters;
  13562. var StandardMaterial = (function (_super) {
  13563. __extends(StandardMaterial, _super);
  13564. function StandardMaterial(name, scene) {
  13565. var _this = this;
  13566. _super.call(this, name, scene);
  13567. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13568. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13569. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13570. this.specularPower = 64;
  13571. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13572. this.useAlphaFromDiffuseTexture = false;
  13573. this.useSpecularOverAlpha = true;
  13574. this.fogEnabled = true;
  13575. this._cachedDefines = null;
  13576. this._renderTargets = new BABYLON.SmartArray(16);
  13577. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13578. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13579. this._scaledDiffuse = new BABYLON.Color3();
  13580. this._scaledSpecular = new BABYLON.Color3();
  13581. this.getRenderTargetTextures = function () {
  13582. _this._renderTargets.reset();
  13583. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13584. _this._renderTargets.push(_this.reflectionTexture);
  13585. }
  13586. return _this._renderTargets;
  13587. };
  13588. }
  13589. StandardMaterial.prototype.needAlphaBlending = function () {
  13590. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13591. };
  13592. StandardMaterial.prototype.needAlphaTesting = function () {
  13593. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13594. };
  13595. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13596. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13597. };
  13598. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13599. return this.diffuseTexture;
  13600. };
  13601. // Methods
  13602. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13603. if (this.checkReadyOnlyOnce) {
  13604. if (this._wasPreviouslyReady) {
  13605. return true;
  13606. }
  13607. }
  13608. var scene = this.getScene();
  13609. if (!this.checkReadyOnEveryCall) {
  13610. if (this._renderId === scene.getRenderId()) {
  13611. return true;
  13612. }
  13613. }
  13614. var engine = scene.getEngine();
  13615. var defines = [];
  13616. var fallbacks = new BABYLON.EffectFallbacks();
  13617. // Textures
  13618. if (scene.texturesEnabled) {
  13619. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13620. if (!this.diffuseTexture.isReady()) {
  13621. return false;
  13622. }
  13623. else {
  13624. defines.push("#define DIFFUSE");
  13625. }
  13626. }
  13627. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13628. if (!this.ambientTexture.isReady()) {
  13629. return false;
  13630. }
  13631. else {
  13632. defines.push("#define AMBIENT");
  13633. }
  13634. }
  13635. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13636. if (!this.opacityTexture.isReady()) {
  13637. return false;
  13638. }
  13639. else {
  13640. defines.push("#define OPACITY");
  13641. if (this.opacityTexture.getAlphaFromRGB) {
  13642. defines.push("#define OPACITYRGB");
  13643. }
  13644. }
  13645. }
  13646. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13647. if (!this.reflectionTexture.isReady()) {
  13648. return false;
  13649. }
  13650. else {
  13651. defines.push("#define REFLECTION");
  13652. fallbacks.addFallback(0, "REFLECTION");
  13653. }
  13654. }
  13655. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13656. if (!this.emissiveTexture.isReady()) {
  13657. return false;
  13658. }
  13659. else {
  13660. defines.push("#define EMISSIVE");
  13661. }
  13662. }
  13663. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13664. if (!this.specularTexture.isReady()) {
  13665. return false;
  13666. }
  13667. else {
  13668. defines.push("#define SPECULAR");
  13669. fallbacks.addFallback(0, "SPECULAR");
  13670. }
  13671. }
  13672. }
  13673. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13674. if (!this.bumpTexture.isReady()) {
  13675. return false;
  13676. }
  13677. else {
  13678. defines.push("#define BUMP");
  13679. fallbacks.addFallback(0, "BUMP");
  13680. }
  13681. }
  13682. // Effect
  13683. if (this.useSpecularOverAlpha) {
  13684. defines.push("#define SPECULAROVERALPHA");
  13685. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13686. }
  13687. if (scene.clipPlane) {
  13688. defines.push("#define CLIPPLANE");
  13689. }
  13690. if (engine.getAlphaTesting()) {
  13691. defines.push("#define ALPHATEST");
  13692. }
  13693. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13694. defines.push("#define ALPHAFROMDIFFUSE");
  13695. }
  13696. // Point size
  13697. if (this.pointsCloud || scene.forcePointsCloud) {
  13698. defines.push("#define POINTSIZE");
  13699. }
  13700. // Fog
  13701. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13702. defines.push("#define FOG");
  13703. fallbacks.addFallback(1, "FOG");
  13704. }
  13705. var shadowsActivated = false;
  13706. var lightIndex = 0;
  13707. if (scene.lightsEnabled) {
  13708. for (var index = 0; index < scene.lights.length; index++) {
  13709. var light = scene.lights[index];
  13710. if (!light.isEnabled()) {
  13711. continue;
  13712. }
  13713. // Excluded check
  13714. if (light._excludedMeshesIds.length > 0) {
  13715. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13716. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13717. if (excludedMesh) {
  13718. light.excludedMeshes.push(excludedMesh);
  13719. }
  13720. }
  13721. light._excludedMeshesIds = [];
  13722. }
  13723. // Included check
  13724. if (light._includedOnlyMeshesIds.length > 0) {
  13725. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13726. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13727. if (includedOnlyMesh) {
  13728. light.includedOnlyMeshes.push(includedOnlyMesh);
  13729. }
  13730. }
  13731. light._includedOnlyMeshesIds = [];
  13732. }
  13733. if (!light.canAffectMesh(mesh)) {
  13734. continue;
  13735. }
  13736. defines.push("#define LIGHT" + lightIndex);
  13737. if (lightIndex > 0) {
  13738. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13739. }
  13740. var type;
  13741. if (light instanceof BABYLON.SpotLight) {
  13742. type = "#define SPOTLIGHT" + lightIndex;
  13743. }
  13744. else if (light instanceof BABYLON.HemisphericLight) {
  13745. type = "#define HEMILIGHT" + lightIndex;
  13746. }
  13747. else {
  13748. type = "#define POINTDIRLIGHT" + lightIndex;
  13749. }
  13750. defines.push(type);
  13751. if (lightIndex > 0) {
  13752. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13753. }
  13754. // Shadows
  13755. if (scene.shadowsEnabled) {
  13756. var shadowGenerator = light.getShadowGenerator();
  13757. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13758. defines.push("#define SHADOW" + lightIndex);
  13759. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13760. if (!shadowsActivated) {
  13761. defines.push("#define SHADOWS");
  13762. shadowsActivated = true;
  13763. }
  13764. if (shadowGenerator.useVarianceShadowMap) {
  13765. defines.push("#define SHADOWVSM" + lightIndex);
  13766. if (lightIndex > 0) {
  13767. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13768. }
  13769. }
  13770. if (shadowGenerator.usePoissonSampling) {
  13771. defines.push("#define SHADOWPCF" + lightIndex);
  13772. if (lightIndex > 0) {
  13773. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13774. }
  13775. }
  13776. }
  13777. }
  13778. lightIndex++;
  13779. if (lightIndex === maxSimultaneousLights)
  13780. break;
  13781. }
  13782. }
  13783. if (StandardMaterial.FresnelEnabled) {
  13784. // Fresnel
  13785. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13786. var fresnelRank = 1;
  13787. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13788. defines.push("#define DIFFUSEFRESNEL");
  13789. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13790. fresnelRank++;
  13791. }
  13792. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13793. defines.push("#define OPACITYFRESNEL");
  13794. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13795. fresnelRank++;
  13796. }
  13797. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13798. defines.push("#define REFLECTIONFRESNEL");
  13799. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13800. fresnelRank++;
  13801. }
  13802. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13803. defines.push("#define EMISSIVEFRESNEL");
  13804. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13805. fresnelRank++;
  13806. }
  13807. defines.push("#define FRESNEL");
  13808. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13809. }
  13810. }
  13811. // Attribs
  13812. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13813. if (mesh) {
  13814. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13815. attribs.push(BABYLON.VertexBuffer.UVKind);
  13816. defines.push("#define UV1");
  13817. }
  13818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13819. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13820. defines.push("#define UV2");
  13821. }
  13822. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13823. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13824. defines.push("#define VERTEXCOLOR");
  13825. if (mesh.hasVertexAlpha) {
  13826. defines.push("#define VERTEXALPHA");
  13827. }
  13828. }
  13829. if (mesh.useBones) {
  13830. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13831. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13832. defines.push("#define BONES");
  13833. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13834. defines.push("#define BONES4");
  13835. fallbacks.addFallback(0, "BONES4");
  13836. }
  13837. // Instances
  13838. if (useInstances) {
  13839. defines.push("#define INSTANCES");
  13840. attribs.push("world0");
  13841. attribs.push("world1");
  13842. attribs.push("world2");
  13843. attribs.push("world3");
  13844. }
  13845. }
  13846. // Get correct effect
  13847. var join = defines.join("\n");
  13848. if (this._cachedDefines !== join) {
  13849. this._cachedDefines = join;
  13850. scene.resetCachedMaterial();
  13851. // Legacy browser patch
  13852. var shaderName = "default";
  13853. if (!scene.getEngine().getCaps().standardDerivatives) {
  13854. shaderName = "legacydefault";
  13855. }
  13856. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13857. }
  13858. if (!this._effect.isReady()) {
  13859. return false;
  13860. }
  13861. this._renderId = scene.getRenderId();
  13862. this._wasPreviouslyReady = true;
  13863. return true;
  13864. };
  13865. StandardMaterial.prototype.unbind = function () {
  13866. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13867. this._effect.setTexture("reflection2DSampler", null);
  13868. }
  13869. };
  13870. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13871. this._effect.setMatrix("world", world);
  13872. };
  13873. StandardMaterial.prototype.bind = function (world, mesh) {
  13874. var scene = this.getScene();
  13875. // Matrices
  13876. this.bindOnlyWorldMatrix(world);
  13877. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13878. // Bones
  13879. if (mesh.useBones) {
  13880. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13881. }
  13882. if (scene.getCachedMaterial() !== this) {
  13883. if (StandardMaterial.FresnelEnabled) {
  13884. // Fresnel
  13885. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13886. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13887. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13888. }
  13889. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13890. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13891. }
  13892. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13893. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13894. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13895. }
  13896. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13897. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13898. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13899. }
  13900. }
  13901. // Textures
  13902. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13903. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13904. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13905. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13906. }
  13907. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13908. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13909. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13910. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13911. }
  13912. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13913. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13914. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13915. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13916. }
  13917. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13918. if (this.reflectionTexture.isCube) {
  13919. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13920. }
  13921. else {
  13922. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13923. }
  13924. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13925. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13926. }
  13927. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13928. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13929. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13930. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13931. }
  13932. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13933. this._effect.setTexture("specularSampler", this.specularTexture);
  13934. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13935. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13936. }
  13937. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13938. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13939. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13940. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13941. }
  13942. // Clip plane
  13943. if (scene.clipPlane) {
  13944. var clipPlane = scene.clipPlane;
  13945. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13946. }
  13947. // Point size
  13948. if (this.pointsCloud) {
  13949. this._effect.setFloat("pointSize", this.pointSize);
  13950. }
  13951. // Colors
  13952. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13953. // Scaling down color according to emissive
  13954. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13955. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13956. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13957. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13958. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13959. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13960. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13961. }
  13962. // Scaling down color according to emissive
  13963. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13964. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13965. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13966. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13967. if (scene.lightsEnabled) {
  13968. var lightIndex = 0;
  13969. for (var index = 0; index < scene.lights.length; index++) {
  13970. var light = scene.lights[index];
  13971. if (!light.isEnabled()) {
  13972. continue;
  13973. }
  13974. if (!light.canAffectMesh(mesh)) {
  13975. continue;
  13976. }
  13977. if (light instanceof BABYLON.PointLight) {
  13978. // Point Light
  13979. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13980. }
  13981. else if (light instanceof BABYLON.DirectionalLight) {
  13982. // Directional Light
  13983. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13984. }
  13985. else if (light instanceof BABYLON.SpotLight) {
  13986. // Spot Light
  13987. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13988. }
  13989. else if (light instanceof BABYLON.HemisphericLight) {
  13990. // Hemispheric Light
  13991. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13992. }
  13993. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13994. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13995. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13996. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13997. // Shadows
  13998. if (scene.shadowsEnabled) {
  13999. var shadowGenerator = light.getShadowGenerator();
  14000. if (mesh.receiveShadows && shadowGenerator) {
  14001. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14002. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  14003. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  14004. }
  14005. }
  14006. lightIndex++;
  14007. if (lightIndex === maxSimultaneousLights)
  14008. break;
  14009. }
  14010. }
  14011. // View
  14012. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14013. this._effect.setMatrix("view", scene.getViewMatrix());
  14014. }
  14015. // Fog
  14016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14017. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14018. this._effect.setColor3("vFogColor", scene.fogColor);
  14019. }
  14020. _super.prototype.bind.call(this, world, mesh);
  14021. };
  14022. StandardMaterial.prototype.getAnimatables = function () {
  14023. var results = [];
  14024. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14025. results.push(this.diffuseTexture);
  14026. }
  14027. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14028. results.push(this.ambientTexture);
  14029. }
  14030. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14031. results.push(this.opacityTexture);
  14032. }
  14033. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14034. results.push(this.reflectionTexture);
  14035. }
  14036. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14037. results.push(this.emissiveTexture);
  14038. }
  14039. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14040. results.push(this.specularTexture);
  14041. }
  14042. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14043. results.push(this.bumpTexture);
  14044. }
  14045. return results;
  14046. };
  14047. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14048. if (this.diffuseTexture) {
  14049. this.diffuseTexture.dispose();
  14050. }
  14051. if (this.ambientTexture) {
  14052. this.ambientTexture.dispose();
  14053. }
  14054. if (this.opacityTexture) {
  14055. this.opacityTexture.dispose();
  14056. }
  14057. if (this.reflectionTexture) {
  14058. this.reflectionTexture.dispose();
  14059. }
  14060. if (this.emissiveTexture) {
  14061. this.emissiveTexture.dispose();
  14062. }
  14063. if (this.specularTexture) {
  14064. this.specularTexture.dispose();
  14065. }
  14066. if (this.bumpTexture) {
  14067. this.bumpTexture.dispose();
  14068. }
  14069. _super.prototype.dispose.call(this, forceDisposeEffect);
  14070. };
  14071. StandardMaterial.prototype.clone = function (name) {
  14072. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14073. // Base material
  14074. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14075. newStandardMaterial.alpha = this.alpha;
  14076. newStandardMaterial.fillMode = this.fillMode;
  14077. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14078. // Standard material
  14079. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14080. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14081. }
  14082. if (this.ambientTexture && this.ambientTexture.clone) {
  14083. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14084. }
  14085. if (this.opacityTexture && this.opacityTexture.clone) {
  14086. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14087. }
  14088. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14089. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14090. }
  14091. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14092. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14093. }
  14094. if (this.specularTexture && this.specularTexture.clone) {
  14095. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14096. }
  14097. if (this.bumpTexture && this.bumpTexture.clone) {
  14098. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14099. }
  14100. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14101. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14102. newStandardMaterial.specularColor = this.specularColor.clone();
  14103. newStandardMaterial.specularPower = this.specularPower;
  14104. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14105. return newStandardMaterial;
  14106. };
  14107. // Statics
  14108. // Flags used to enable or disable a type of texture for all Standard Materials
  14109. StandardMaterial.DiffuseTextureEnabled = true;
  14110. StandardMaterial.AmbientTextureEnabled = true;
  14111. StandardMaterial.OpacityTextureEnabled = true;
  14112. StandardMaterial.ReflectionTextureEnabled = true;
  14113. StandardMaterial.EmissiveTextureEnabled = true;
  14114. StandardMaterial.SpecularTextureEnabled = true;
  14115. StandardMaterial.BumpTextureEnabled = true;
  14116. StandardMaterial.FresnelEnabled = true;
  14117. return StandardMaterial;
  14118. })(BABYLON.Material);
  14119. BABYLON.StandardMaterial = StandardMaterial;
  14120. })(BABYLON || (BABYLON = {}));
  14121. //# sourceMappingURL=babylon.standardMaterial.js.map
  14122. var BABYLON;
  14123. (function (BABYLON) {
  14124. var MultiMaterial = (function (_super) {
  14125. __extends(MultiMaterial, _super);
  14126. function MultiMaterial(name, scene) {
  14127. _super.call(this, name, scene, true);
  14128. this.subMaterials = new Array();
  14129. scene.multiMaterials.push(this);
  14130. }
  14131. // Properties
  14132. MultiMaterial.prototype.getSubMaterial = function (index) {
  14133. if (index < 0 || index >= this.subMaterials.length) {
  14134. return this.getScene().defaultMaterial;
  14135. }
  14136. return this.subMaterials[index];
  14137. };
  14138. // Methods
  14139. MultiMaterial.prototype.isReady = function (mesh) {
  14140. for (var index = 0; index < this.subMaterials.length; index++) {
  14141. var subMaterial = this.subMaterials[index];
  14142. if (subMaterial) {
  14143. if (!this.subMaterials[index].isReady(mesh)) {
  14144. return false;
  14145. }
  14146. }
  14147. }
  14148. return true;
  14149. };
  14150. return MultiMaterial;
  14151. })(BABYLON.Material);
  14152. BABYLON.MultiMaterial = MultiMaterial;
  14153. })(BABYLON || (BABYLON = {}));
  14154. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14155. (function (BABYLON) {
  14156. var Database = (function () {
  14157. function Database(urlToScene, callbackManifestChecked) {
  14158. // Handling various flavors of prefixed version of IndexedDB
  14159. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14160. this.callbackManifestChecked = callbackManifestChecked;
  14161. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14162. this.db = null;
  14163. this.enableSceneOffline = false;
  14164. this.enableTexturesOffline = false;
  14165. this.manifestVersionFound = 0;
  14166. this.mustUpdateRessources = false;
  14167. this.hasReachedQuota = false;
  14168. this.checkManifestFile();
  14169. }
  14170. Database.prototype.checkManifestFile = function () {
  14171. var _this = this;
  14172. function noManifestFile() {
  14173. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14174. that.enableSceneOffline = false;
  14175. that.enableTexturesOffline = false;
  14176. that.callbackManifestChecked(false);
  14177. }
  14178. var that = this;
  14179. var manifestURL = this.currentSceneUrl + ".manifest";
  14180. var xhr = new XMLHttpRequest();
  14181. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14182. xhr.open("GET", manifestURLTimeStamped, true);
  14183. xhr.addEventListener("load", function () {
  14184. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14185. try {
  14186. var manifestFile = JSON.parse(xhr.response);
  14187. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14188. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14189. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14190. _this.manifestVersionFound = manifestFile.version;
  14191. }
  14192. if (_this.callbackManifestChecked) {
  14193. _this.callbackManifestChecked(true);
  14194. }
  14195. }
  14196. catch (ex) {
  14197. noManifestFile();
  14198. }
  14199. }
  14200. else {
  14201. noManifestFile();
  14202. }
  14203. }, false);
  14204. xhr.addEventListener("error", function (event) {
  14205. noManifestFile();
  14206. }, false);
  14207. try {
  14208. xhr.send();
  14209. }
  14210. catch (ex) {
  14211. BABYLON.Tools.Error("Error on XHR send request.");
  14212. that.callbackManifestChecked(false);
  14213. }
  14214. };
  14215. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14216. var _this = this;
  14217. function handleError() {
  14218. that.isSupported = false;
  14219. if (errorCallback)
  14220. errorCallback();
  14221. }
  14222. var that = this;
  14223. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14224. // Your browser doesn't support IndexedDB
  14225. this.isSupported = false;
  14226. if (errorCallback)
  14227. errorCallback();
  14228. }
  14229. else {
  14230. // If the DB hasn't been opened or created yet
  14231. if (!this.db) {
  14232. this.hasReachedQuota = false;
  14233. this.isSupported = true;
  14234. var request = this.idbFactory.open("babylonjs", 1);
  14235. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14236. request.onerror = function (event) {
  14237. handleError();
  14238. };
  14239. // executes when a version change transaction cannot complete due to other active transactions
  14240. request.onblocked = function (event) {
  14241. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14242. handleError();
  14243. };
  14244. // DB has been opened successfully
  14245. request.onsuccess = function (event) {
  14246. _this.db = request.result;
  14247. successCallback();
  14248. };
  14249. // Initialization of the DB. Creating Scenes & Textures stores
  14250. request.onupgradeneeded = function (event) {
  14251. _this.db = (event.target).result;
  14252. try {
  14253. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14254. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14255. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14256. }
  14257. catch (ex) {
  14258. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14259. handleError();
  14260. }
  14261. };
  14262. }
  14263. else {
  14264. if (successCallback)
  14265. successCallback();
  14266. }
  14267. }
  14268. };
  14269. Database.prototype.loadImageFromDB = function (url, image) {
  14270. var _this = this;
  14271. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14272. var saveAndLoadImage = function () {
  14273. if (!_this.hasReachedQuota && _this.db !== null) {
  14274. // the texture is not yet in the DB, let's try to save it
  14275. _this._saveImageIntoDBAsync(completeURL, image);
  14276. }
  14277. else {
  14278. image.src = url;
  14279. }
  14280. };
  14281. if (!this.mustUpdateRessources) {
  14282. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14283. }
  14284. else {
  14285. saveAndLoadImage();
  14286. }
  14287. };
  14288. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14289. if (this.isSupported && this.db !== null) {
  14290. var texture;
  14291. var transaction = this.db.transaction(["textures"]);
  14292. transaction.onabort = function (event) {
  14293. image.src = url;
  14294. };
  14295. transaction.oncomplete = function (event) {
  14296. var blobTextureURL;
  14297. if (texture) {
  14298. var URL = window.URL || window.webkitURL;
  14299. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14300. image.onerror = function () {
  14301. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14302. image.src = url;
  14303. };
  14304. image.src = blobTextureURL;
  14305. }
  14306. else {
  14307. notInDBCallback();
  14308. }
  14309. };
  14310. var getRequest = transaction.objectStore("textures").get(url);
  14311. getRequest.onsuccess = function (event) {
  14312. texture = (event.target).result;
  14313. };
  14314. getRequest.onerror = function (event) {
  14315. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14316. image.src = url;
  14317. };
  14318. }
  14319. else {
  14320. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14321. image.src = url;
  14322. }
  14323. };
  14324. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14325. var _this = this;
  14326. if (this.isSupported) {
  14327. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14328. var generateBlobUrl = function () {
  14329. var blobTextureURL;
  14330. if (blob) {
  14331. var URL = window.URL || window.webkitURL;
  14332. try {
  14333. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14334. }
  14335. catch (ex) {
  14336. blobTextureURL = URL.createObjectURL(blob);
  14337. }
  14338. }
  14339. image.src = blobTextureURL;
  14340. };
  14341. if (BABYLON.Database.isUASupportingBlobStorage) {
  14342. var xhr = new XMLHttpRequest(), blob;
  14343. xhr.open("GET", url, true);
  14344. xhr.responseType = "blob";
  14345. xhr.addEventListener("load", function () {
  14346. if (xhr.status === 200) {
  14347. // Blob as response (XHR2)
  14348. blob = xhr.response;
  14349. var transaction = _this.db.transaction(["textures"], "readwrite");
  14350. // the transaction could abort because of a QuotaExceededError error
  14351. transaction.onabort = function (event) {
  14352. try {
  14353. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14354. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14355. this.hasReachedQuota = true;
  14356. }
  14357. }
  14358. catch (ex) {
  14359. }
  14360. generateBlobUrl();
  14361. };
  14362. transaction.oncomplete = function (event) {
  14363. generateBlobUrl();
  14364. };
  14365. var newTexture = { textureUrl: url, data: blob };
  14366. try {
  14367. // Put the blob into the dabase
  14368. var addRequest = transaction.objectStore("textures").put(newTexture);
  14369. addRequest.onsuccess = function (event) {
  14370. };
  14371. addRequest.onerror = function (event) {
  14372. generateBlobUrl();
  14373. };
  14374. }
  14375. catch (ex) {
  14376. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14377. if (ex.code === 25) {
  14378. BABYLON.Database.isUASupportingBlobStorage = false;
  14379. }
  14380. image.src = url;
  14381. }
  14382. }
  14383. else {
  14384. image.src = url;
  14385. }
  14386. }, false);
  14387. xhr.addEventListener("error", function (event) {
  14388. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14389. image.src = url;
  14390. }, false);
  14391. xhr.send();
  14392. }
  14393. else {
  14394. image.src = url;
  14395. }
  14396. }
  14397. else {
  14398. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14399. image.src = url;
  14400. }
  14401. };
  14402. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14403. var _this = this;
  14404. var updateVersion = function (event) {
  14405. // the version is not yet in the DB or we need to update it
  14406. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14407. };
  14408. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14409. };
  14410. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14411. var _this = this;
  14412. if (this.isSupported) {
  14413. var version;
  14414. try {
  14415. var transaction = this.db.transaction(["versions"]);
  14416. transaction.oncomplete = function (event) {
  14417. if (version) {
  14418. // If the version in the JSON file is > than the version in DB
  14419. if (_this.manifestVersionFound > version.data) {
  14420. _this.mustUpdateRessources = true;
  14421. updateInDBCallback();
  14422. }
  14423. else {
  14424. callback(version.data);
  14425. }
  14426. }
  14427. else {
  14428. _this.mustUpdateRessources = true;
  14429. updateInDBCallback();
  14430. }
  14431. };
  14432. transaction.onabort = function (event) {
  14433. callback(-1);
  14434. };
  14435. var getRequest = transaction.objectStore("versions").get(url);
  14436. getRequest.onsuccess = function (event) {
  14437. version = (event.target).result;
  14438. };
  14439. getRequest.onerror = function (event) {
  14440. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14441. callback(-1);
  14442. };
  14443. }
  14444. catch (ex) {
  14445. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14446. callback(-1);
  14447. }
  14448. }
  14449. else {
  14450. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14451. callback(-1);
  14452. }
  14453. };
  14454. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14455. var _this = this;
  14456. if (this.isSupported && !this.hasReachedQuota) {
  14457. try {
  14458. // Open a transaction to the database
  14459. var transaction = this.db.transaction(["versions"], "readwrite");
  14460. // the transaction could abort because of a QuotaExceededError error
  14461. transaction.onabort = function (event) {
  14462. try {
  14463. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14464. _this.hasReachedQuota = true;
  14465. }
  14466. }
  14467. catch (ex) {
  14468. }
  14469. callback(-1);
  14470. };
  14471. transaction.oncomplete = function (event) {
  14472. callback(_this.manifestVersionFound);
  14473. };
  14474. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14475. // Put the scene into the database
  14476. var addRequest = transaction.objectStore("versions").put(newVersion);
  14477. addRequest.onsuccess = function (event) {
  14478. };
  14479. addRequest.onerror = function (event) {
  14480. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14481. };
  14482. }
  14483. catch (ex) {
  14484. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14485. callback(-1);
  14486. }
  14487. }
  14488. else {
  14489. callback(-1);
  14490. }
  14491. };
  14492. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14493. var _this = this;
  14494. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14495. var saveAndLoadFile = function (event) {
  14496. // the scene is not yet in the DB, let's try to save it
  14497. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14498. };
  14499. this._checkVersionFromDB(completeUrl, function (version) {
  14500. if (version !== -1) {
  14501. if (!_this.mustUpdateRessources) {
  14502. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14503. }
  14504. else {
  14505. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14506. }
  14507. }
  14508. else {
  14509. errorCallback();
  14510. }
  14511. });
  14512. };
  14513. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14514. if (this.isSupported) {
  14515. var targetStore;
  14516. if (url.indexOf(".babylon") !== -1) {
  14517. targetStore = "scenes";
  14518. }
  14519. else {
  14520. targetStore = "textures";
  14521. }
  14522. var file;
  14523. var transaction = this.db.transaction([targetStore]);
  14524. transaction.oncomplete = function (event) {
  14525. if (file) {
  14526. callback(file.data);
  14527. }
  14528. else {
  14529. notInDBCallback();
  14530. }
  14531. };
  14532. transaction.onabort = function (event) {
  14533. notInDBCallback();
  14534. };
  14535. var getRequest = transaction.objectStore(targetStore).get(url);
  14536. getRequest.onsuccess = function (event) {
  14537. file = (event.target).result;
  14538. };
  14539. getRequest.onerror = function (event) {
  14540. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14541. notInDBCallback();
  14542. };
  14543. }
  14544. else {
  14545. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14546. callback();
  14547. }
  14548. };
  14549. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14550. var _this = this;
  14551. if (this.isSupported) {
  14552. var targetStore;
  14553. if (url.indexOf(".babylon") !== -1) {
  14554. targetStore = "scenes";
  14555. }
  14556. else {
  14557. targetStore = "textures";
  14558. }
  14559. // Create XHR
  14560. var xhr = new XMLHttpRequest(), fileData;
  14561. xhr.open("GET", url, true);
  14562. if (useArrayBuffer) {
  14563. xhr.responseType = "arraybuffer";
  14564. }
  14565. xhr.onprogress = progressCallback;
  14566. xhr.addEventListener("load", function () {
  14567. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14568. // Blob as response (XHR2)
  14569. //fileData = xhr.responseText;
  14570. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14571. if (!_this.hasReachedQuota) {
  14572. // Open a transaction to the database
  14573. var transaction = _this.db.transaction([targetStore], "readwrite");
  14574. // the transaction could abort because of a QuotaExceededError error
  14575. transaction.onabort = function (event) {
  14576. try {
  14577. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14578. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14579. this.hasReachedQuota = true;
  14580. }
  14581. }
  14582. catch (ex) {
  14583. }
  14584. callback(fileData);
  14585. };
  14586. transaction.oncomplete = function (event) {
  14587. callback(fileData);
  14588. };
  14589. var newFile;
  14590. if (targetStore === "scenes") {
  14591. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14592. }
  14593. else {
  14594. newFile = { textureUrl: url, data: fileData };
  14595. }
  14596. try {
  14597. // Put the scene into the database
  14598. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14599. addRequest.onsuccess = function (event) {
  14600. };
  14601. addRequest.onerror = function (event) {
  14602. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14603. };
  14604. }
  14605. catch (ex) {
  14606. callback(fileData);
  14607. }
  14608. }
  14609. else {
  14610. callback(fileData);
  14611. }
  14612. }
  14613. else {
  14614. callback();
  14615. }
  14616. }, false);
  14617. xhr.addEventListener("error", function (event) {
  14618. BABYLON.Tools.Error("error on XHR request.");
  14619. callback();
  14620. }, false);
  14621. xhr.send();
  14622. }
  14623. else {
  14624. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14625. callback();
  14626. }
  14627. };
  14628. Database.isUASupportingBlobStorage = true;
  14629. Database.parseURL = function (url) {
  14630. var a = document.createElement('a');
  14631. a.href = url;
  14632. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14633. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14634. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14635. return absLocation;
  14636. };
  14637. Database.ReturnFullUrlLocation = function (url) {
  14638. if (url.indexOf("http:/") === -1) {
  14639. return (BABYLON.Database.parseURL(window.location.href) + url);
  14640. }
  14641. else {
  14642. return url;
  14643. }
  14644. };
  14645. return Database;
  14646. })();
  14647. BABYLON.Database = Database;
  14648. })(BABYLON || (BABYLON = {}));
  14649. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14650. (function (BABYLON) {
  14651. var SpriteManager = (function () {
  14652. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14653. this.name = name;
  14654. this.cellSize = cellSize;
  14655. this.sprites = new Array();
  14656. this.renderingGroupId = 0;
  14657. this.fogEnabled = true;
  14658. this._vertexDeclaration = [3, 4, 4, 4];
  14659. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14660. this._capacity = capacity;
  14661. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14662. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14663. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14664. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14665. this._scene = scene;
  14666. this._scene.spriteManagers.push(this);
  14667. // VBO
  14668. this._vertexDeclaration = [3, 4, 4, 4];
  14669. this._vertexStrideSize = 15 * 4;
  14670. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14671. var indices = [];
  14672. var index = 0;
  14673. for (var count = 0; count < capacity; count++) {
  14674. indices.push(index);
  14675. indices.push(index + 1);
  14676. indices.push(index + 2);
  14677. indices.push(index);
  14678. indices.push(index + 2);
  14679. indices.push(index + 3);
  14680. index += 4;
  14681. }
  14682. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14683. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14684. // Effects
  14685. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14686. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14687. }
  14688. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14689. var arrayOffset = index * 15;
  14690. if (offsetX == 0)
  14691. offsetX = this._epsilon;
  14692. else if (offsetX == 1)
  14693. offsetX = 1 - this._epsilon;
  14694. if (offsetY == 0)
  14695. offsetY = this._epsilon;
  14696. else if (offsetY == 1)
  14697. offsetY = 1 - this._epsilon;
  14698. this._vertices[arrayOffset] = sprite.position.x;
  14699. this._vertices[arrayOffset + 1] = sprite.position.y;
  14700. this._vertices[arrayOffset + 2] = sprite.position.z;
  14701. this._vertices[arrayOffset + 3] = sprite.angle;
  14702. this._vertices[arrayOffset + 4] = sprite.size;
  14703. this._vertices[arrayOffset + 5] = offsetX;
  14704. this._vertices[arrayOffset + 6] = offsetY;
  14705. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14706. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14707. var offset = (sprite.cellIndex / rowSize) >> 0;
  14708. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14709. this._vertices[arrayOffset + 10] = offset;
  14710. // Color
  14711. this._vertices[arrayOffset + 11] = sprite.color.r;
  14712. this._vertices[arrayOffset + 12] = sprite.color.g;
  14713. this._vertices[arrayOffset + 13] = sprite.color.b;
  14714. this._vertices[arrayOffset + 14] = sprite.color.a;
  14715. };
  14716. SpriteManager.prototype.render = function () {
  14717. // Check
  14718. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14719. return;
  14720. var engine = this._scene.getEngine();
  14721. var baseSize = this._spriteTexture.getBaseSize();
  14722. // Sprites
  14723. var deltaTime = engine.getDeltaTime();
  14724. var max = Math.min(this._capacity, this.sprites.length);
  14725. var rowSize = baseSize.width / this.cellSize;
  14726. var offset = 0;
  14727. for (var index = 0; index < max; index++) {
  14728. var sprite = this.sprites[index];
  14729. if (!sprite) {
  14730. continue;
  14731. }
  14732. sprite._animate(deltaTime);
  14733. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14734. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14735. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14736. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14737. }
  14738. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14739. // Render
  14740. var effect = this._effectBase;
  14741. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14742. effect = this._effectFog;
  14743. }
  14744. engine.enableEffect(effect);
  14745. var viewMatrix = this._scene.getViewMatrix();
  14746. effect.setTexture("diffuseSampler", this._spriteTexture);
  14747. effect.setMatrix("view", viewMatrix);
  14748. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14749. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14750. // Fog
  14751. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14752. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14753. effect.setColor3("vFogColor", this._scene.fogColor);
  14754. }
  14755. // VBOs
  14756. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14757. // Draw order
  14758. effect.setBool("alphaTest", true);
  14759. engine.setColorWrite(false);
  14760. engine.draw(true, 0, max * 6);
  14761. engine.setColorWrite(true);
  14762. effect.setBool("alphaTest", false);
  14763. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14764. engine.draw(true, 0, max * 6);
  14765. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14766. };
  14767. SpriteManager.prototype.dispose = function () {
  14768. if (this._vertexBuffer) {
  14769. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14770. this._vertexBuffer = null;
  14771. }
  14772. if (this._indexBuffer) {
  14773. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14774. this._indexBuffer = null;
  14775. }
  14776. if (this._spriteTexture) {
  14777. this._spriteTexture.dispose();
  14778. this._spriteTexture = null;
  14779. }
  14780. // Remove from scene
  14781. var index = this._scene.spriteManagers.indexOf(this);
  14782. this._scene.spriteManagers.splice(index, 1);
  14783. // Callback
  14784. if (this.onDispose) {
  14785. this.onDispose();
  14786. }
  14787. };
  14788. return SpriteManager;
  14789. })();
  14790. BABYLON.SpriteManager = SpriteManager;
  14791. })(BABYLON || (BABYLON = {}));
  14792. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14793. (function (BABYLON) {
  14794. var Sprite = (function () {
  14795. function Sprite(name, manager) {
  14796. this.name = name;
  14797. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14798. this.size = 1.0;
  14799. this.angle = 0;
  14800. this.cellIndex = 0;
  14801. this.invertU = 0;
  14802. this.invertV = 0;
  14803. this.animations = new Array();
  14804. this._animationStarted = false;
  14805. this._loopAnimation = false;
  14806. this._fromIndex = 0;
  14807. this._toIndex = 0;
  14808. this._delay = 0;
  14809. this._direction = 1;
  14810. this._frameCount = 0;
  14811. this._time = 0;
  14812. this._manager = manager;
  14813. this._manager.sprites.push(this);
  14814. this.position = BABYLON.Vector3.Zero();
  14815. }
  14816. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14817. this._fromIndex = from;
  14818. this._toIndex = to;
  14819. this._loopAnimation = loop;
  14820. this._delay = delay;
  14821. this._animationStarted = true;
  14822. this._direction = from < to ? 1 : -1;
  14823. this.cellIndex = from;
  14824. this._time = 0;
  14825. };
  14826. Sprite.prototype.stopAnimation = function () {
  14827. this._animationStarted = false;
  14828. };
  14829. Sprite.prototype._animate = function (deltaTime) {
  14830. if (!this._animationStarted)
  14831. return;
  14832. this._time += deltaTime;
  14833. if (this._time > this._delay) {
  14834. this._time = this._time % this._delay;
  14835. this.cellIndex += this._direction;
  14836. if (this.cellIndex == this._toIndex) {
  14837. if (this._loopAnimation) {
  14838. this.cellIndex = this._fromIndex;
  14839. }
  14840. else {
  14841. this._animationStarted = false;
  14842. if (this.disposeWhenFinishedAnimating) {
  14843. this.dispose();
  14844. }
  14845. }
  14846. }
  14847. }
  14848. };
  14849. Sprite.prototype.dispose = function () {
  14850. for (var i = 0; i < this._manager.sprites.length; i++) {
  14851. if (this._manager.sprites[i] == this) {
  14852. this._manager.sprites.splice(i, 1);
  14853. }
  14854. }
  14855. };
  14856. return Sprite;
  14857. })();
  14858. BABYLON.Sprite = Sprite;
  14859. })(BABYLON || (BABYLON = {}));
  14860. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14861. (function (BABYLON) {
  14862. var Layer = (function () {
  14863. function Layer(name, imgUrl, scene, isBackground, color) {
  14864. this.name = name;
  14865. this._vertexDeclaration = [2];
  14866. this._vertexStrideSize = 2 * 4;
  14867. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14868. this.isBackground = isBackground === undefined ? true : isBackground;
  14869. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14870. this._scene = scene;
  14871. this._scene.layers.push(this);
  14872. // VBO
  14873. var vertices = [];
  14874. vertices.push(1, 1);
  14875. vertices.push(-1, 1);
  14876. vertices.push(-1, -1);
  14877. vertices.push(1, -1);
  14878. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14879. // Indices
  14880. var indices = [];
  14881. indices.push(0);
  14882. indices.push(1);
  14883. indices.push(2);
  14884. indices.push(0);
  14885. indices.push(2);
  14886. indices.push(3);
  14887. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14888. // Effects
  14889. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14890. }
  14891. Layer.prototype.render = function () {
  14892. // Check
  14893. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14894. return;
  14895. var engine = this._scene.getEngine();
  14896. // Render
  14897. engine.enableEffect(this._effect);
  14898. engine.setState(false);
  14899. // Texture
  14900. this._effect.setTexture("textureSampler", this.texture);
  14901. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14902. // Color
  14903. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14904. // VBOs
  14905. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14906. // Draw order
  14907. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14908. engine.draw(true, 0, 6);
  14909. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14910. };
  14911. Layer.prototype.dispose = function () {
  14912. if (this._vertexBuffer) {
  14913. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14914. this._vertexBuffer = null;
  14915. }
  14916. if (this._indexBuffer) {
  14917. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14918. this._indexBuffer = null;
  14919. }
  14920. if (this.texture) {
  14921. this.texture.dispose();
  14922. this.texture = null;
  14923. }
  14924. // Remove from scene
  14925. var index = this._scene.layers.indexOf(this);
  14926. this._scene.layers.splice(index, 1);
  14927. // Callback
  14928. if (this.onDispose) {
  14929. this.onDispose();
  14930. }
  14931. };
  14932. return Layer;
  14933. })();
  14934. BABYLON.Layer = Layer;
  14935. })(BABYLON || (BABYLON = {}));
  14936. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14937. (function (BABYLON) {
  14938. var Particle = (function () {
  14939. function Particle() {
  14940. this.position = BABYLON.Vector3.Zero();
  14941. this.direction = BABYLON.Vector3.Zero();
  14942. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14943. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14944. this.lifeTime = 1.0;
  14945. this.age = 0;
  14946. this.size = 0;
  14947. this.angle = 0;
  14948. this.angularSpeed = 0;
  14949. }
  14950. Particle.prototype.copyTo = function (other) {
  14951. other.position.copyFrom(this.position);
  14952. other.direction.copyFrom(this.direction);
  14953. other.color.copyFrom(this.color);
  14954. other.colorStep.copyFrom(this.colorStep);
  14955. other.lifeTime = this.lifeTime;
  14956. other.age = this.age;
  14957. other.size = this.size;
  14958. other.angle = this.angle;
  14959. other.angularSpeed = this.angularSpeed;
  14960. };
  14961. return Particle;
  14962. })();
  14963. BABYLON.Particle = Particle;
  14964. })(BABYLON || (BABYLON = {}));
  14965. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14966. (function (BABYLON) {
  14967. var randomNumber = function (min, max) {
  14968. if (min === max) {
  14969. return (min);
  14970. }
  14971. var random = Math.random();
  14972. return ((random * (max - min)) + min);
  14973. };
  14974. var ParticleSystem = (function () {
  14975. function ParticleSystem(name, capacity, scene, customEffect) {
  14976. var _this = this;
  14977. this.name = name;
  14978. this.renderingGroupId = 0;
  14979. this.emitter = null;
  14980. this.emitRate = 10;
  14981. this.manualEmitCount = -1;
  14982. this.updateSpeed = 0.01;
  14983. this.targetStopDuration = 0;
  14984. this.disposeOnStop = false;
  14985. this.minEmitPower = 1;
  14986. this.maxEmitPower = 1;
  14987. this.minLifeTime = 1;
  14988. this.maxLifeTime = 1;
  14989. this.minSize = 1;
  14990. this.maxSize = 1;
  14991. this.minAngularSpeed = 0;
  14992. this.maxAngularSpeed = 0;
  14993. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14994. this.forceDepthWrite = false;
  14995. this.gravity = BABYLON.Vector3.Zero();
  14996. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14997. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14998. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14999. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15000. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15001. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15002. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15003. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15004. this.particles = new Array();
  15005. this._vertexDeclaration = [3, 4, 4];
  15006. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15007. this._stockParticles = new Array();
  15008. this._newPartsExcess = 0;
  15009. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15010. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15011. this._scaledDirection = BABYLON.Vector3.Zero();
  15012. this._scaledGravity = BABYLON.Vector3.Zero();
  15013. this._currentRenderId = -1;
  15014. this._started = false;
  15015. this._stopped = false;
  15016. this._actualFrame = 0;
  15017. this.id = name;
  15018. this._capacity = capacity;
  15019. this._scene = scene;
  15020. this._customEffect = customEffect;
  15021. scene.particleSystems.push(this);
  15022. // VBO
  15023. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15024. var indices = [];
  15025. var index = 0;
  15026. for (var count = 0; count < capacity; count++) {
  15027. indices.push(index);
  15028. indices.push(index + 1);
  15029. indices.push(index + 2);
  15030. indices.push(index);
  15031. indices.push(index + 2);
  15032. indices.push(index + 3);
  15033. index += 4;
  15034. }
  15035. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15036. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15037. // Default behaviors
  15038. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15039. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15040. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15041. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15042. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15043. };
  15044. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15045. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15046. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15047. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15048. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15049. };
  15050. this.updateFunction = function (particles) {
  15051. for (var index = 0; index < particles.length; index++) {
  15052. var particle = particles[index];
  15053. particle.age += _this._scaledUpdateSpeed;
  15054. if (particle.age >= particle.lifeTime) {
  15055. _this.recycleParticle(particle);
  15056. index--;
  15057. continue;
  15058. }
  15059. else {
  15060. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15061. particle.color.addInPlace(_this._scaledColorStep);
  15062. if (particle.color.a < 0)
  15063. particle.color.a = 0;
  15064. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15065. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15066. particle.position.addInPlace(_this._scaledDirection);
  15067. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15068. particle.direction.addInPlace(_this._scaledGravity);
  15069. }
  15070. }
  15071. };
  15072. }
  15073. ParticleSystem.prototype.recycleParticle = function (particle) {
  15074. var lastParticle = this.particles.pop();
  15075. if (lastParticle !== particle) {
  15076. lastParticle.copyTo(particle);
  15077. this._stockParticles.push(lastParticle);
  15078. }
  15079. };
  15080. ParticleSystem.prototype.getCapacity = function () {
  15081. return this._capacity;
  15082. };
  15083. ParticleSystem.prototype.isAlive = function () {
  15084. return this._alive;
  15085. };
  15086. ParticleSystem.prototype.isStarted = function () {
  15087. return this._started;
  15088. };
  15089. ParticleSystem.prototype.start = function () {
  15090. this._started = true;
  15091. this._stopped = false;
  15092. this._actualFrame = 0;
  15093. };
  15094. ParticleSystem.prototype.stop = function () {
  15095. this._stopped = true;
  15096. };
  15097. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15098. var offset = index * 11;
  15099. this._vertices[offset] = particle.position.x;
  15100. this._vertices[offset + 1] = particle.position.y;
  15101. this._vertices[offset + 2] = particle.position.z;
  15102. this._vertices[offset + 3] = particle.color.r;
  15103. this._vertices[offset + 4] = particle.color.g;
  15104. this._vertices[offset + 5] = particle.color.b;
  15105. this._vertices[offset + 6] = particle.color.a;
  15106. this._vertices[offset + 7] = particle.angle;
  15107. this._vertices[offset + 8] = particle.size;
  15108. this._vertices[offset + 9] = offsetX;
  15109. this._vertices[offset + 10] = offsetY;
  15110. };
  15111. ParticleSystem.prototype._update = function (newParticles) {
  15112. // Update current
  15113. this._alive = this.particles.length > 0;
  15114. this.updateFunction(this.particles);
  15115. // Add new ones
  15116. var worldMatrix;
  15117. if (this.emitter.position) {
  15118. worldMatrix = this.emitter.getWorldMatrix();
  15119. }
  15120. else {
  15121. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15122. }
  15123. for (var index = 0; index < newParticles; index++) {
  15124. if (this.particles.length === this._capacity) {
  15125. break;
  15126. }
  15127. if (this._stockParticles.length !== 0) {
  15128. var particle = this._stockParticles.pop();
  15129. particle.age = 0;
  15130. }
  15131. else {
  15132. particle = new BABYLON.Particle();
  15133. }
  15134. this.particles.push(particle);
  15135. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15136. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15137. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15138. particle.size = randomNumber(this.minSize, this.maxSize);
  15139. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15140. this.startPositionFunction(worldMatrix, particle.position);
  15141. var step = randomNumber(0, 1.0);
  15142. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15143. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15144. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15145. }
  15146. };
  15147. ParticleSystem.prototype._getEffect = function () {
  15148. if (this._customEffect) {
  15149. return this._customEffect;
  15150. }
  15151. ;
  15152. var defines = [];
  15153. if (this._scene.clipPlane) {
  15154. defines.push("#define CLIPPLANE");
  15155. }
  15156. // Effect
  15157. var join = defines.join("\n");
  15158. if (this._cachedDefines !== join) {
  15159. this._cachedDefines = join;
  15160. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15161. }
  15162. return this._effect;
  15163. };
  15164. ParticleSystem.prototype.animate = function () {
  15165. if (!this._started)
  15166. return;
  15167. var effect = this._getEffect();
  15168. // Check
  15169. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15170. return;
  15171. if (this._currentRenderId === this._scene.getRenderId()) {
  15172. return;
  15173. }
  15174. this._currentRenderId = this._scene.getRenderId();
  15175. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15176. // determine the number of particles we need to create
  15177. var emitCout;
  15178. if (this.manualEmitCount > -1) {
  15179. emitCout = this.manualEmitCount;
  15180. this.manualEmitCount = 0;
  15181. }
  15182. else {
  15183. emitCout = this.emitRate;
  15184. }
  15185. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15186. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15187. if (this._newPartsExcess > 1.0) {
  15188. newParticles += this._newPartsExcess >> 0;
  15189. this._newPartsExcess -= this._newPartsExcess >> 0;
  15190. }
  15191. this._alive = false;
  15192. if (!this._stopped) {
  15193. this._actualFrame += this._scaledUpdateSpeed;
  15194. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15195. this.stop();
  15196. }
  15197. else {
  15198. newParticles = 0;
  15199. }
  15200. this._update(newParticles);
  15201. // Stopped?
  15202. if (this._stopped) {
  15203. if (!this._alive) {
  15204. this._started = false;
  15205. if (this.disposeOnStop) {
  15206. this._scene._toBeDisposed.push(this);
  15207. }
  15208. }
  15209. }
  15210. // Update VBO
  15211. var offset = 0;
  15212. for (var index = 0; index < this.particles.length; index++) {
  15213. var particle = this.particles[index];
  15214. this._appendParticleVertex(offset++, particle, 0, 0);
  15215. this._appendParticleVertex(offset++, particle, 1, 0);
  15216. this._appendParticleVertex(offset++, particle, 1, 1);
  15217. this._appendParticleVertex(offset++, particle, 0, 1);
  15218. }
  15219. var engine = this._scene.getEngine();
  15220. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15221. };
  15222. ParticleSystem.prototype.render = function () {
  15223. var effect = this._getEffect();
  15224. // Check
  15225. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15226. return 0;
  15227. var engine = this._scene.getEngine();
  15228. // Render
  15229. engine.enableEffect(effect);
  15230. engine.setState(false);
  15231. var viewMatrix = this._scene.getViewMatrix();
  15232. effect.setTexture("diffuseSampler", this.particleTexture);
  15233. effect.setMatrix("view", viewMatrix);
  15234. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15235. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15236. if (this._scene.clipPlane) {
  15237. var clipPlane = this._scene.clipPlane;
  15238. var invView = viewMatrix.clone();
  15239. invView.invert();
  15240. effect.setMatrix("invView", invView);
  15241. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15242. }
  15243. // VBOs
  15244. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15245. // Draw order
  15246. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15247. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15248. }
  15249. else {
  15250. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15251. }
  15252. if (this.forceDepthWrite) {
  15253. engine.setDepthWrite(true);
  15254. }
  15255. engine.draw(true, 0, this.particles.length * 6);
  15256. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15257. return this.particles.length;
  15258. };
  15259. ParticleSystem.prototype.dispose = function () {
  15260. if (this._vertexBuffer) {
  15261. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15262. this._vertexBuffer = null;
  15263. }
  15264. if (this._indexBuffer) {
  15265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15266. this._indexBuffer = null;
  15267. }
  15268. if (this.particleTexture) {
  15269. this.particleTexture.dispose();
  15270. this.particleTexture = null;
  15271. }
  15272. // Remove from scene
  15273. var index = this._scene.particleSystems.indexOf(this);
  15274. this._scene.particleSystems.splice(index, 1);
  15275. // Callback
  15276. if (this.onDispose) {
  15277. this.onDispose();
  15278. }
  15279. };
  15280. // Clone
  15281. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15282. var result = new ParticleSystem(name, this._capacity, this._scene);
  15283. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15284. if (newEmitter === undefined) {
  15285. newEmitter = this.emitter;
  15286. }
  15287. result.emitter = newEmitter;
  15288. if (this.particleTexture) {
  15289. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15290. }
  15291. result.start();
  15292. return result;
  15293. };
  15294. // Statics
  15295. ParticleSystem.BLENDMODE_ONEONE = 0;
  15296. ParticleSystem.BLENDMODE_STANDARD = 1;
  15297. return ParticleSystem;
  15298. })();
  15299. BABYLON.ParticleSystem = ParticleSystem;
  15300. })(BABYLON || (BABYLON = {}));
  15301. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15302. (function (BABYLON) {
  15303. var Animation = (function () {
  15304. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15305. this.name = name;
  15306. this.targetProperty = targetProperty;
  15307. this.framePerSecond = framePerSecond;
  15308. this.dataType = dataType;
  15309. this.loopMode = loopMode;
  15310. this._offsetsCache = {};
  15311. this._highLimitsCache = {};
  15312. this._stopped = false;
  15313. this.targetPropertyPath = targetProperty.split(".");
  15314. this.dataType = dataType;
  15315. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15316. }
  15317. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15318. var dataType = undefined;
  15319. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15320. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15321. }
  15322. else if (from instanceof BABYLON.Quaternion) {
  15323. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15324. }
  15325. else if (from instanceof BABYLON.Vector3) {
  15326. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15327. }
  15328. else if (from instanceof BABYLON.Vector2) {
  15329. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15330. }
  15331. else if (from instanceof BABYLON.Color3) {
  15332. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15333. }
  15334. if (dataType == undefined) {
  15335. return;
  15336. }
  15337. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15338. var keys = [];
  15339. keys.push({ frame: 0, value: from });
  15340. keys.push({ frame: totalFrame, value: to });
  15341. animation.setKeys(keys);
  15342. mesh.animations.push(animation);
  15343. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15344. };
  15345. // Methods
  15346. Animation.prototype.isStopped = function () {
  15347. return this._stopped;
  15348. };
  15349. Animation.prototype.getKeys = function () {
  15350. return this._keys;
  15351. };
  15352. Animation.prototype.getEasingFunction = function () {
  15353. return this._easingFunction;
  15354. };
  15355. Animation.prototype.setEasingFunction = function (easingFunction) {
  15356. this._easingFunction = easingFunction;
  15357. };
  15358. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15359. return startValue + (endValue - startValue) * gradient;
  15360. };
  15361. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15362. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15363. };
  15364. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15365. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15366. };
  15367. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15368. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15369. };
  15370. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15371. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15372. };
  15373. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15374. var startScale = new BABYLON.Vector3(0, 0, 0);
  15375. var startRotation = new BABYLON.Quaternion();
  15376. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15377. startValue.decompose(startScale, startRotation, startTranslation);
  15378. var endScale = new BABYLON.Vector3(0, 0, 0);
  15379. var endRotation = new BABYLON.Quaternion();
  15380. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15381. endValue.decompose(endScale, endRotation, endTranslation);
  15382. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15383. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15384. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15385. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15386. return result;
  15387. };
  15388. Animation.prototype.clone = function () {
  15389. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15390. clone.setKeys(this._keys);
  15391. return clone;
  15392. };
  15393. Animation.prototype.setKeys = function (values) {
  15394. this._keys = values.slice(0);
  15395. this._offsetsCache = {};
  15396. this._highLimitsCache = {};
  15397. };
  15398. Animation.prototype._getKeyValue = function (value) {
  15399. if (typeof value === "function") {
  15400. return value();
  15401. }
  15402. return value;
  15403. };
  15404. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15405. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15406. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15407. }
  15408. this.currentFrame = currentFrame;
  15409. for (var key = 0; key < this._keys.length; key++) {
  15410. // for each frame, we need the key just before the frame superior
  15411. if (this._keys[key + 1].frame >= currentFrame) {
  15412. var startValue = this._getKeyValue(this._keys[key].value);
  15413. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15414. // gradient : percent of currentFrame between the frame inf and the frame sup
  15415. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15416. // check for easingFunction and correction of gradient
  15417. if (this._easingFunction != null) {
  15418. gradient = this._easingFunction.ease(gradient);
  15419. }
  15420. switch (this.dataType) {
  15421. case Animation.ANIMATIONTYPE_FLOAT:
  15422. switch (loopMode) {
  15423. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15424. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15425. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15426. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15427. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15428. }
  15429. break;
  15430. case Animation.ANIMATIONTYPE_QUATERNION:
  15431. var quaternion = null;
  15432. switch (loopMode) {
  15433. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15434. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15435. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15436. break;
  15437. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15438. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15439. break;
  15440. }
  15441. return quaternion;
  15442. case Animation.ANIMATIONTYPE_VECTOR3:
  15443. switch (loopMode) {
  15444. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15445. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15446. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15447. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15448. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15449. }
  15450. case Animation.ANIMATIONTYPE_VECTOR2:
  15451. switch (loopMode) {
  15452. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15453. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15454. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15455. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15456. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15457. }
  15458. case Animation.ANIMATIONTYPE_COLOR3:
  15459. switch (loopMode) {
  15460. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15461. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15462. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15463. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15464. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15465. }
  15466. case Animation.ANIMATIONTYPE_MATRIX:
  15467. switch (loopMode) {
  15468. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15469. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15470. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15471. return startValue;
  15472. }
  15473. default:
  15474. break;
  15475. }
  15476. break;
  15477. }
  15478. }
  15479. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15480. };
  15481. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15482. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15483. this._stopped = true;
  15484. return false;
  15485. }
  15486. var returnValue = true;
  15487. // Adding a start key at frame 0 if missing
  15488. if (this._keys[0].frame !== 0) {
  15489. var newKey = { frame: 0, value: this._keys[0].value };
  15490. this._keys.splice(0, 0, newKey);
  15491. }
  15492. // Check limits
  15493. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15494. from = this._keys[0].frame;
  15495. }
  15496. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15497. to = this._keys[this._keys.length - 1].frame;
  15498. }
  15499. // Compute ratio
  15500. var range = to - from;
  15501. var offsetValue;
  15502. // ratio represents the frame delta between from and to
  15503. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15504. var highLimitValue = 0;
  15505. if (ratio > range && !loop) {
  15506. returnValue = false;
  15507. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15508. }
  15509. else {
  15510. // Get max value if required
  15511. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15512. var keyOffset = to.toString() + from.toString();
  15513. if (!this._offsetsCache[keyOffset]) {
  15514. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15515. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15516. switch (this.dataType) {
  15517. case Animation.ANIMATIONTYPE_FLOAT:
  15518. this._offsetsCache[keyOffset] = toValue - fromValue;
  15519. break;
  15520. case Animation.ANIMATIONTYPE_QUATERNION:
  15521. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15522. break;
  15523. case Animation.ANIMATIONTYPE_VECTOR3:
  15524. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15525. case Animation.ANIMATIONTYPE_VECTOR2:
  15526. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15527. case Animation.ANIMATIONTYPE_COLOR3:
  15528. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15529. default:
  15530. break;
  15531. }
  15532. this._highLimitsCache[keyOffset] = toValue;
  15533. }
  15534. highLimitValue = this._highLimitsCache[keyOffset];
  15535. offsetValue = this._offsetsCache[keyOffset];
  15536. }
  15537. }
  15538. if (offsetValue === undefined) {
  15539. switch (this.dataType) {
  15540. case Animation.ANIMATIONTYPE_FLOAT:
  15541. offsetValue = 0;
  15542. break;
  15543. case Animation.ANIMATIONTYPE_QUATERNION:
  15544. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15545. break;
  15546. case Animation.ANIMATIONTYPE_VECTOR3:
  15547. offsetValue = BABYLON.Vector3.Zero();
  15548. break;
  15549. case Animation.ANIMATIONTYPE_VECTOR2:
  15550. offsetValue = BABYLON.Vector2.Zero();
  15551. break;
  15552. case Animation.ANIMATIONTYPE_COLOR3:
  15553. offsetValue = BABYLON.Color3.Black();
  15554. }
  15555. }
  15556. // Compute value
  15557. var repeatCount = (ratio / range) >> 0;
  15558. var currentFrame = returnValue ? from + ratio % range : to;
  15559. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15560. // Set value
  15561. if (this.targetPropertyPath.length > 1) {
  15562. var property = this._target[this.targetPropertyPath[0]];
  15563. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15564. property = property[this.targetPropertyPath[index]];
  15565. }
  15566. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15567. }
  15568. else {
  15569. this._target[this.targetPropertyPath[0]] = currentValue;
  15570. }
  15571. if (this._target.markAsDirty) {
  15572. this._target.markAsDirty(this.targetProperty);
  15573. }
  15574. if (!returnValue) {
  15575. this._stopped = true;
  15576. }
  15577. return returnValue;
  15578. };
  15579. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15580. get: function () {
  15581. return Animation._ANIMATIONTYPE_FLOAT;
  15582. },
  15583. enumerable: true,
  15584. configurable: true
  15585. });
  15586. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15587. get: function () {
  15588. return Animation._ANIMATIONTYPE_VECTOR3;
  15589. },
  15590. enumerable: true,
  15591. configurable: true
  15592. });
  15593. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15594. get: function () {
  15595. return Animation._ANIMATIONTYPE_VECTOR2;
  15596. },
  15597. enumerable: true,
  15598. configurable: true
  15599. });
  15600. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15601. get: function () {
  15602. return Animation._ANIMATIONTYPE_QUATERNION;
  15603. },
  15604. enumerable: true,
  15605. configurable: true
  15606. });
  15607. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15608. get: function () {
  15609. return Animation._ANIMATIONTYPE_MATRIX;
  15610. },
  15611. enumerable: true,
  15612. configurable: true
  15613. });
  15614. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15615. get: function () {
  15616. return Animation._ANIMATIONTYPE_COLOR3;
  15617. },
  15618. enumerable: true,
  15619. configurable: true
  15620. });
  15621. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15622. get: function () {
  15623. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15624. },
  15625. enumerable: true,
  15626. configurable: true
  15627. });
  15628. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15629. get: function () {
  15630. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15631. },
  15632. enumerable: true,
  15633. configurable: true
  15634. });
  15635. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15636. get: function () {
  15637. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15638. },
  15639. enumerable: true,
  15640. configurable: true
  15641. });
  15642. // Statics
  15643. Animation._ANIMATIONTYPE_FLOAT = 0;
  15644. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15645. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15646. Animation._ANIMATIONTYPE_MATRIX = 3;
  15647. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15648. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15649. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15650. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15651. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15652. return Animation;
  15653. })();
  15654. BABYLON.Animation = Animation;
  15655. })(BABYLON || (BABYLON = {}));
  15656. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15657. (function (BABYLON) {
  15658. var Animatable = (function () {
  15659. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15660. if (fromFrame === void 0) { fromFrame = 0; }
  15661. if (toFrame === void 0) { toFrame = 100; }
  15662. if (loopAnimation === void 0) { loopAnimation = false; }
  15663. if (speedRatio === void 0) { speedRatio = 1.0; }
  15664. this.target = target;
  15665. this.fromFrame = fromFrame;
  15666. this.toFrame = toFrame;
  15667. this.loopAnimation = loopAnimation;
  15668. this.speedRatio = speedRatio;
  15669. this.onAnimationEnd = onAnimationEnd;
  15670. this._animations = new Array();
  15671. this._paused = false;
  15672. this.animationStarted = false;
  15673. if (animations) {
  15674. this.appendAnimations(target, animations);
  15675. }
  15676. this._scene = scene;
  15677. scene._activeAnimatables.push(this);
  15678. }
  15679. // Methods
  15680. Animatable.prototype.appendAnimations = function (target, animations) {
  15681. for (var index = 0; index < animations.length; index++) {
  15682. var animation = animations[index];
  15683. animation._target = target;
  15684. this._animations.push(animation);
  15685. }
  15686. };
  15687. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15688. var animations = this._animations;
  15689. for (var index = 0; index < animations.length; index++) {
  15690. if (animations[index].targetProperty === property) {
  15691. return animations[index];
  15692. }
  15693. }
  15694. return null;
  15695. };
  15696. Animatable.prototype.pause = function () {
  15697. if (this._paused) {
  15698. return;
  15699. }
  15700. this._paused = true;
  15701. };
  15702. Animatable.prototype.restart = function () {
  15703. this._paused = false;
  15704. };
  15705. Animatable.prototype.stop = function () {
  15706. var index = this._scene._activeAnimatables.indexOf(this);
  15707. if (index > -1) {
  15708. this._scene._activeAnimatables.splice(index, 1);
  15709. }
  15710. if (this.onAnimationEnd) {
  15711. this.onAnimationEnd();
  15712. }
  15713. };
  15714. Animatable.prototype._animate = function (delay) {
  15715. if (this._paused) {
  15716. if (!this._pausedDelay) {
  15717. this._pausedDelay = delay;
  15718. }
  15719. return true;
  15720. }
  15721. if (!this._localDelayOffset) {
  15722. this._localDelayOffset = delay;
  15723. }
  15724. else if (this._pausedDelay) {
  15725. this._localDelayOffset += delay - this._pausedDelay;
  15726. this._pausedDelay = null;
  15727. }
  15728. // Animating
  15729. var running = false;
  15730. var animations = this._animations;
  15731. for (var index = 0; index < animations.length; index++) {
  15732. var animation = animations[index];
  15733. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15734. running = running || isRunning;
  15735. }
  15736. if (!running && this.onAnimationEnd) {
  15737. this.onAnimationEnd();
  15738. }
  15739. return running;
  15740. };
  15741. return Animatable;
  15742. })();
  15743. BABYLON.Animatable = Animatable;
  15744. })(BABYLON || (BABYLON = {}));
  15745. //# sourceMappingURL=babylon.animatable.js.map
  15746. var BABYLON;
  15747. (function (BABYLON) {
  15748. var EasingFunction = (function () {
  15749. function EasingFunction() {
  15750. // Properties
  15751. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15752. }
  15753. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15754. get: function () {
  15755. return EasingFunction._EASINGMODE_EASEIN;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15761. get: function () {
  15762. return EasingFunction._EASINGMODE_EASEOUT;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15768. get: function () {
  15769. return EasingFunction._EASINGMODE_EASEINOUT;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15775. var n = Math.min(Math.max(easingMode, 0), 2);
  15776. this._easingMode = n;
  15777. };
  15778. EasingFunction.prototype.getEasingMode = function () {
  15779. return this._easingMode;
  15780. };
  15781. EasingFunction.prototype.easeInCore = function (gradient) {
  15782. throw new Error('You must implement this method');
  15783. };
  15784. EasingFunction.prototype.ease = function (gradient) {
  15785. switch (this._easingMode) {
  15786. case EasingFunction.EASINGMODE_EASEIN:
  15787. return this.easeInCore(gradient);
  15788. case EasingFunction.EASINGMODE_EASEOUT:
  15789. return (1 - this.easeInCore(1 - gradient));
  15790. }
  15791. if (gradient >= 0.5) {
  15792. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15793. }
  15794. return (this.easeInCore(gradient * 2) * 0.5);
  15795. };
  15796. //Statics
  15797. EasingFunction._EASINGMODE_EASEIN = 0;
  15798. EasingFunction._EASINGMODE_EASEOUT = 1;
  15799. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15800. return EasingFunction;
  15801. })();
  15802. BABYLON.EasingFunction = EasingFunction;
  15803. var CircleEase = (function (_super) {
  15804. __extends(CircleEase, _super);
  15805. function CircleEase() {
  15806. _super.apply(this, arguments);
  15807. }
  15808. CircleEase.prototype.easeInCore = function (gradient) {
  15809. gradient = Math.max(0, Math.min(1, gradient));
  15810. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15811. };
  15812. return CircleEase;
  15813. })(EasingFunction);
  15814. BABYLON.CircleEase = CircleEase;
  15815. var BackEase = (function (_super) {
  15816. __extends(BackEase, _super);
  15817. function BackEase(amplitude) {
  15818. if (amplitude === void 0) { amplitude = 1; }
  15819. _super.call(this);
  15820. this.amplitude = amplitude;
  15821. }
  15822. BackEase.prototype.easeInCore = function (gradient) {
  15823. var num = Math.max(0, this.amplitude);
  15824. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15825. };
  15826. return BackEase;
  15827. })(EasingFunction);
  15828. BABYLON.BackEase = BackEase;
  15829. var BounceEase = (function (_super) {
  15830. __extends(BounceEase, _super);
  15831. function BounceEase(bounces, bounciness) {
  15832. if (bounces === void 0) { bounces = 3; }
  15833. if (bounciness === void 0) { bounciness = 2; }
  15834. _super.call(this);
  15835. this.bounces = bounces;
  15836. this.bounciness = bounciness;
  15837. }
  15838. BounceEase.prototype.easeInCore = function (gradient) {
  15839. var y = Math.max(0.0, this.bounces);
  15840. var bounciness = this.bounciness;
  15841. if (bounciness <= 1.0) {
  15842. bounciness = 1.001;
  15843. }
  15844. var num9 = Math.pow(bounciness, y);
  15845. var num5 = 1.0 - bounciness;
  15846. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15847. var num15 = gradient * num4;
  15848. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15849. var num3 = Math.floor(num65);
  15850. var num13 = num3 + 1.0;
  15851. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15852. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15853. var num7 = (num8 + num12) * 0.5;
  15854. var num6 = gradient - num7;
  15855. var num2 = num7 - num8;
  15856. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15857. };
  15858. return BounceEase;
  15859. })(EasingFunction);
  15860. BABYLON.BounceEase = BounceEase;
  15861. var CubicEase = (function (_super) {
  15862. __extends(CubicEase, _super);
  15863. function CubicEase() {
  15864. _super.apply(this, arguments);
  15865. }
  15866. CubicEase.prototype.easeInCore = function (gradient) {
  15867. return (gradient * gradient * gradient);
  15868. };
  15869. return CubicEase;
  15870. })(EasingFunction);
  15871. BABYLON.CubicEase = CubicEase;
  15872. var ElasticEase = (function (_super) {
  15873. __extends(ElasticEase, _super);
  15874. function ElasticEase(oscillations, springiness) {
  15875. if (oscillations === void 0) { oscillations = 3; }
  15876. if (springiness === void 0) { springiness = 3; }
  15877. _super.call(this);
  15878. this.oscillations = oscillations;
  15879. this.springiness = springiness;
  15880. }
  15881. ElasticEase.prototype.easeInCore = function (gradient) {
  15882. var num2;
  15883. var num3 = Math.max(0.0, this.oscillations);
  15884. var num = Math.max(0.0, this.springiness);
  15885. if (num == 0) {
  15886. num2 = gradient;
  15887. }
  15888. else {
  15889. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15890. }
  15891. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15892. };
  15893. return ElasticEase;
  15894. })(EasingFunction);
  15895. BABYLON.ElasticEase = ElasticEase;
  15896. var ExponentialEase = (function (_super) {
  15897. __extends(ExponentialEase, _super);
  15898. function ExponentialEase(exponent) {
  15899. if (exponent === void 0) { exponent = 2; }
  15900. _super.call(this);
  15901. this.exponent = exponent;
  15902. }
  15903. ExponentialEase.prototype.easeInCore = function (gradient) {
  15904. if (this.exponent <= 0) {
  15905. return gradient;
  15906. }
  15907. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15908. };
  15909. return ExponentialEase;
  15910. })(EasingFunction);
  15911. BABYLON.ExponentialEase = ExponentialEase;
  15912. var PowerEase = (function (_super) {
  15913. __extends(PowerEase, _super);
  15914. function PowerEase(power) {
  15915. if (power === void 0) { power = 2; }
  15916. _super.call(this);
  15917. this.power = power;
  15918. }
  15919. PowerEase.prototype.easeInCore = function (gradient) {
  15920. var y = Math.max(0.0, this.power);
  15921. return Math.pow(gradient, y);
  15922. };
  15923. return PowerEase;
  15924. })(EasingFunction);
  15925. BABYLON.PowerEase = PowerEase;
  15926. var QuadraticEase = (function (_super) {
  15927. __extends(QuadraticEase, _super);
  15928. function QuadraticEase() {
  15929. _super.apply(this, arguments);
  15930. }
  15931. QuadraticEase.prototype.easeInCore = function (gradient) {
  15932. return (gradient * gradient);
  15933. };
  15934. return QuadraticEase;
  15935. })(EasingFunction);
  15936. BABYLON.QuadraticEase = QuadraticEase;
  15937. var QuarticEase = (function (_super) {
  15938. __extends(QuarticEase, _super);
  15939. function QuarticEase() {
  15940. _super.apply(this, arguments);
  15941. }
  15942. QuarticEase.prototype.easeInCore = function (gradient) {
  15943. return (gradient * gradient * gradient * gradient);
  15944. };
  15945. return QuarticEase;
  15946. })(EasingFunction);
  15947. BABYLON.QuarticEase = QuarticEase;
  15948. var QuinticEase = (function (_super) {
  15949. __extends(QuinticEase, _super);
  15950. function QuinticEase() {
  15951. _super.apply(this, arguments);
  15952. }
  15953. QuinticEase.prototype.easeInCore = function (gradient) {
  15954. return (gradient * gradient * gradient * gradient * gradient);
  15955. };
  15956. return QuinticEase;
  15957. })(EasingFunction);
  15958. BABYLON.QuinticEase = QuinticEase;
  15959. var SineEase = (function (_super) {
  15960. __extends(SineEase, _super);
  15961. function SineEase() {
  15962. _super.apply(this, arguments);
  15963. }
  15964. SineEase.prototype.easeInCore = function (gradient) {
  15965. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15966. };
  15967. return SineEase;
  15968. })(EasingFunction);
  15969. BABYLON.SineEase = SineEase;
  15970. var BezierCurveEase = (function (_super) {
  15971. __extends(BezierCurveEase, _super);
  15972. function BezierCurveEase(x1, y1, x2, y2) {
  15973. if (x1 === void 0) { x1 = 0; }
  15974. if (y1 === void 0) { y1 = 0; }
  15975. if (x2 === void 0) { x2 = 1; }
  15976. if (y2 === void 0) { y2 = 1; }
  15977. _super.call(this);
  15978. this.x1 = x1;
  15979. this.y1 = y1;
  15980. this.x2 = x2;
  15981. this.y2 = y2;
  15982. }
  15983. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15984. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15985. };
  15986. return BezierCurveEase;
  15987. })(EasingFunction);
  15988. BABYLON.BezierCurveEase = BezierCurveEase;
  15989. })(BABYLON || (BABYLON = {}));
  15990. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15991. (function (BABYLON) {
  15992. var Octree = (function () {
  15993. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15994. if (maxDepth === void 0) { maxDepth = 2; }
  15995. this.maxDepth = maxDepth;
  15996. this.dynamicContent = new Array();
  15997. this._maxBlockCapacity = maxBlockCapacity || 64;
  15998. this._selectionContent = new BABYLON.SmartArray(1024);
  15999. this._creationFunc = creationFunc;
  16000. }
  16001. // Methods
  16002. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16003. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16004. };
  16005. Octree.prototype.addMesh = function (entry) {
  16006. for (var index = 0; index < this.blocks.length; index++) {
  16007. var block = this.blocks[index];
  16008. block.addEntry(entry);
  16009. }
  16010. };
  16011. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16012. this._selectionContent.reset();
  16013. for (var index = 0; index < this.blocks.length; index++) {
  16014. var block = this.blocks[index];
  16015. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16016. }
  16017. if (allowDuplicate) {
  16018. this._selectionContent.concat(this.dynamicContent);
  16019. }
  16020. else {
  16021. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16022. }
  16023. return this._selectionContent;
  16024. };
  16025. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16026. this._selectionContent.reset();
  16027. for (var index = 0; index < this.blocks.length; index++) {
  16028. var block = this.blocks[index];
  16029. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16030. }
  16031. if (allowDuplicate) {
  16032. this._selectionContent.concat(this.dynamicContent);
  16033. }
  16034. else {
  16035. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16036. }
  16037. return this._selectionContent;
  16038. };
  16039. Octree.prototype.intersectsRay = function (ray) {
  16040. this._selectionContent.reset();
  16041. for (var index = 0; index < this.blocks.length; index++) {
  16042. var block = this.blocks[index];
  16043. block.intersectsRay(ray, this._selectionContent);
  16044. }
  16045. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16046. return this._selectionContent;
  16047. };
  16048. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16049. target.blocks = new Array();
  16050. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16051. for (var x = 0; x < 2; x++) {
  16052. for (var y = 0; y < 2; y++) {
  16053. for (var z = 0; z < 2; z++) {
  16054. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16055. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16056. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16057. block.addEntries(entries);
  16058. target.blocks.push(block);
  16059. }
  16060. }
  16061. }
  16062. };
  16063. Octree.CreationFuncForMeshes = function (entry, block) {
  16064. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16065. block.entries.push(entry);
  16066. }
  16067. };
  16068. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16069. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16070. block.entries.push(entry);
  16071. }
  16072. };
  16073. return Octree;
  16074. })();
  16075. BABYLON.Octree = Octree;
  16076. })(BABYLON || (BABYLON = {}));
  16077. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16078. (function (BABYLON) {
  16079. var OctreeBlock = (function () {
  16080. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16081. this.entries = new Array();
  16082. this._boundingVectors = new Array();
  16083. this._capacity = capacity;
  16084. this._depth = depth;
  16085. this._maxDepth = maxDepth;
  16086. this._creationFunc = creationFunc;
  16087. this._minPoint = minPoint;
  16088. this._maxPoint = maxPoint;
  16089. this._boundingVectors.push(minPoint.clone());
  16090. this._boundingVectors.push(maxPoint.clone());
  16091. this._boundingVectors.push(minPoint.clone());
  16092. this._boundingVectors[2].x = maxPoint.x;
  16093. this._boundingVectors.push(minPoint.clone());
  16094. this._boundingVectors[3].y = maxPoint.y;
  16095. this._boundingVectors.push(minPoint.clone());
  16096. this._boundingVectors[4].z = maxPoint.z;
  16097. this._boundingVectors.push(maxPoint.clone());
  16098. this._boundingVectors[5].z = minPoint.z;
  16099. this._boundingVectors.push(maxPoint.clone());
  16100. this._boundingVectors[6].x = minPoint.x;
  16101. this._boundingVectors.push(maxPoint.clone());
  16102. this._boundingVectors[7].y = minPoint.y;
  16103. }
  16104. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16105. // Property
  16106. get: function () {
  16107. return this._capacity;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16113. get: function () {
  16114. return this._minPoint;
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16120. get: function () {
  16121. return this._maxPoint;
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. // Methods
  16127. OctreeBlock.prototype.addEntry = function (entry) {
  16128. if (this.blocks) {
  16129. for (var index = 0; index < this.blocks.length; index++) {
  16130. var block = this.blocks[index];
  16131. block.addEntry(entry);
  16132. }
  16133. return;
  16134. }
  16135. this._creationFunc(entry, this);
  16136. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16137. this.createInnerBlocks();
  16138. }
  16139. };
  16140. OctreeBlock.prototype.addEntries = function (entries) {
  16141. for (var index = 0; index < entries.length; index++) {
  16142. var mesh = entries[index];
  16143. this.addEntry(mesh);
  16144. }
  16145. };
  16146. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16147. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16148. if (this.blocks) {
  16149. for (var index = 0; index < this.blocks.length; index++) {
  16150. var block = this.blocks[index];
  16151. block.select(frustumPlanes, selection, allowDuplicate);
  16152. }
  16153. return;
  16154. }
  16155. if (allowDuplicate) {
  16156. selection.concat(this.entries);
  16157. }
  16158. else {
  16159. selection.concatWithNoDuplicate(this.entries);
  16160. }
  16161. }
  16162. };
  16163. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16164. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16165. if (this.blocks) {
  16166. for (var index = 0; index < this.blocks.length; index++) {
  16167. var block = this.blocks[index];
  16168. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16169. }
  16170. return;
  16171. }
  16172. if (allowDuplicate) {
  16173. selection.concat(this.entries);
  16174. }
  16175. else {
  16176. selection.concatWithNoDuplicate(this.entries);
  16177. }
  16178. }
  16179. };
  16180. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16181. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16182. if (this.blocks) {
  16183. for (var index = 0; index < this.blocks.length; index++) {
  16184. var block = this.blocks[index];
  16185. block.intersectsRay(ray, selection);
  16186. }
  16187. return;
  16188. }
  16189. selection.concatWithNoDuplicate(this.entries);
  16190. }
  16191. };
  16192. OctreeBlock.prototype.createInnerBlocks = function () {
  16193. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16194. };
  16195. return OctreeBlock;
  16196. })();
  16197. BABYLON.OctreeBlock = OctreeBlock;
  16198. })(BABYLON || (BABYLON = {}));
  16199. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16200. (function (BABYLON) {
  16201. var Bone = (function () {
  16202. function Bone(name, skeleton, parentBone, matrix) {
  16203. this.name = name;
  16204. this.children = new Array();
  16205. this.animations = new Array();
  16206. this._worldTransform = new BABYLON.Matrix();
  16207. this._absoluteTransform = new BABYLON.Matrix();
  16208. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16209. this._skeleton = skeleton;
  16210. this._matrix = matrix;
  16211. this._baseMatrix = matrix;
  16212. skeleton.bones.push(this);
  16213. if (parentBone) {
  16214. this._parent = parentBone;
  16215. parentBone.children.push(this);
  16216. }
  16217. else {
  16218. this._parent = null;
  16219. }
  16220. this._updateDifferenceMatrix();
  16221. }
  16222. // Members
  16223. Bone.prototype.getParent = function () {
  16224. return this._parent;
  16225. };
  16226. Bone.prototype.getLocalMatrix = function () {
  16227. return this._matrix;
  16228. };
  16229. Bone.prototype.getBaseMatrix = function () {
  16230. return this._baseMatrix;
  16231. };
  16232. Bone.prototype.getWorldMatrix = function () {
  16233. return this._worldTransform;
  16234. };
  16235. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16236. return this._invertedAbsoluteTransform;
  16237. };
  16238. Bone.prototype.getAbsoluteMatrix = function () {
  16239. var matrix = this._matrix.clone();
  16240. var parent = this._parent;
  16241. while (parent) {
  16242. matrix = matrix.multiply(parent.getLocalMatrix());
  16243. parent = parent.getParent();
  16244. }
  16245. return matrix;
  16246. };
  16247. // Methods
  16248. Bone.prototype.updateMatrix = function (matrix) {
  16249. this._matrix = matrix;
  16250. this._skeleton._markAsDirty();
  16251. this._updateDifferenceMatrix();
  16252. };
  16253. Bone.prototype._updateDifferenceMatrix = function () {
  16254. if (this._parent) {
  16255. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16256. }
  16257. else {
  16258. this._absoluteTransform.copyFrom(this._matrix);
  16259. }
  16260. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16261. for (var index = 0; index < this.children.length; index++) {
  16262. this.children[index]._updateDifferenceMatrix();
  16263. }
  16264. };
  16265. Bone.prototype.markAsDirty = function () {
  16266. this._skeleton._markAsDirty();
  16267. };
  16268. return Bone;
  16269. })();
  16270. BABYLON.Bone = Bone;
  16271. })(BABYLON || (BABYLON = {}));
  16272. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16273. (function (BABYLON) {
  16274. var Skeleton = (function () {
  16275. function Skeleton(name, id, scene) {
  16276. this.name = name;
  16277. this.id = id;
  16278. this.bones = new Array();
  16279. this._isDirty = true;
  16280. this._identity = BABYLON.Matrix.Identity();
  16281. this.bones = [];
  16282. this._scene = scene;
  16283. scene.skeletons.push(this);
  16284. }
  16285. // Members
  16286. Skeleton.prototype.getTransformMatrices = function () {
  16287. return this._transformMatrices;
  16288. };
  16289. // Methods
  16290. Skeleton.prototype._markAsDirty = function () {
  16291. this._isDirty = true;
  16292. };
  16293. Skeleton.prototype.prepare = function () {
  16294. if (!this._isDirty) {
  16295. return;
  16296. }
  16297. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16298. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16299. }
  16300. for (var index = 0; index < this.bones.length; index++) {
  16301. var bone = this.bones[index];
  16302. var parentBone = bone.getParent();
  16303. if (parentBone) {
  16304. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16305. }
  16306. else {
  16307. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16308. }
  16309. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16310. }
  16311. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16312. this._isDirty = false;
  16313. };
  16314. Skeleton.prototype.getAnimatables = function () {
  16315. if (!this._animatables || this._animatables.length != this.bones.length) {
  16316. this._animatables = [];
  16317. for (var index = 0; index < this.bones.length; index++) {
  16318. this._animatables.push(this.bones[index]);
  16319. }
  16320. }
  16321. return this._animatables;
  16322. };
  16323. Skeleton.prototype.clone = function (name, id) {
  16324. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16325. for (var index = 0; index < this.bones.length; index++) {
  16326. var source = this.bones[index];
  16327. var parentBone = null;
  16328. if (source.getParent()) {
  16329. var parentIndex = this.bones.indexOf(source.getParent());
  16330. parentBone = result.bones[parentIndex];
  16331. }
  16332. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16333. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16334. }
  16335. return result;
  16336. };
  16337. return Skeleton;
  16338. })();
  16339. BABYLON.Skeleton = Skeleton;
  16340. })(BABYLON || (BABYLON = {}));
  16341. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16342. (function (BABYLON) {
  16343. var PostProcess = (function () {
  16344. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16345. this.name = name;
  16346. this.width = -1;
  16347. this.height = -1;
  16348. this._reusable = false;
  16349. this._textures = new BABYLON.SmartArray(2);
  16350. this._currentRenderTextureInd = 0;
  16351. if (camera != null) {
  16352. this._camera = camera;
  16353. this._scene = camera.getScene();
  16354. camera.attachPostProcess(this);
  16355. this._engine = this._scene.getEngine();
  16356. }
  16357. else {
  16358. this._engine = engine;
  16359. }
  16360. this._renderRatio = ratio;
  16361. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16362. this._reusable = reusable || false;
  16363. samplers = samplers || [];
  16364. samplers.push("textureSampler");
  16365. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16366. }
  16367. PostProcess.prototype.isReusable = function () {
  16368. return this._reusable;
  16369. };
  16370. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16371. camera = camera || this._camera;
  16372. var scene = camera.getScene();
  16373. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16374. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16375. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16376. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16377. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16378. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16379. if (this._textures.length > 0) {
  16380. for (var i = 0; i < this._textures.length; i++) {
  16381. this._engine._releaseTexture(this._textures.data[i]);
  16382. }
  16383. this._textures.reset();
  16384. }
  16385. this.width = desiredWidth;
  16386. this.height = desiredHeight;
  16387. 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 }));
  16388. if (this._reusable) {
  16389. 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 }));
  16390. }
  16391. if (this.onSizeChanged) {
  16392. this.onSizeChanged();
  16393. }
  16394. }
  16395. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16396. if (this.onActivate) {
  16397. this.onActivate(camera);
  16398. }
  16399. // Clear
  16400. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16401. if (this._reusable) {
  16402. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16403. }
  16404. };
  16405. PostProcess.prototype.apply = function () {
  16406. // Check
  16407. if (!this._effect.isReady())
  16408. return null;
  16409. // States
  16410. this._engine.enableEffect(this._effect);
  16411. this._engine.setState(false);
  16412. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16413. this._engine.setDepthBuffer(false);
  16414. this._engine.setDepthWrite(false);
  16415. // Texture
  16416. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16417. // Parameters
  16418. if (this.onApply) {
  16419. this.onApply(this._effect);
  16420. }
  16421. return this._effect;
  16422. };
  16423. PostProcess.prototype.dispose = function (camera) {
  16424. camera = camera || this._camera;
  16425. if (this._textures.length > 0) {
  16426. for (var i = 0; i < this._textures.length; i++) {
  16427. this._engine._releaseTexture(this._textures.data[i]);
  16428. }
  16429. this._textures.reset();
  16430. }
  16431. camera.detachPostProcess(this);
  16432. var index = camera._postProcesses.indexOf(this);
  16433. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16434. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16435. }
  16436. };
  16437. return PostProcess;
  16438. })();
  16439. BABYLON.PostProcess = PostProcess;
  16440. })(BABYLON || (BABYLON = {}));
  16441. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16442. (function (BABYLON) {
  16443. var PostProcessManager = (function () {
  16444. function PostProcessManager(scene) {
  16445. this._vertexDeclaration = [2];
  16446. this._vertexStrideSize = 2 * 4;
  16447. this._scene = scene;
  16448. // VBO
  16449. var vertices = [];
  16450. vertices.push(1, 1);
  16451. vertices.push(-1, 1);
  16452. vertices.push(-1, -1);
  16453. vertices.push(1, -1);
  16454. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16455. // Indices
  16456. var indices = [];
  16457. indices.push(0);
  16458. indices.push(1);
  16459. indices.push(2);
  16460. indices.push(0);
  16461. indices.push(2);
  16462. indices.push(3);
  16463. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16464. }
  16465. // Methods
  16466. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16467. var postProcesses = this._scene.activeCamera._postProcesses;
  16468. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16469. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16470. return false;
  16471. }
  16472. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16473. return true;
  16474. };
  16475. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16476. var postProcesses = this._scene.activeCamera._postProcesses;
  16477. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16478. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16479. return;
  16480. }
  16481. var engine = this._scene.getEngine();
  16482. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16483. if (index < postProcessesTakenIndices.length - 1) {
  16484. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16485. }
  16486. else {
  16487. if (targetTexture) {
  16488. engine.bindFramebuffer(targetTexture);
  16489. }
  16490. else {
  16491. engine.restoreDefaultFramebuffer();
  16492. }
  16493. }
  16494. if (doNotPresent) {
  16495. break;
  16496. }
  16497. var pp = postProcesses[postProcessesTakenIndices[index]];
  16498. var effect = pp.apply();
  16499. if (effect) {
  16500. if (pp.onBeforeRender) {
  16501. pp.onBeforeRender(effect);
  16502. }
  16503. // VBOs
  16504. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16505. // Draw order
  16506. engine.draw(true, 0, 6);
  16507. }
  16508. }
  16509. // Restore depth buffer
  16510. engine.setDepthBuffer(true);
  16511. engine.setDepthWrite(true);
  16512. };
  16513. PostProcessManager.prototype.dispose = function () {
  16514. if (this._vertexBuffer) {
  16515. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16516. this._vertexBuffer = null;
  16517. }
  16518. if (this._indexBuffer) {
  16519. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16520. this._indexBuffer = null;
  16521. }
  16522. };
  16523. return PostProcessManager;
  16524. })();
  16525. BABYLON.PostProcessManager = PostProcessManager;
  16526. })(BABYLON || (BABYLON = {}));
  16527. //# sourceMappingURL=babylon.postProcessManager.js.map
  16528. var BABYLON;
  16529. (function (BABYLON) {
  16530. var PassPostProcess = (function (_super) {
  16531. __extends(PassPostProcess, _super);
  16532. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16533. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16534. }
  16535. return PassPostProcess;
  16536. })(BABYLON.PostProcess);
  16537. BABYLON.PassPostProcess = PassPostProcess;
  16538. })(BABYLON || (BABYLON = {}));
  16539. //# sourceMappingURL=babylon.passPostProcess.js.map
  16540. var BABYLON;
  16541. (function (BABYLON) {
  16542. var BlurPostProcess = (function (_super) {
  16543. __extends(BlurPostProcess, _super);
  16544. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16545. var _this = this;
  16546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16547. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16548. this.direction = direction;
  16549. this.blurWidth = blurWidth;
  16550. this.onApply = function (effect) {
  16551. effect.setFloat2("screenSize", _this.width, _this.height);
  16552. effect.setVector2("direction", _this.direction);
  16553. effect.setFloat("blurWidth", _this.blurWidth);
  16554. };
  16555. }
  16556. return BlurPostProcess;
  16557. })(BABYLON.PostProcess);
  16558. BABYLON.BlurPostProcess = BlurPostProcess;
  16559. })(BABYLON || (BABYLON = {}));
  16560. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16561. var BABYLON;
  16562. (function (BABYLON) {
  16563. var FilterPostProcess = (function (_super) {
  16564. __extends(FilterPostProcess, _super);
  16565. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16566. var _this = this;
  16567. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16568. this.kernelMatrix = kernelMatrix;
  16569. this.onApply = function (effect) {
  16570. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16571. };
  16572. }
  16573. return FilterPostProcess;
  16574. })(BABYLON.PostProcess);
  16575. BABYLON.FilterPostProcess = FilterPostProcess;
  16576. })(BABYLON || (BABYLON = {}));
  16577. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16578. var BABYLON;
  16579. (function (BABYLON) {
  16580. var RefractionPostProcess = (function (_super) {
  16581. __extends(RefractionPostProcess, _super);
  16582. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16583. var _this = this;
  16584. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16585. this.color = color;
  16586. this.depth = depth;
  16587. this.colorLevel = colorLevel;
  16588. this.onActivate = function (cam) {
  16589. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16590. };
  16591. this.onApply = function (effect) {
  16592. effect.setColor3("baseColor", _this.color);
  16593. effect.setFloat("depth", _this.depth);
  16594. effect.setFloat("colorLevel", _this.colorLevel);
  16595. effect.setTexture("refractionSampler", _this._refRexture);
  16596. };
  16597. }
  16598. // Methods
  16599. RefractionPostProcess.prototype.dispose = function (camera) {
  16600. if (this._refRexture) {
  16601. this._refRexture.dispose();
  16602. }
  16603. _super.prototype.dispose.call(this, camera);
  16604. };
  16605. return RefractionPostProcess;
  16606. })(BABYLON.PostProcess);
  16607. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16608. })(BABYLON || (BABYLON = {}));
  16609. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16610. var BABYLON;
  16611. (function (BABYLON) {
  16612. var BlackAndWhitePostProcess = (function (_super) {
  16613. __extends(BlackAndWhitePostProcess, _super);
  16614. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16615. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16616. }
  16617. return BlackAndWhitePostProcess;
  16618. })(BABYLON.PostProcess);
  16619. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16620. })(BABYLON || (BABYLON = {}));
  16621. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16622. var BABYLON;
  16623. (function (BABYLON) {
  16624. var ConvolutionPostProcess = (function (_super) {
  16625. __extends(ConvolutionPostProcess, _super);
  16626. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16627. var _this = this;
  16628. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16629. this.kernel = kernel;
  16630. this.onApply = function (effect) {
  16631. effect.setFloat2("screenSize", _this.width, _this.height);
  16632. effect.setArray("kernel", _this.kernel);
  16633. };
  16634. }
  16635. // Statics
  16636. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16637. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16638. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16639. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16640. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16641. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16642. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16643. return ConvolutionPostProcess;
  16644. })(BABYLON.PostProcess);
  16645. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16646. })(BABYLON || (BABYLON = {}));
  16647. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16648. var BABYLON;
  16649. (function (BABYLON) {
  16650. var FxaaPostProcess = (function (_super) {
  16651. __extends(FxaaPostProcess, _super);
  16652. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16653. var _this = this;
  16654. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16655. this.onSizeChanged = function () {
  16656. _this.texelWidth = 1.0 / _this.width;
  16657. _this.texelHeight = 1.0 / _this.height;
  16658. };
  16659. this.onApply = function (effect) {
  16660. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16661. };
  16662. }
  16663. return FxaaPostProcess;
  16664. })(BABYLON.PostProcess);
  16665. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16666. })(BABYLON || (BABYLON = {}));
  16667. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16668. (function (BABYLON) {
  16669. var LensFlare = (function () {
  16670. function LensFlare(size, position, color, imgUrl, system) {
  16671. this.size = size;
  16672. this.position = position;
  16673. this.dispose = function () {
  16674. if (this.texture) {
  16675. this.texture.dispose();
  16676. }
  16677. // Remove from scene
  16678. var index = this._system.lensFlares.indexOf(this);
  16679. this._system.lensFlares.splice(index, 1);
  16680. };
  16681. this.color = color || new BABYLON.Color3(1, 1, 1);
  16682. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16683. this._system = system;
  16684. system.lensFlares.push(this);
  16685. }
  16686. return LensFlare;
  16687. })();
  16688. BABYLON.LensFlare = LensFlare;
  16689. })(BABYLON || (BABYLON = {}));
  16690. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16691. (function (BABYLON) {
  16692. var LensFlareSystem = (function () {
  16693. function LensFlareSystem(name, emitter, scene) {
  16694. this.name = name;
  16695. this.lensFlares = new Array();
  16696. this.borderLimit = 300;
  16697. this._vertexDeclaration = [2];
  16698. this._vertexStrideSize = 2 * 4;
  16699. this._isEnabled = true;
  16700. this._scene = scene;
  16701. this._emitter = emitter;
  16702. scene.lensFlareSystems.push(this);
  16703. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16704. // VBO
  16705. var vertices = [];
  16706. vertices.push(1, 1);
  16707. vertices.push(-1, 1);
  16708. vertices.push(-1, -1);
  16709. vertices.push(1, -1);
  16710. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16711. // Indices
  16712. var indices = [];
  16713. indices.push(0);
  16714. indices.push(1);
  16715. indices.push(2);
  16716. indices.push(0);
  16717. indices.push(2);
  16718. indices.push(3);
  16719. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16720. // Effects
  16721. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16722. }
  16723. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16724. get: function () {
  16725. return this._isEnabled;
  16726. },
  16727. set: function (value) {
  16728. this._isEnabled = value;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. LensFlareSystem.prototype.getScene = function () {
  16734. return this._scene;
  16735. };
  16736. LensFlareSystem.prototype.getEmitter = function () {
  16737. return this._emitter;
  16738. };
  16739. LensFlareSystem.prototype.getEmitterPosition = function () {
  16740. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16741. };
  16742. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16743. var position = this.getEmitterPosition();
  16744. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16745. this._positionX = position.x;
  16746. this._positionY = position.y;
  16747. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16748. if (position.z > 0) {
  16749. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16750. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16751. return true;
  16752. }
  16753. }
  16754. return false;
  16755. };
  16756. LensFlareSystem.prototype._isVisible = function () {
  16757. if (!this._isEnabled) {
  16758. return false;
  16759. }
  16760. var emitterPosition = this.getEmitterPosition();
  16761. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16762. var distance = direction.length();
  16763. direction.normalize();
  16764. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16765. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16766. return !pickInfo.hit || pickInfo.distance > distance;
  16767. };
  16768. LensFlareSystem.prototype.render = function () {
  16769. if (!this._effect.isReady())
  16770. return false;
  16771. var engine = this._scene.getEngine();
  16772. var viewport = this._scene.activeCamera.viewport;
  16773. var globalViewport = viewport.toGlobal(engine);
  16774. // Position
  16775. if (!this.computeEffectivePosition(globalViewport)) {
  16776. return false;
  16777. }
  16778. // Visibility
  16779. if (!this._isVisible()) {
  16780. return false;
  16781. }
  16782. // Intensity
  16783. var awayX;
  16784. var awayY;
  16785. if (this._positionX < this.borderLimit + globalViewport.x) {
  16786. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16787. }
  16788. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16789. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16790. }
  16791. else {
  16792. awayX = 0;
  16793. }
  16794. if (this._positionY < this.borderLimit + globalViewport.y) {
  16795. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16796. }
  16797. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16798. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16799. }
  16800. else {
  16801. awayY = 0;
  16802. }
  16803. var away = (awayX > awayY) ? awayX : awayY;
  16804. if (away > this.borderLimit) {
  16805. away = this.borderLimit;
  16806. }
  16807. var intensity = 1.0 - (away / this.borderLimit);
  16808. if (intensity < 0) {
  16809. return false;
  16810. }
  16811. if (intensity > 1.0) {
  16812. intensity = 1.0;
  16813. }
  16814. // Position
  16815. var centerX = globalViewport.x + globalViewport.width / 2;
  16816. var centerY = globalViewport.y + globalViewport.height / 2;
  16817. var distX = centerX - this._positionX;
  16818. var distY = centerY - this._positionY;
  16819. // Effects
  16820. engine.enableEffect(this._effect);
  16821. engine.setState(false);
  16822. engine.setDepthBuffer(false);
  16823. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16824. // VBOs
  16825. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16826. for (var index = 0; index < this.lensFlares.length; index++) {
  16827. var flare = this.lensFlares[index];
  16828. var x = centerX - (distX * flare.position);
  16829. var y = centerY - (distY * flare.position);
  16830. var cw = flare.size;
  16831. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16832. var cx = 2 * (x / globalViewport.width) - 1.0;
  16833. var cy = 1.0 - 2 * (y / globalViewport.height);
  16834. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16835. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16836. // Texture
  16837. this._effect.setTexture("textureSampler", flare.texture);
  16838. // Color
  16839. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16840. // Draw order
  16841. engine.draw(true, 0, 6);
  16842. }
  16843. engine.setDepthBuffer(true);
  16844. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16845. return true;
  16846. };
  16847. LensFlareSystem.prototype.dispose = function () {
  16848. if (this._vertexBuffer) {
  16849. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16850. this._vertexBuffer = null;
  16851. }
  16852. if (this._indexBuffer) {
  16853. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16854. this._indexBuffer = null;
  16855. }
  16856. while (this.lensFlares.length) {
  16857. this.lensFlares[0].dispose();
  16858. }
  16859. // Remove from scene
  16860. var index = this._scene.lensFlareSystems.indexOf(this);
  16861. this._scene.lensFlareSystems.splice(index, 1);
  16862. };
  16863. return LensFlareSystem;
  16864. })();
  16865. BABYLON.LensFlareSystem = LensFlareSystem;
  16866. })(BABYLON || (BABYLON = {}));
  16867. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16868. (function (BABYLON) {
  16869. var IntersectionInfo = (function () {
  16870. function IntersectionInfo(bu, bv, distance) {
  16871. this.bu = bu;
  16872. this.bv = bv;
  16873. this.distance = distance;
  16874. this.faceId = 0;
  16875. this.subMeshId = 0;
  16876. }
  16877. return IntersectionInfo;
  16878. })();
  16879. BABYLON.IntersectionInfo = IntersectionInfo;
  16880. var PickingInfo = (function () {
  16881. function PickingInfo() {
  16882. this.hit = false;
  16883. this.distance = 0;
  16884. this.pickedPoint = null;
  16885. this.pickedMesh = null;
  16886. this.bu = 0;
  16887. this.bv = 0;
  16888. this.faceId = -1;
  16889. this.subMeshId = 0;
  16890. }
  16891. // Methods
  16892. PickingInfo.prototype.getNormal = function () {
  16893. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16894. return null;
  16895. }
  16896. var indices = this.pickedMesh.getIndices();
  16897. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16898. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16899. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16900. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16901. normal0 = normal0.scale(this.bu);
  16902. normal1 = normal1.scale(this.bv);
  16903. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16904. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16905. };
  16906. PickingInfo.prototype.getTextureCoordinates = function () {
  16907. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16908. return null;
  16909. }
  16910. var indices = this.pickedMesh.getIndices();
  16911. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16912. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16913. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16914. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16915. uv0 = uv0.scale(this.bu);
  16916. uv1 = uv1.scale(this.bv);
  16917. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16918. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16919. };
  16920. return PickingInfo;
  16921. })();
  16922. BABYLON.PickingInfo = PickingInfo;
  16923. })(BABYLON || (BABYLON = {}));
  16924. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16925. (function (BABYLON) {
  16926. var FilesInput = (function () {
  16927. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16928. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16929. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16930. this.engine = p_engine;
  16931. this.canvas = p_canvas;
  16932. this.currentScene = p_scene;
  16933. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16934. this.progressCallback = p_progressCallback;
  16935. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16936. this.textureLoadingCallback = p_textureLoadingCallback;
  16937. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16938. }
  16939. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16940. var _this = this;
  16941. if (p_elementToMonitor) {
  16942. this.elementToMonitor = p_elementToMonitor;
  16943. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16944. _this.drag(e);
  16945. }, false);
  16946. this.elementToMonitor.addEventListener("dragover", function (e) {
  16947. _this.drag(e);
  16948. }, false);
  16949. this.elementToMonitor.addEventListener("drop", function (e) {
  16950. _this.drop(e);
  16951. }, false);
  16952. }
  16953. };
  16954. FilesInput.prototype.renderFunction = function () {
  16955. if (this.additionnalRenderLoopLogicCallback) {
  16956. this.additionnalRenderLoopLogicCallback();
  16957. }
  16958. if (this.currentScene) {
  16959. if (this.textureLoadingCallback) {
  16960. var remaining = this.currentScene.getWaitingItemsCount();
  16961. if (remaining > 0) {
  16962. this.textureLoadingCallback(remaining);
  16963. }
  16964. }
  16965. this.currentScene.render();
  16966. }
  16967. };
  16968. FilesInput.prototype.drag = function (e) {
  16969. e.stopPropagation();
  16970. e.preventDefault();
  16971. };
  16972. FilesInput.prototype.drop = function (eventDrop) {
  16973. eventDrop.stopPropagation();
  16974. eventDrop.preventDefault();
  16975. this.loadFiles(eventDrop);
  16976. };
  16977. FilesInput.prototype.loadFiles = function (event) {
  16978. var _this = this;
  16979. var that = this;
  16980. if (this.startingProcessingFilesCallback)
  16981. this.startingProcessingFilesCallback();
  16982. var sceneFileToLoad;
  16983. var filesToLoad;
  16984. // Handling data transfer via drag'n'drop
  16985. if (event && event.dataTransfer && event.dataTransfer.files) {
  16986. filesToLoad = event.dataTransfer.files;
  16987. }
  16988. // Handling files from input files
  16989. if (event && event.target && event.target.files) {
  16990. filesToLoad = event.target.files;
  16991. }
  16992. if (filesToLoad && filesToLoad.length > 0) {
  16993. for (var i = 0; i < filesToLoad.length; i++) {
  16994. switch (filesToLoad[i].type) {
  16995. case "image/jpeg":
  16996. case "image/png":
  16997. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16998. break;
  16999. case "image/targa":
  17000. case "image/vnd.ms-dds":
  17001. case "audio/wav":
  17002. case "audio/x-wav":
  17003. case "audio/mp3":
  17004. case "audio/mpeg":
  17005. case "audio/mpeg3":
  17006. case "audio/x-mpeg-3":
  17007. case "audio/ogg":
  17008. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  17009. break;
  17010. default:
  17011. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17012. sceneFileToLoad = filesToLoad[i];
  17013. }
  17014. break;
  17015. }
  17016. }
  17017. // If a ".babylon" file has been provided
  17018. if (sceneFileToLoad) {
  17019. if (this.currentScene) {
  17020. this.engine.stopRenderLoop();
  17021. this.currentScene.dispose();
  17022. }
  17023. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  17024. that.currentScene = newScene;
  17025. // Wait for textures and shaders to be ready
  17026. that.currentScene.executeWhenReady(function () {
  17027. // Attach camera to canvas inputs
  17028. if (that.currentScene.activeCamera) {
  17029. that.currentScene.activeCamera.attachControl(that.canvas);
  17030. }
  17031. if (that.sceneLoadedCallback) {
  17032. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  17033. }
  17034. that.engine.runRenderLoop(function () {
  17035. that.renderFunction();
  17036. });
  17037. });
  17038. }, function (progress) {
  17039. if (_this.progressCallback) {
  17040. _this.progressCallback(progress);
  17041. }
  17042. });
  17043. }
  17044. else {
  17045. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17046. }
  17047. }
  17048. };
  17049. FilesInput.FilesTextures = new Array();
  17050. FilesInput.FilesToLoad = new Array();
  17051. return FilesInput;
  17052. })();
  17053. BABYLON.FilesInput = FilesInput;
  17054. })(BABYLON || (BABYLON = {}));
  17055. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17056. (function (BABYLON) {
  17057. var OimoJSPlugin = (function () {
  17058. function OimoJSPlugin() {
  17059. this._registeredMeshes = [];
  17060. /**
  17061. * Update the body position according to the mesh position
  17062. * @param mesh
  17063. */
  17064. this.updateBodyPosition = function (mesh) {
  17065. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17066. var registeredMesh = this._registeredMeshes[index];
  17067. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17068. var body = registeredMesh.body.body;
  17069. mesh.computeWorldMatrix(true);
  17070. var center = mesh.getBoundingInfo().boundingBox.center;
  17071. body.setPosition(center.x, center.y, center.z);
  17072. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17073. return;
  17074. }
  17075. // Case where the parent has been updated
  17076. if (registeredMesh.mesh.parent === mesh) {
  17077. mesh.computeWorldMatrix(true);
  17078. registeredMesh.mesh.computeWorldMatrix(true);
  17079. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17080. var absoluteRotation = mesh.rotation;
  17081. body = registeredMesh.body.body;
  17082. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17083. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17084. return;
  17085. }
  17086. }
  17087. };
  17088. }
  17089. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17090. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17091. };
  17092. OimoJSPlugin.prototype.initialize = function (iterations) {
  17093. this._world = new OIMO.World();
  17094. this._world.clear();
  17095. };
  17096. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17097. this._world.gravity = gravity;
  17098. };
  17099. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17100. var body = null;
  17101. this.unregisterMesh(mesh);
  17102. mesh.computeWorldMatrix(true);
  17103. var initialRotation = null;
  17104. if (mesh.rotationQuaternion) {
  17105. initialRotation = mesh.rotationQuaternion.clone();
  17106. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17107. mesh.computeWorldMatrix(true);
  17108. }
  17109. var bbox = mesh.getBoundingInfo().boundingBox;
  17110. // The delta between the mesh position and the mesh bounding box center
  17111. var deltaPosition = mesh.position.subtract(bbox.center);
  17112. // Transform delta position with the rotation
  17113. if (initialRotation) {
  17114. var m = new BABYLON.Matrix();
  17115. initialRotation.toRotationMatrix(m);
  17116. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17117. }
  17118. switch (impostor) {
  17119. case BABYLON.PhysicsEngine.SphereImpostor:
  17120. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17121. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17122. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17123. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17124. body = new OIMO.Body({
  17125. type: 'sphere',
  17126. size: [size],
  17127. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17128. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17129. move: options.mass != 0,
  17130. config: [options.mass, options.friction, options.restitution],
  17131. world: this._world
  17132. });
  17133. break;
  17134. case BABYLON.PhysicsEngine.PlaneImpostor:
  17135. case BABYLON.PhysicsEngine.CylinderImpostor:
  17136. case BABYLON.PhysicsEngine.BoxImpostor:
  17137. var min = bbox.minimumWorld;
  17138. var max = bbox.maximumWorld;
  17139. var box = max.subtract(min);
  17140. var sizeX = this._checkWithEpsilon(box.x);
  17141. var sizeY = this._checkWithEpsilon(box.y);
  17142. var sizeZ = this._checkWithEpsilon(box.z);
  17143. body = new OIMO.Body({
  17144. type: 'box',
  17145. size: [sizeX, sizeY, sizeZ],
  17146. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17147. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17148. move: options.mass != 0,
  17149. config: [options.mass, options.friction, options.restitution],
  17150. world: this._world
  17151. });
  17152. break;
  17153. }
  17154. //If quaternion was set as the rotation of the object
  17155. if (initialRotation) {
  17156. //We have to access the rigid body's properties to set the quaternion.
  17157. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17158. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17159. //update the internal rotation matrix
  17160. body.body.syncShapes();
  17161. }
  17162. this._registeredMeshes.push({
  17163. mesh: mesh,
  17164. body: body,
  17165. delta: deltaPosition
  17166. });
  17167. return body;
  17168. };
  17169. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17170. var types = [], sizes = [], positions = [], rotations = [];
  17171. var initialMesh = parts[0].mesh;
  17172. for (var index = 0; index < parts.length; index++) {
  17173. var part = parts[index];
  17174. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17175. types.push(bodyParameters.type);
  17176. sizes.push.apply(sizes, bodyParameters.size);
  17177. positions.push.apply(positions, bodyParameters.pos);
  17178. rotations.push.apply(rotations, bodyParameters.rot);
  17179. }
  17180. var body = new OIMO.Body({
  17181. type: types,
  17182. size: sizes,
  17183. pos: positions,
  17184. rot: rotations,
  17185. move: options.mass != 0,
  17186. config: [options.mass, options.friction, options.restitution],
  17187. world: this._world
  17188. });
  17189. this._registeredMeshes.push({
  17190. mesh: initialMesh,
  17191. body: body
  17192. });
  17193. return body;
  17194. };
  17195. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17196. var bodyParameters = null;
  17197. var mesh = part.mesh;
  17198. // We need the bounding box/sphere info to compute the physics body
  17199. mesh.computeWorldMatrix();
  17200. switch (part.impostor) {
  17201. case BABYLON.PhysicsEngine.SphereImpostor:
  17202. var bbox = mesh.getBoundingInfo().boundingBox;
  17203. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17204. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17205. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17206. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17207. bodyParameters = {
  17208. type: 'sphere',
  17209. /* bug with oimo : sphere needs 3 sizes in this case */
  17210. size: [size, -1, -1],
  17211. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17212. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17213. };
  17214. break;
  17215. case BABYLON.PhysicsEngine.PlaneImpostor:
  17216. case BABYLON.PhysicsEngine.BoxImpostor:
  17217. bbox = mesh.getBoundingInfo().boundingBox;
  17218. var min = bbox.minimumWorld;
  17219. var max = bbox.maximumWorld;
  17220. var box = max.subtract(min);
  17221. var sizeX = this._checkWithEpsilon(box.x);
  17222. var sizeY = this._checkWithEpsilon(box.y);
  17223. var sizeZ = this._checkWithEpsilon(box.z);
  17224. var relativePosition = mesh.position;
  17225. bodyParameters = {
  17226. type: 'box',
  17227. size: [sizeX, sizeY, sizeZ],
  17228. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17229. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17230. };
  17231. break;
  17232. }
  17233. return bodyParameters;
  17234. };
  17235. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17236. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17237. var registeredMesh = this._registeredMeshes[index];
  17238. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17239. if (registeredMesh.body) {
  17240. this._world.removeRigidBody(registeredMesh.body.body);
  17241. this._unbindBody(registeredMesh.body);
  17242. }
  17243. this._registeredMeshes.splice(index, 1);
  17244. return;
  17245. }
  17246. }
  17247. };
  17248. OimoJSPlugin.prototype._unbindBody = function (body) {
  17249. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17250. var registeredMesh = this._registeredMeshes[index];
  17251. if (registeredMesh.body === body) {
  17252. registeredMesh.body = null;
  17253. }
  17254. }
  17255. };
  17256. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17257. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17258. var registeredMesh = this._registeredMeshes[index];
  17259. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17260. // Get object mass to have a behaviour similar to cannon.js
  17261. var mass = registeredMesh.body.body.massInfo.mass;
  17262. // The force is scaled with the mass of object
  17263. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17264. return;
  17265. }
  17266. }
  17267. };
  17268. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17269. var body1 = null, body2 = null;
  17270. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17271. var registeredMesh = this._registeredMeshes[index];
  17272. if (registeredMesh.mesh === mesh1) {
  17273. body1 = registeredMesh.body.body;
  17274. }
  17275. else if (registeredMesh.mesh === mesh2) {
  17276. body2 = registeredMesh.body.body;
  17277. }
  17278. }
  17279. if (!body1 || !body2) {
  17280. return false;
  17281. }
  17282. if (!options) {
  17283. options = {};
  17284. }
  17285. new OIMO.Link({
  17286. type: options.type,
  17287. body1: body1,
  17288. body2: body2,
  17289. min: options.min,
  17290. max: options.max,
  17291. axe1: options.axe1,
  17292. axe2: options.axe2,
  17293. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17294. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17295. collision: options.collision,
  17296. spring: options.spring,
  17297. world: this._world
  17298. });
  17299. return true;
  17300. };
  17301. OimoJSPlugin.prototype.dispose = function () {
  17302. this._world.clear();
  17303. while (this._registeredMeshes.length) {
  17304. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17305. }
  17306. };
  17307. OimoJSPlugin.prototype.isSupported = function () {
  17308. return OIMO !== undefined;
  17309. };
  17310. OimoJSPlugin.prototype._getLastShape = function (body) {
  17311. var lastShape = body.shapes;
  17312. while (lastShape.next) {
  17313. lastShape = lastShape.next;
  17314. }
  17315. return lastShape;
  17316. };
  17317. OimoJSPlugin.prototype.runOneStep = function (time) {
  17318. this._world.step();
  17319. // Update the position of all registered meshes
  17320. var i = this._registeredMeshes.length;
  17321. var m;
  17322. while (i--) {
  17323. var body = this._registeredMeshes[i].body.body;
  17324. var mesh = this._registeredMeshes[i].mesh;
  17325. var delta = this._registeredMeshes[i].delta;
  17326. if (!body.sleeping) {
  17327. if (body.shapes.next) {
  17328. var parentShape = this._getLastShape(body);
  17329. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17330. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17331. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17332. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17333. if (!mesh.rotationQuaternion) {
  17334. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17335. }
  17336. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17337. mesh.computeWorldMatrix();
  17338. }
  17339. else {
  17340. m = body.getMatrix();
  17341. mtx = BABYLON.Matrix.FromArray(m);
  17342. // Body position
  17343. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17344. if (!delta) {
  17345. mesh.position.x = bodyX;
  17346. mesh.position.y = bodyY;
  17347. mesh.position.z = bodyZ;
  17348. }
  17349. else {
  17350. mesh.position.x = bodyX + delta.x;
  17351. mesh.position.y = bodyY + delta.y;
  17352. mesh.position.z = bodyZ + delta.z;
  17353. }
  17354. if (!mesh.rotationQuaternion) {
  17355. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17356. }
  17357. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17358. mesh.computeWorldMatrix();
  17359. }
  17360. }
  17361. }
  17362. };
  17363. return OimoJSPlugin;
  17364. })();
  17365. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17366. })(BABYLON || (BABYLON = {}));
  17367. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17368. (function (BABYLON) {
  17369. var PhysicsEngine = (function () {
  17370. function PhysicsEngine(plugin) {
  17371. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17372. }
  17373. PhysicsEngine.prototype._initialize = function (gravity) {
  17374. this._currentPlugin.initialize();
  17375. this._setGravity(gravity);
  17376. };
  17377. PhysicsEngine.prototype._runOneStep = function (delta) {
  17378. if (delta > 0.1) {
  17379. delta = 0.1;
  17380. }
  17381. else if (delta <= 0) {
  17382. delta = 1.0 / 60.0;
  17383. }
  17384. this._currentPlugin.runOneStep(delta);
  17385. };
  17386. PhysicsEngine.prototype._setGravity = function (gravity) {
  17387. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17388. this._currentPlugin.setGravity(this.gravity);
  17389. };
  17390. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17391. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17392. };
  17393. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17394. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17395. };
  17396. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17397. this._currentPlugin.unregisterMesh(mesh);
  17398. };
  17399. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17400. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17401. };
  17402. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17403. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17404. };
  17405. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17406. this._currentPlugin.updateBodyPosition(mesh);
  17407. };
  17408. PhysicsEngine.prototype.dispose = function () {
  17409. this._currentPlugin.dispose();
  17410. };
  17411. PhysicsEngine.prototype.isSupported = function () {
  17412. return this._currentPlugin.isSupported();
  17413. };
  17414. // Statics
  17415. PhysicsEngine.NoImpostor = 0;
  17416. PhysicsEngine.SphereImpostor = 1;
  17417. PhysicsEngine.BoxImpostor = 2;
  17418. PhysicsEngine.PlaneImpostor = 3;
  17419. PhysicsEngine.MeshImpostor = 4;
  17420. PhysicsEngine.CapsuleImpostor = 5;
  17421. PhysicsEngine.ConeImpostor = 6;
  17422. PhysicsEngine.CylinderImpostor = 7;
  17423. PhysicsEngine.ConvexHullImpostor = 8;
  17424. PhysicsEngine.Epsilon = 0.001;
  17425. return PhysicsEngine;
  17426. })();
  17427. BABYLON.PhysicsEngine = PhysicsEngine;
  17428. })(BABYLON || (BABYLON = {}));
  17429. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17430. (function (BABYLON) {
  17431. var serializeLight = function (light) {
  17432. var serializationObject = {};
  17433. serializationObject.name = light.name;
  17434. serializationObject.id = light.id;
  17435. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17436. if (light instanceof BABYLON.PointLight) {
  17437. serializationObject.type = 0;
  17438. serializationObject.position = light.position.asArray();
  17439. }
  17440. else if (light instanceof BABYLON.DirectionalLight) {
  17441. serializationObject.type = 1;
  17442. var directionalLight = light;
  17443. serializationObject.position = directionalLight.position.asArray();
  17444. serializationObject.direction = directionalLight.direction.asArray();
  17445. }
  17446. else if (light instanceof BABYLON.SpotLight) {
  17447. serializationObject.type = 2;
  17448. var spotLight = light;
  17449. serializationObject.position = spotLight.position.asArray();
  17450. serializationObject.direction = spotLight.position.asArray();
  17451. serializationObject.angle = spotLight.angle;
  17452. serializationObject.exponent = spotLight.exponent;
  17453. }
  17454. else if (light instanceof BABYLON.HemisphericLight) {
  17455. serializationObject.type = 3;
  17456. var hemisphericLight = light;
  17457. serializationObject.direction = hemisphericLight.direction.asArray();
  17458. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17459. }
  17460. if (light.intensity) {
  17461. serializationObject.intensity = light.intensity;
  17462. }
  17463. serializationObject.range = light.range;
  17464. serializationObject.diffuse = light.diffuse.asArray();
  17465. serializationObject.specular = light.specular.asArray();
  17466. return serializationObject;
  17467. };
  17468. var serializeFresnelParameter = function (fresnelParameter) {
  17469. var serializationObject = {};
  17470. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17471. serializationObject.leftColor = fresnelParameter.leftColor;
  17472. serializationObject.rightColor = fresnelParameter.rightColor;
  17473. serializationObject.bias = fresnelParameter.bias;
  17474. serializationObject.power = fresnelParameter.power;
  17475. return serializationObject;
  17476. };
  17477. var serializeCamera = function (camera) {
  17478. var serializationObject = {};
  17479. serializationObject.name = camera.name;
  17480. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17481. serializationObject.id = camera.id;
  17482. serializationObject.position = camera.position.asArray();
  17483. // Parent
  17484. if (camera.parent) {
  17485. serializationObject.parentId = camera.parent.id;
  17486. }
  17487. // Target
  17488. serializationObject.rotation = camera.rotation.asArray();
  17489. // Locked target
  17490. if (camera.lockedTarget && camera.lockedTarget.id) {
  17491. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17492. }
  17493. serializationObject.fov = camera.fov;
  17494. serializationObject.minZ = camera.minZ;
  17495. serializationObject.maxZ = camera.maxZ;
  17496. serializationObject.speed = camera.speed;
  17497. serializationObject.inertia = camera.inertia;
  17498. serializationObject.checkCollisions = camera.checkCollisions;
  17499. serializationObject.applyGravity = camera.applyGravity;
  17500. if (camera.ellipsoid) {
  17501. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17502. }
  17503. // Animations
  17504. appendAnimations(camera, serializationObject);
  17505. // Layer mask
  17506. serializationObject.layerMask = camera.layerMask;
  17507. return serializationObject;
  17508. };
  17509. var appendAnimations = function (source, destination) {
  17510. if (source.animations) {
  17511. destination.animations = [];
  17512. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17513. var animation = source.animations[animationIndex];
  17514. destination.animations.push(serializeAnimation(animation));
  17515. }
  17516. }
  17517. };
  17518. var serializeAnimation = function (animation) {
  17519. var serializationObject = {};
  17520. serializationObject.name = animation.name;
  17521. serializationObject.property = animation.targetProperty;
  17522. serializationObject.framePerSecond = animation.framePerSecond;
  17523. serializationObject.dataType = animation.dataType;
  17524. serializationObject.loopBehavior = animation.loopMode;
  17525. var dataType = animation.dataType;
  17526. serializationObject.keys = [];
  17527. var keys = animation.getKeys();
  17528. for (var index = 0; index < keys.length; index++) {
  17529. var animationKey = keys[index];
  17530. var key = {};
  17531. key.frame = animationKey.frame;
  17532. switch (dataType) {
  17533. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17534. key.values = [animationKey.value];
  17535. break;
  17536. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17537. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17538. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17539. key.values = animationKey.value.asArray();
  17540. break;
  17541. }
  17542. serializationObject.keys.push(key);
  17543. }
  17544. return serializationObject;
  17545. };
  17546. var serializeMultiMaterial = function (material) {
  17547. var serializationObject = {};
  17548. serializationObject.name = material.name;
  17549. serializationObject.id = material.id;
  17550. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17551. serializationObject.materials = [];
  17552. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17553. var subMat = material.subMaterials[matIndex];
  17554. if (subMat) {
  17555. serializationObject.materials.push(subMat.id);
  17556. }
  17557. else {
  17558. serializationObject.materials.push(null);
  17559. }
  17560. }
  17561. return serializationObject;
  17562. };
  17563. var serializeMaterial = function (material) {
  17564. var serializationObject = {};
  17565. serializationObject.name = material.name;
  17566. serializationObject.ambient = material.ambientColor.asArray();
  17567. serializationObject.diffuse = material.diffuseColor.asArray();
  17568. serializationObject.specular = material.specularColor.asArray();
  17569. serializationObject.specularPower = material.specularPower;
  17570. serializationObject.emissive = material.emissiveColor.asArray();
  17571. serializationObject.alpha = material.alpha;
  17572. serializationObject.id = material.id;
  17573. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17574. serializationObject.backFaceCulling = material.backFaceCulling;
  17575. if (material.diffuseTexture) {
  17576. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17577. }
  17578. if (material.diffuseFresnelParameters) {
  17579. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17580. }
  17581. if (material.ambientTexture) {
  17582. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17583. }
  17584. if (material.opacityTexture) {
  17585. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17586. }
  17587. if (material.opacityFresnelParameters) {
  17588. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17589. }
  17590. if (material.reflectionTexture) {
  17591. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17592. }
  17593. if (material.reflectionFresnelParameters) {
  17594. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17595. }
  17596. if (material.emissiveTexture) {
  17597. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17598. }
  17599. if (material.emissiveFresnelParameters) {
  17600. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17601. }
  17602. if (material.specularTexture) {
  17603. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17604. }
  17605. if (material.bumpTexture) {
  17606. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17607. }
  17608. return serializationObject;
  17609. };
  17610. var serializeTexture = function (texture) {
  17611. var serializationObject = {};
  17612. if (!texture.name) {
  17613. return null;
  17614. }
  17615. if (texture instanceof BABYLON.CubeTexture) {
  17616. serializationObject.name = texture.name;
  17617. serializationObject.hasAlpha = texture.hasAlpha;
  17618. serializationObject.level = texture.level;
  17619. serializationObject.coordinatesMode = texture.coordinatesMode;
  17620. return serializationObject;
  17621. }
  17622. if (texture instanceof BABYLON.MirrorTexture) {
  17623. var mirrorTexture = texture;
  17624. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17625. serializationObject.renderList = [];
  17626. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17627. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17628. }
  17629. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17630. }
  17631. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17632. var renderTargetTexture = texture;
  17633. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17634. serializationObject.renderList = [];
  17635. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17636. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17637. }
  17638. }
  17639. var regularTexture = texture;
  17640. serializationObject.name = texture.name;
  17641. serializationObject.hasAlpha = texture.hasAlpha;
  17642. serializationObject.level = texture.level;
  17643. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17644. serializationObject.coordinatesMode = texture.coordinatesMode;
  17645. serializationObject.uOffset = regularTexture.uOffset;
  17646. serializationObject.vOffset = regularTexture.vOffset;
  17647. serializationObject.uScale = regularTexture.uScale;
  17648. serializationObject.vScale = regularTexture.vScale;
  17649. serializationObject.uAng = regularTexture.uAng;
  17650. serializationObject.vAng = regularTexture.vAng;
  17651. serializationObject.wAng = regularTexture.wAng;
  17652. serializationObject.wrapU = texture.wrapU;
  17653. serializationObject.wrapV = texture.wrapV;
  17654. // Animations
  17655. appendAnimations(texture, serializationObject);
  17656. return serializationObject;
  17657. };
  17658. var serializeSkeleton = function (skeleton) {
  17659. var serializationObject = {};
  17660. serializationObject.name = skeleton.name;
  17661. serializationObject.id = skeleton.id;
  17662. serializationObject.bones = [];
  17663. for (var index = 0; index < skeleton.bones.length; index++) {
  17664. var bone = skeleton.bones[index];
  17665. var serializedBone = {
  17666. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17667. name: bone.name,
  17668. matrix: bone.getLocalMatrix().toArray()
  17669. };
  17670. serializationObject.bones.push(serializedBone);
  17671. if (bone.animations && bone.animations.length > 0) {
  17672. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17673. }
  17674. }
  17675. return serializationObject;
  17676. };
  17677. var serializeParticleSystem = function (particleSystem) {
  17678. var serializationObject = {};
  17679. serializationObject.emitterId = particleSystem.emitter.id;
  17680. serializationObject.capacity = particleSystem.getCapacity();
  17681. if (particleSystem.particleTexture) {
  17682. serializationObject.textureName = particleSystem.particleTexture.name;
  17683. }
  17684. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17685. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17686. serializationObject.minSize = particleSystem.minSize;
  17687. serializationObject.maxSize = particleSystem.maxSize;
  17688. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17689. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17690. serializationObject.emitRate = particleSystem.emitRate;
  17691. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17692. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17693. serializationObject.gravity = particleSystem.gravity.asArray();
  17694. serializationObject.direction1 = particleSystem.direction1.asArray();
  17695. serializationObject.direction2 = particleSystem.direction2.asArray();
  17696. serializationObject.color1 = particleSystem.color1.asArray();
  17697. serializationObject.color2 = particleSystem.color2.asArray();
  17698. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17699. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17700. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17701. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17702. serializationObject.blendMode = particleSystem.blendMode;
  17703. return serializationObject;
  17704. };
  17705. var serializeLensFlareSystem = function (lensFlareSystem) {
  17706. var serializationObject = {};
  17707. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17708. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17709. serializationObject.flares = [];
  17710. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17711. var flare = lensFlareSystem.lensFlares[index];
  17712. serializationObject.flares.push({
  17713. size: flare.size,
  17714. position: flare.position,
  17715. color: flare.color.asArray(),
  17716. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17717. });
  17718. }
  17719. return serializationObject;
  17720. };
  17721. var serializeShadowGenerator = function (light) {
  17722. var serializationObject = {};
  17723. var shadowGenerator = light.getShadowGenerator();
  17724. serializationObject.lightId = light.id;
  17725. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17726. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17727. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17728. serializationObject.renderList = [];
  17729. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17730. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17731. serializationObject.renderList.push(mesh.id);
  17732. }
  17733. return serializationObject;
  17734. };
  17735. var serializedGeometries = [];
  17736. var serializeGeometry = function (geometry, serializationGeometries) {
  17737. if (serializedGeometries[geometry.id]) {
  17738. return;
  17739. }
  17740. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17741. serializationGeometries.boxes.push(serializeBox(geometry));
  17742. }
  17743. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17744. serializationGeometries.spheres.push(serializeSphere(geometry));
  17745. }
  17746. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17747. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17748. }
  17749. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17750. serializationGeometries.toruses.push(serializeTorus(geometry));
  17751. }
  17752. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17753. serializationGeometries.grounds.push(serializeGround(geometry));
  17754. }
  17755. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17756. serializationGeometries.planes.push(serializePlane(geometry));
  17757. }
  17758. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17759. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17760. }
  17761. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17762. throw new Error("Unknow primitive type");
  17763. }
  17764. else {
  17765. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17766. }
  17767. serializedGeometries[geometry.id] = true;
  17768. };
  17769. var serializeGeometryBase = function (geometry) {
  17770. var serializationObject = {};
  17771. serializationObject.id = geometry.id;
  17772. if (BABYLON.Tags.HasTags(geometry)) {
  17773. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17774. }
  17775. return serializationObject;
  17776. };
  17777. var serializeVertexData = function (vertexData) {
  17778. var serializationObject = serializeGeometryBase(vertexData);
  17779. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17780. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17781. }
  17782. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17783. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17784. }
  17785. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17786. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17787. }
  17788. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17789. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17790. }
  17791. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17792. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17793. }
  17794. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17795. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17796. serializationObject.matricesIndices._isExpanded = true;
  17797. }
  17798. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17799. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17800. }
  17801. serializationObject.indices = vertexData.getIndices();
  17802. return serializationObject;
  17803. };
  17804. var serializePrimitive = function (primitive) {
  17805. var serializationObject = serializeGeometryBase(primitive);
  17806. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17807. return serializationObject;
  17808. };
  17809. var serializeBox = function (box) {
  17810. var serializationObject = serializePrimitive(box);
  17811. serializationObject.size = box.size;
  17812. return serializationObject;
  17813. };
  17814. var serializeSphere = function (sphere) {
  17815. var serializationObject = serializePrimitive(sphere);
  17816. serializationObject.segments = sphere.segments;
  17817. serializationObject.diameter = sphere.diameter;
  17818. return serializationObject;
  17819. };
  17820. var serializeCylinder = function (cylinder) {
  17821. var serializationObject = serializePrimitive(cylinder);
  17822. serializationObject.height = cylinder.height;
  17823. serializationObject.diameterTop = cylinder.diameterTop;
  17824. serializationObject.diameterBottom = cylinder.diameterBottom;
  17825. serializationObject.tessellation = cylinder.tessellation;
  17826. return serializationObject;
  17827. };
  17828. var serializeTorus = function (torus) {
  17829. var serializationObject = serializePrimitive(torus);
  17830. serializationObject.diameter = torus.diameter;
  17831. serializationObject.thickness = torus.thickness;
  17832. serializationObject.tessellation = torus.tessellation;
  17833. return serializationObject;
  17834. };
  17835. var serializeGround = function (ground) {
  17836. var serializationObject = serializePrimitive(ground);
  17837. serializationObject.width = ground.width;
  17838. serializationObject.height = ground.height;
  17839. serializationObject.subdivisions = ground.subdivisions;
  17840. return serializationObject;
  17841. };
  17842. var serializePlane = function (plane) {
  17843. var serializationObject = serializePrimitive(plane);
  17844. serializationObject.size = plane.size;
  17845. return serializationObject;
  17846. };
  17847. var serializeTorusKnot = function (torusKnot) {
  17848. var serializationObject = serializePrimitive(torusKnot);
  17849. serializationObject.radius = torusKnot.radius;
  17850. serializationObject.tube = torusKnot.tube;
  17851. serializationObject.radialSegments = torusKnot.radialSegments;
  17852. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17853. serializationObject.p = torusKnot.p;
  17854. serializationObject.q = torusKnot.q;
  17855. return serializationObject;
  17856. };
  17857. var serializeMesh = function (mesh, serializationScene) {
  17858. var serializationObject = {};
  17859. serializationObject.name = mesh.name;
  17860. serializationObject.id = mesh.id;
  17861. if (BABYLON.Tags.HasTags(mesh)) {
  17862. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17863. }
  17864. serializationObject.position = mesh.position.asArray();
  17865. if (mesh.rotationQuaternion) {
  17866. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17867. }
  17868. else if (mesh.rotation) {
  17869. serializationObject.rotation = mesh.rotation.asArray();
  17870. }
  17871. serializationObject.scaling = mesh.scaling.asArray();
  17872. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17873. serializationObject.isEnabled = mesh.isEnabled();
  17874. serializationObject.isVisible = mesh.isVisible;
  17875. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17876. serializationObject.pickable = mesh.isPickable;
  17877. serializationObject.receiveShadows = mesh.receiveShadows;
  17878. serializationObject.billboardMode = mesh.billboardMode;
  17879. serializationObject.visibility = mesh.visibility;
  17880. serializationObject.checkCollisions = mesh.checkCollisions;
  17881. // Parent
  17882. if (mesh.parent) {
  17883. serializationObject.parentId = mesh.parent.id;
  17884. }
  17885. // Geometry
  17886. var geometry = mesh._geometry;
  17887. if (geometry) {
  17888. var geometryId = geometry.id;
  17889. serializationObject.geometryId = geometryId;
  17890. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17891. // 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
  17892. serializeGeometry(geometry, serializationScene.geometries);
  17893. }
  17894. // SubMeshes
  17895. serializationObject.subMeshes = [];
  17896. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17897. var subMesh = mesh.subMeshes[subIndex];
  17898. serializationObject.subMeshes.push({
  17899. materialIndex: subMesh.materialIndex,
  17900. verticesStart: subMesh.verticesStart,
  17901. verticesCount: subMesh.verticesCount,
  17902. indexStart: subMesh.indexStart,
  17903. indexCount: subMesh.indexCount
  17904. });
  17905. }
  17906. }
  17907. // Material
  17908. if (mesh.material) {
  17909. serializationObject.materialId = mesh.material.id;
  17910. }
  17911. else {
  17912. mesh.material = null;
  17913. }
  17914. // Skeleton
  17915. if (mesh.skeleton) {
  17916. serializationObject.skeletonId = mesh.skeleton.id;
  17917. }
  17918. // Physics
  17919. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17920. serializationObject.physicsMass = mesh.getPhysicsMass();
  17921. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17922. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17923. switch (mesh.getPhysicsImpostor()) {
  17924. case BABYLON.PhysicsEngine.BoxImpostor:
  17925. serializationObject.physicsImpostor = 1;
  17926. break;
  17927. case BABYLON.PhysicsEngine.SphereImpostor:
  17928. serializationObject.physicsImpostor = 2;
  17929. break;
  17930. }
  17931. }
  17932. // Instances
  17933. serializationObject.instances = [];
  17934. for (var index = 0; index < mesh.instances.length; index++) {
  17935. var instance = mesh.instances[index];
  17936. var serializationInstance = {
  17937. name: instance.name,
  17938. position: instance.position,
  17939. rotation: instance.rotation,
  17940. rotationQuaternion: instance.rotationQuaternion,
  17941. scaling: instance.scaling
  17942. };
  17943. serializationObject.instances.push(serializationInstance);
  17944. // Animations
  17945. appendAnimations(instance, serializationInstance);
  17946. }
  17947. // Animations
  17948. appendAnimations(mesh, serializationObject);
  17949. // Layer mask
  17950. serializationObject.layerMask = mesh.layerMask;
  17951. return serializationObject;
  17952. };
  17953. var SceneSerializer = (function () {
  17954. function SceneSerializer() {
  17955. }
  17956. SceneSerializer.Serialize = function (scene) {
  17957. var serializationObject = {};
  17958. // Scene
  17959. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17960. serializationObject.autoClear = scene.autoClear;
  17961. serializationObject.clearColor = scene.clearColor.asArray();
  17962. serializationObject.ambientColor = scene.ambientColor.asArray();
  17963. serializationObject.gravity = scene.gravity.asArray();
  17964. // Fog
  17965. if (scene.fogMode && scene.fogMode !== 0) {
  17966. serializationObject.fogMode = scene.fogMode;
  17967. serializationObject.fogColor = scene.fogColor.asArray();
  17968. serializationObject.fogStart = scene.fogStart;
  17969. serializationObject.fogEnd = scene.fogEnd;
  17970. serializationObject.fogDensity = scene.fogDensity;
  17971. }
  17972. // Lights
  17973. serializationObject.lights = [];
  17974. for (var index = 0; index < scene.lights.length; index++) {
  17975. var light = scene.lights[index];
  17976. serializationObject.lights.push(serializeLight(light));
  17977. }
  17978. // Cameras
  17979. serializationObject.cameras = [];
  17980. for (index = 0; index < scene.cameras.length; index++) {
  17981. var camera = scene.cameras[index];
  17982. if (camera instanceof BABYLON.FreeCamera) {
  17983. serializationObject.cameras.push(serializeCamera(camera));
  17984. }
  17985. }
  17986. if (scene.activeCamera) {
  17987. serializationObject.activeCameraID = scene.activeCamera.id;
  17988. }
  17989. // Materials
  17990. serializationObject.materials = [];
  17991. serializationObject.multiMaterials = [];
  17992. for (index = 0; index < scene.materials.length; index++) {
  17993. var material = scene.materials[index];
  17994. if (material instanceof BABYLON.StandardMaterial) {
  17995. serializationObject.materials.push(serializeMaterial(material));
  17996. }
  17997. else if (material instanceof BABYLON.MultiMaterial) {
  17998. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17999. }
  18000. }
  18001. // Skeletons
  18002. serializationObject.skeletons = [];
  18003. for (index = 0; index < scene.skeletons.length; index++) {
  18004. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18005. }
  18006. // Geometries
  18007. serializationObject.geometries = {};
  18008. serializationObject.geometries.boxes = [];
  18009. serializationObject.geometries.spheres = [];
  18010. serializationObject.geometries.cylinders = [];
  18011. serializationObject.geometries.toruses = [];
  18012. serializationObject.geometries.grounds = [];
  18013. serializationObject.geometries.planes = [];
  18014. serializationObject.geometries.torusKnots = [];
  18015. serializationObject.geometries.vertexData = [];
  18016. serializedGeometries = [];
  18017. var geometries = scene.getGeometries();
  18018. for (var index = 0; index < geometries.length; index++) {
  18019. var geometry = geometries[index];
  18020. if (geometry.isReady()) {
  18021. serializeGeometry(geometry, serializationObject.geometries);
  18022. }
  18023. }
  18024. // Meshes
  18025. serializationObject.meshes = [];
  18026. for (index = 0; index < scene.meshes.length; index++) {
  18027. var abstractMesh = scene.meshes[index];
  18028. if (abstractMesh instanceof BABYLON.Mesh) {
  18029. var mesh = abstractMesh;
  18030. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18031. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18032. }
  18033. }
  18034. }
  18035. // Particles Systems
  18036. serializationObject.particleSystems = [];
  18037. for (index = 0; index < scene.particleSystems.length; index++) {
  18038. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18039. }
  18040. // Lens flares
  18041. serializationObject.lensFlareSystems = [];
  18042. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18043. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18044. }
  18045. // Shadows
  18046. serializationObject.shadowGenerators = [];
  18047. for (index = 0; index < scene.lights.length; index++) {
  18048. light = scene.lights[index];
  18049. if (light.getShadowGenerator()) {
  18050. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18051. }
  18052. }
  18053. return serializationObject;
  18054. };
  18055. return SceneSerializer;
  18056. })();
  18057. BABYLON.SceneSerializer = SceneSerializer;
  18058. })(BABYLON || (BABYLON = {}));
  18059. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18060. (function (BABYLON) {
  18061. var SceneLoader = (function () {
  18062. function SceneLoader() {
  18063. }
  18064. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18065. get: function () {
  18066. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18067. },
  18068. set: function (value) {
  18069. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18070. },
  18071. enumerable: true,
  18072. configurable: true
  18073. });
  18074. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18075. get: function () {
  18076. return SceneLoader._ShowLoadingScreen;
  18077. },
  18078. set: function (value) {
  18079. SceneLoader._ShowLoadingScreen = value;
  18080. },
  18081. enumerable: true,
  18082. configurable: true
  18083. });
  18084. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18085. var dotPosition = sceneFilename.lastIndexOf(".");
  18086. var queryStringPosition = sceneFilename.indexOf("?");
  18087. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18088. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18089. var plugin = this._registeredPlugins[index];
  18090. if (plugin.extensions.indexOf(extension) !== -1) {
  18091. return plugin;
  18092. }
  18093. }
  18094. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18095. };
  18096. // Public functions
  18097. SceneLoader.RegisterPlugin = function (plugin) {
  18098. plugin.extensions = plugin.extensions.toLowerCase();
  18099. SceneLoader._registeredPlugins.push(plugin);
  18100. };
  18101. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18102. var manifestChecked = function (success) {
  18103. scene.database = database;
  18104. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18105. var importMeshFromData = function (data) {
  18106. var meshes = [];
  18107. var particleSystems = [];
  18108. var skeletons = [];
  18109. try {
  18110. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18111. if (onerror) {
  18112. onerror(scene, 'unable to load the scene');
  18113. }
  18114. return;
  18115. }
  18116. }
  18117. catch (e) {
  18118. if (onerror) {
  18119. onerror(scene, e);
  18120. }
  18121. return;
  18122. }
  18123. if (onsuccess) {
  18124. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18125. onsuccess(meshes, particleSystems, skeletons);
  18126. }
  18127. };
  18128. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18129. // Direct load
  18130. importMeshFromData(sceneFilename.substr(5));
  18131. return;
  18132. }
  18133. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18134. importMeshFromData(data);
  18135. }, progressCallBack, database);
  18136. };
  18137. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18138. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18139. };
  18140. /**
  18141. * Load a scene
  18142. * @param rootUrl a string that defines the root url for scene and resources
  18143. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18144. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18145. */
  18146. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18147. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18148. };
  18149. /**
  18150. * Append a scene
  18151. * @param rootUrl a string that defines the root url for scene and resources
  18152. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18153. * @param scene is the instance of BABYLON.Scene to append to
  18154. */
  18155. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18156. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18157. var database;
  18158. if (SceneLoader.ShowLoadingScreen) {
  18159. scene.getEngine().displayLoadingUI();
  18160. }
  18161. var loadSceneFromData = function (data) {
  18162. scene.database = database;
  18163. if (!plugin.load(scene, data, rootUrl)) {
  18164. if (onerror) {
  18165. onerror(scene);
  18166. }
  18167. scene.getEngine().hideLoadingUI();
  18168. return;
  18169. }
  18170. if (onsuccess) {
  18171. onsuccess(scene);
  18172. }
  18173. if (SceneLoader.ShowLoadingScreen) {
  18174. scene.executeWhenReady(function () {
  18175. scene.getEngine().hideLoadingUI();
  18176. });
  18177. }
  18178. };
  18179. var manifestChecked = function (success) {
  18180. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18181. };
  18182. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18183. // Direct load
  18184. loadSceneFromData(sceneFilename.substr(5));
  18185. return;
  18186. }
  18187. if (rootUrl.indexOf("file:") === -1) {
  18188. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18189. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18190. }
  18191. else {
  18192. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18193. }
  18194. };
  18195. // Flags
  18196. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18197. SceneLoader._ShowLoadingScreen = true;
  18198. // Members
  18199. SceneLoader._registeredPlugins = new Array();
  18200. return SceneLoader;
  18201. })();
  18202. BABYLON.SceneLoader = SceneLoader;
  18203. ;
  18204. })(BABYLON || (BABYLON = {}));
  18205. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18206. (function (BABYLON) {
  18207. var Internals;
  18208. (function (Internals) {
  18209. var checkColors4 = function (colors, count) {
  18210. // Check if color3 was used
  18211. if (colors.length === count * 3) {
  18212. var colors4 = [];
  18213. for (var index = 0; index < colors.length; index += 3) {
  18214. var newIndex = (index / 3) * 4;
  18215. colors4[newIndex] = colors[index];
  18216. colors4[newIndex + 1] = colors[index + 1];
  18217. colors4[newIndex + 2] = colors[index + 2];
  18218. colors4[newIndex + 3] = 1.0;
  18219. }
  18220. return colors4;
  18221. }
  18222. return colors;
  18223. };
  18224. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18225. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18226. texture.name = parsedTexture.name;
  18227. texture.hasAlpha = parsedTexture.hasAlpha;
  18228. texture.level = parsedTexture.level;
  18229. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18230. return texture;
  18231. };
  18232. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18233. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18234. return null;
  18235. }
  18236. if (parsedTexture.isCube) {
  18237. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18238. }
  18239. var texture;
  18240. if (parsedTexture.mirrorPlane) {
  18241. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18242. texture._waitingRenderList = parsedTexture.renderList;
  18243. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18244. }
  18245. else if (parsedTexture.isRenderTarget) {
  18246. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18247. texture._waitingRenderList = parsedTexture.renderList;
  18248. }
  18249. else {
  18250. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18251. }
  18252. texture.name = parsedTexture.name;
  18253. texture.hasAlpha = parsedTexture.hasAlpha;
  18254. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18255. texture.level = parsedTexture.level;
  18256. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18257. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18258. texture.uOffset = parsedTexture.uOffset;
  18259. texture.vOffset = parsedTexture.vOffset;
  18260. texture.uScale = parsedTexture.uScale;
  18261. texture.vScale = parsedTexture.vScale;
  18262. texture.uAng = parsedTexture.uAng;
  18263. texture.vAng = parsedTexture.vAng;
  18264. texture.wAng = parsedTexture.wAng;
  18265. texture.wrapU = parsedTexture.wrapU;
  18266. texture.wrapV = parsedTexture.wrapV;
  18267. // Animations
  18268. if (parsedTexture.animations) {
  18269. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18270. var parsedAnimation = parsedTexture.animations[animationIndex];
  18271. texture.animations.push(parseAnimation(parsedAnimation));
  18272. }
  18273. }
  18274. return texture;
  18275. };
  18276. var parseSkeleton = function (parsedSkeleton, scene) {
  18277. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18278. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18279. var parsedBone = parsedSkeleton.bones[index];
  18280. var parentBone = null;
  18281. if (parsedBone.parentBoneIndex > -1) {
  18282. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18283. }
  18284. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18285. if (parsedBone.animation) {
  18286. bone.animations.push(parseAnimation(parsedBone.animation));
  18287. }
  18288. }
  18289. return skeleton;
  18290. };
  18291. var parseFresnelParameters = function (parsedFresnelParameters) {
  18292. var fresnelParameters = new BABYLON.FresnelParameters();
  18293. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18294. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18295. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18296. fresnelParameters.bias = parsedFresnelParameters.bias;
  18297. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18298. return fresnelParameters;
  18299. };
  18300. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18301. var material;
  18302. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18303. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18304. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18305. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18306. material.specularPower = parsedMaterial.specularPower;
  18307. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18308. material.alpha = parsedMaterial.alpha;
  18309. material.id = parsedMaterial.id;
  18310. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18311. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18312. material.wireframe = parsedMaterial.wireframe;
  18313. if (parsedMaterial.diffuseTexture) {
  18314. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18315. }
  18316. if (parsedMaterial.diffuseFresnelParameters) {
  18317. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18318. }
  18319. if (parsedMaterial.ambientTexture) {
  18320. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18321. }
  18322. if (parsedMaterial.opacityTexture) {
  18323. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18324. }
  18325. if (parsedMaterial.opacityFresnelParameters) {
  18326. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18327. }
  18328. if (parsedMaterial.reflectionTexture) {
  18329. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18330. }
  18331. if (parsedMaterial.reflectionFresnelParameters) {
  18332. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18333. }
  18334. if (parsedMaterial.emissiveTexture) {
  18335. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18336. }
  18337. if (parsedMaterial.emissiveFresnelParameters) {
  18338. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18339. }
  18340. if (parsedMaterial.specularTexture) {
  18341. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18342. }
  18343. if (parsedMaterial.bumpTexture) {
  18344. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18345. }
  18346. return material;
  18347. };
  18348. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18349. for (var index = 0; index < parsedData.materials.length; index++) {
  18350. var parsedMaterial = parsedData.materials[index];
  18351. if (parsedMaterial.id === id) {
  18352. return parseMaterial(parsedMaterial, scene, rootUrl);
  18353. }
  18354. }
  18355. return null;
  18356. };
  18357. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18358. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18359. multiMaterial.id = parsedMultiMaterial.id;
  18360. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18361. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18362. var subMatId = parsedMultiMaterial.materials[matIndex];
  18363. if (subMatId) {
  18364. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18365. }
  18366. else {
  18367. multiMaterial.subMaterials.push(null);
  18368. }
  18369. }
  18370. return multiMaterial;
  18371. };
  18372. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18373. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18374. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18375. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18376. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18377. var parsedFlare = parsedLensFlareSystem.flares[index];
  18378. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18379. }
  18380. return lensFlareSystem;
  18381. };
  18382. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18383. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18384. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18385. if (parsedParticleSystem.textureName) {
  18386. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18387. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18388. }
  18389. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18390. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18391. particleSystem.minSize = parsedParticleSystem.minSize;
  18392. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18393. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18394. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18395. particleSystem.emitter = emitter;
  18396. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18397. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18398. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18399. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18400. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18401. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18402. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18403. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18404. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18405. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18406. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18407. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18408. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18409. particleSystem.start();
  18410. return particleSystem;
  18411. };
  18412. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18413. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18414. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18415. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18416. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18417. shadowGenerator.getShadowMap().renderList.push(mesh);
  18418. }
  18419. if (parsedShadowGenerator.usePoissonSampling) {
  18420. shadowGenerator.usePoissonSampling = true;
  18421. }
  18422. else {
  18423. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18424. }
  18425. return shadowGenerator;
  18426. };
  18427. var parseAnimation = function (parsedAnimation) {
  18428. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18429. var dataType = parsedAnimation.dataType;
  18430. var keys = [];
  18431. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18432. var key = parsedAnimation.keys[index];
  18433. var data;
  18434. switch (dataType) {
  18435. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18436. data = key.values[0];
  18437. break;
  18438. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18439. data = BABYLON.Quaternion.FromArray(key.values);
  18440. break;
  18441. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18442. data = BABYLON.Matrix.FromArray(key.values);
  18443. break;
  18444. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18445. default:
  18446. data = BABYLON.Vector3.FromArray(key.values);
  18447. break;
  18448. }
  18449. keys.push({
  18450. frame: key.frame,
  18451. value: data
  18452. });
  18453. }
  18454. animation.setKeys(keys);
  18455. return animation;
  18456. };
  18457. var parseLight = function (parsedLight, scene) {
  18458. var light;
  18459. switch (parsedLight.type) {
  18460. case 0:
  18461. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18462. break;
  18463. case 1:
  18464. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18465. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18466. break;
  18467. case 2:
  18468. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18469. break;
  18470. case 3:
  18471. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18472. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18473. break;
  18474. }
  18475. light.id = parsedLight.id;
  18476. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18477. if (parsedLight.intensity !== undefined) {
  18478. light.intensity = parsedLight.intensity;
  18479. }
  18480. if (parsedLight.range) {
  18481. light.range = parsedLight.range;
  18482. }
  18483. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18484. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18485. if (parsedLight.excludedMeshesIds) {
  18486. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18487. }
  18488. // Parent
  18489. if (parsedLight.parentId) {
  18490. light._waitingParentId = parsedLight.parentId;
  18491. }
  18492. if (parsedLight.includedOnlyMeshesIds) {
  18493. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18494. }
  18495. // Animations
  18496. if (parsedLight.animations) {
  18497. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18498. var parsedAnimation = parsedLight.animations[animationIndex];
  18499. light.animations.push(parseAnimation(parsedAnimation));
  18500. }
  18501. }
  18502. if (parsedLight.autoAnimate) {
  18503. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18504. }
  18505. };
  18506. var parseCamera = function (parsedCamera, scene) {
  18507. var camera;
  18508. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18509. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18510. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18511. var alpha = parsedCamera.alpha;
  18512. var beta = parsedCamera.beta;
  18513. var radius = parsedCamera.radius;
  18514. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18515. var eye_space = parsedCamera.eye_space;
  18516. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18517. }
  18518. else {
  18519. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18520. }
  18521. }
  18522. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18523. eye_space = parsedCamera.eye_space;
  18524. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18525. }
  18526. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18527. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18528. }
  18529. else if (parsedCamera.type === "FollowCamera") {
  18530. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18531. camera.heightOffset = parsedCamera.heightOffset;
  18532. camera.radius = parsedCamera.radius;
  18533. camera.rotationOffset = parsedCamera.rotationOffset;
  18534. if (lockedTargetMesh)
  18535. camera.target = lockedTargetMesh;
  18536. }
  18537. else if (parsedCamera.type === "GamepadCamera") {
  18538. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18539. }
  18540. else if (parsedCamera.type === "OculusCamera") {
  18541. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18542. }
  18543. else if (parsedCamera.type === "OculusGamepadCamera") {
  18544. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18545. }
  18546. else if (parsedCamera.type === "TouchCamera") {
  18547. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18548. }
  18549. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18550. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18551. }
  18552. else if (parsedCamera.type === "WebVRCamera") {
  18553. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18554. }
  18555. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18556. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18557. }
  18558. else {
  18559. // Free Camera is the default value
  18560. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18561. }
  18562. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18563. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18564. camera.lockedTarget = lockedTargetMesh;
  18565. }
  18566. camera.id = parsedCamera.id;
  18567. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18568. // Parent
  18569. if (parsedCamera.parentId) {
  18570. camera._waitingParentId = parsedCamera.parentId;
  18571. }
  18572. // Target
  18573. if (parsedCamera.target) {
  18574. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18575. }
  18576. else {
  18577. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18578. }
  18579. camera.fov = parsedCamera.fov;
  18580. camera.minZ = parsedCamera.minZ;
  18581. camera.maxZ = parsedCamera.maxZ;
  18582. camera.speed = parsedCamera.speed;
  18583. camera.inertia = parsedCamera.inertia;
  18584. camera.checkCollisions = parsedCamera.checkCollisions;
  18585. camera.applyGravity = parsedCamera.applyGravity;
  18586. if (parsedCamera.ellipsoid) {
  18587. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18588. }
  18589. // Animations
  18590. if (parsedCamera.animations) {
  18591. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18592. var parsedAnimation = parsedCamera.animations[animationIndex];
  18593. camera.animations.push(parseAnimation(parsedAnimation));
  18594. }
  18595. }
  18596. if (parsedCamera.autoAnimate) {
  18597. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18598. }
  18599. // Layer Mask
  18600. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18601. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18602. }
  18603. else {
  18604. camera.layerMask = 0xFFFFFFFF;
  18605. }
  18606. return camera;
  18607. };
  18608. var parseGeometry = function (parsedGeometry, scene) {
  18609. var id = parsedGeometry.id;
  18610. return scene.getGeometryByID(id);
  18611. };
  18612. var parseBox = function (parsedBox, scene) {
  18613. if (parseGeometry(parsedBox, scene)) {
  18614. return null; // null since geometry could be something else than a box...
  18615. }
  18616. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18617. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18618. scene.pushGeometry(box, true);
  18619. return box;
  18620. };
  18621. var parseSphere = function (parsedSphere, scene) {
  18622. if (parseGeometry(parsedSphere, scene)) {
  18623. return null; // null since geometry could be something else than a sphere...
  18624. }
  18625. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18626. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18627. scene.pushGeometry(sphere, true);
  18628. return sphere;
  18629. };
  18630. var parseCylinder = function (parsedCylinder, scene) {
  18631. if (parseGeometry(parsedCylinder, scene)) {
  18632. return null; // null since geometry could be something else than a cylinder...
  18633. }
  18634. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18635. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18636. scene.pushGeometry(cylinder, true);
  18637. return cylinder;
  18638. };
  18639. var parseTorus = function (parsedTorus, scene) {
  18640. if (parseGeometry(parsedTorus, scene)) {
  18641. return null; // null since geometry could be something else than a torus...
  18642. }
  18643. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18644. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18645. scene.pushGeometry(torus, true);
  18646. return torus;
  18647. };
  18648. var parseGround = function (parsedGround, scene) {
  18649. if (parseGeometry(parsedGround, scene)) {
  18650. return null; // null since geometry could be something else than a ground...
  18651. }
  18652. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18653. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18654. scene.pushGeometry(ground, true);
  18655. return ground;
  18656. };
  18657. var parsePlane = function (parsedPlane, scene) {
  18658. if (parseGeometry(parsedPlane, scene)) {
  18659. return null; // null since geometry could be something else than a plane...
  18660. }
  18661. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18662. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18663. scene.pushGeometry(plane, true);
  18664. return plane;
  18665. };
  18666. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18667. if (parseGeometry(parsedTorusKnot, scene)) {
  18668. return null; // null since geometry could be something else than a torusKnot...
  18669. }
  18670. 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);
  18671. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18672. scene.pushGeometry(torusKnot, true);
  18673. return torusKnot;
  18674. };
  18675. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18676. if (parseGeometry(parsedVertexData, scene)) {
  18677. return null; // null since geometry could be a primitive
  18678. }
  18679. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18680. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18681. if (parsedVertexData.delayLoadingFile) {
  18682. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18683. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18684. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18685. geometry._delayInfo = [];
  18686. if (parsedVertexData.hasUVs) {
  18687. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18688. }
  18689. if (parsedVertexData.hasUVs2) {
  18690. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18691. }
  18692. if (parsedVertexData.hasColors) {
  18693. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18694. }
  18695. if (parsedVertexData.hasMatricesIndices) {
  18696. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18697. }
  18698. if (parsedVertexData.hasMatricesWeights) {
  18699. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18700. }
  18701. geometry._delayLoadingFunction = importVertexData;
  18702. }
  18703. else {
  18704. importVertexData(parsedVertexData, geometry);
  18705. }
  18706. scene.pushGeometry(geometry, true);
  18707. return geometry;
  18708. };
  18709. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18710. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18711. mesh.id = parsedMesh.id;
  18712. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18713. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18714. if (parsedMesh.rotationQuaternion) {
  18715. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18716. }
  18717. else if (parsedMesh.rotation) {
  18718. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18719. }
  18720. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18721. if (parsedMesh.localMatrix) {
  18722. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18723. }
  18724. else if (parsedMesh.pivotMatrix) {
  18725. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18726. }
  18727. mesh.setEnabled(parsedMesh.isEnabled);
  18728. mesh.isVisible = parsedMesh.isVisible;
  18729. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18730. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18731. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18732. if (parsedMesh.applyFog !== undefined) {
  18733. mesh.applyFog = parsedMesh.applyFog;
  18734. }
  18735. if (parsedMesh.pickable !== undefined) {
  18736. mesh.isPickable = parsedMesh.pickable;
  18737. }
  18738. if (parsedMesh.alphaIndex !== undefined) {
  18739. mesh.alphaIndex = parsedMesh.alphaIndex;
  18740. }
  18741. mesh.receiveShadows = parsedMesh.receiveShadows;
  18742. mesh.billboardMode = parsedMesh.billboardMode;
  18743. if (parsedMesh.visibility !== undefined) {
  18744. mesh.visibility = parsedMesh.visibility;
  18745. }
  18746. mesh.checkCollisions = parsedMesh.checkCollisions;
  18747. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18748. // Parent
  18749. if (parsedMesh.parentId) {
  18750. mesh._waitingParentId = parsedMesh.parentId;
  18751. }
  18752. // Actions
  18753. if (parsedMesh.actions !== undefined) {
  18754. mesh._waitingActions = parsedMesh.actions;
  18755. }
  18756. // Geometry
  18757. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18758. if (parsedMesh.delayLoadingFile) {
  18759. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18760. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18761. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18762. if (parsedMesh._binaryInfo) {
  18763. mesh._binaryInfo = parsedMesh._binaryInfo;
  18764. }
  18765. mesh._delayInfo = [];
  18766. if (parsedMesh.hasUVs) {
  18767. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18768. }
  18769. if (parsedMesh.hasUVs2) {
  18770. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18771. }
  18772. if (parsedMesh.hasColors) {
  18773. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18774. }
  18775. if (parsedMesh.hasMatricesIndices) {
  18776. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18777. }
  18778. if (parsedMesh.hasMatricesWeights) {
  18779. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18780. }
  18781. mesh._delayLoadingFunction = importGeometry;
  18782. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18783. mesh._checkDelayState();
  18784. }
  18785. }
  18786. else {
  18787. importGeometry(parsedMesh, mesh);
  18788. }
  18789. // Material
  18790. if (parsedMesh.materialId) {
  18791. mesh.setMaterialByID(parsedMesh.materialId);
  18792. }
  18793. else {
  18794. mesh.material = null;
  18795. }
  18796. // Skeleton
  18797. if (parsedMesh.skeletonId > -1) {
  18798. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18799. }
  18800. // Physics
  18801. if (parsedMesh.physicsImpostor) {
  18802. if (!scene.isPhysicsEnabled()) {
  18803. scene.enablePhysics();
  18804. }
  18805. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18806. }
  18807. // Animations
  18808. if (parsedMesh.animations) {
  18809. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18810. var parsedAnimation = parsedMesh.animations[animationIndex];
  18811. mesh.animations.push(parseAnimation(parsedAnimation));
  18812. }
  18813. }
  18814. if (parsedMesh.autoAnimate) {
  18815. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18816. }
  18817. // Layer Mask
  18818. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18819. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18820. }
  18821. else {
  18822. mesh.layerMask = 0xFFFFFFFF;
  18823. }
  18824. // Instances
  18825. if (parsedMesh.instances) {
  18826. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18827. var parsedInstance = parsedMesh.instances[index];
  18828. var instance = mesh.createInstance(parsedInstance.name);
  18829. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18830. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18831. if (parsedInstance.rotationQuaternion) {
  18832. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18833. }
  18834. else if (parsedInstance.rotation) {
  18835. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18836. }
  18837. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18838. instance.checkCollisions = mesh.checkCollisions;
  18839. if (parsedMesh.animations) {
  18840. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18841. parsedAnimation = parsedMesh.animations[animationIndex];
  18842. instance.animations.push(parseAnimation(parsedAnimation));
  18843. }
  18844. }
  18845. }
  18846. }
  18847. return mesh;
  18848. };
  18849. var parseActions = function (parsedActions, object, scene) {
  18850. var actionManager = new BABYLON.ActionManager(scene);
  18851. if (object === null)
  18852. scene.actionManager = actionManager;
  18853. else
  18854. object.actionManager = actionManager;
  18855. // instanciate a new object
  18856. var instanciate = function (name, params) {
  18857. var newInstance = Object.create(BABYLON[name].prototype);
  18858. newInstance.constructor.apply(newInstance, params);
  18859. return newInstance;
  18860. };
  18861. var parseParameter = function (name, value, target, propertyPath) {
  18862. if (propertyPath === null) {
  18863. // String, boolean or float
  18864. var floatValue = parseFloat(value);
  18865. if (value === "true" || value === "false")
  18866. return value === "true";
  18867. else
  18868. return isNaN(floatValue) ? value : floatValue;
  18869. }
  18870. var effectiveTarget = propertyPath.split(".");
  18871. var values = value.split(",");
  18872. for (var i = 0; i < effectiveTarget.length; i++) {
  18873. target = target[effectiveTarget[i]];
  18874. }
  18875. // Return appropriate value with its type
  18876. if (target instanceof Boolean)
  18877. return values[0] === "true";
  18878. if (target instanceof String)
  18879. return values[0];
  18880. // Parameters with multiple values such as Vector3 etc.
  18881. var split = new Array();
  18882. for (var i = 0; i < values.length; i++)
  18883. split.push(parseFloat(values[i]));
  18884. if (target instanceof BABYLON.Vector3)
  18885. return BABYLON.Vector3.FromArray(split);
  18886. if (target instanceof BABYLON.Vector4)
  18887. return BABYLON.Vector4.FromArray(split);
  18888. if (target instanceof BABYLON.Color3)
  18889. return BABYLON.Color3.FromArray(split);
  18890. if (target instanceof BABYLON.Color4)
  18891. return BABYLON.Color4.FromArray(split);
  18892. return parseFloat(values[0]);
  18893. };
  18894. // traverse graph per trigger
  18895. var traverse = function (parsedAction, trigger, condition, action) {
  18896. var parameters = new Array();
  18897. var target = null;
  18898. var propertyPath = null;
  18899. // Parameters
  18900. if (parsedAction.type === 2)
  18901. parameters.push(actionManager);
  18902. else
  18903. parameters.push(trigger);
  18904. for (var i = 0; i < parsedAction.properties.length; i++) {
  18905. var value = parsedAction.properties[i].value;
  18906. var name = parsedAction.properties[i].name;
  18907. if (name === "target")
  18908. value = target = scene.getNodeByName(value);
  18909. else if (name === "parent")
  18910. value = scene.getNodeByName(value);
  18911. else if (name === "sound")
  18912. value = scene.getSoundByName(value);
  18913. else if (name !== "propertyPath") {
  18914. if (parsedAction.type === 2 && name === "operator")
  18915. value = BABYLON.ValueCondition[value];
  18916. else
  18917. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18918. }
  18919. else {
  18920. propertyPath = value;
  18921. }
  18922. parameters.push(value);
  18923. }
  18924. parameters.push(condition);
  18925. // If interpolate value action
  18926. if (parsedAction.name === "InterpolateValueAction") {
  18927. var param = parameters[parameters.length - 2];
  18928. parameters[parameters.length - 1] = param;
  18929. parameters[parameters.length - 2] = condition;
  18930. }
  18931. // Action or condition(s)
  18932. var newAction = instanciate(parsedAction.name, parameters);
  18933. if (newAction instanceof BABYLON.Condition) {
  18934. condition = newAction;
  18935. newAction = action;
  18936. }
  18937. else {
  18938. condition = null;
  18939. if (action)
  18940. action.then(newAction);
  18941. else
  18942. actionManager.registerAction(newAction);
  18943. }
  18944. for (var i = 0; i < parsedAction.children.length; i++)
  18945. traverse(parsedAction.children[i], trigger, condition, newAction);
  18946. };
  18947. for (var i = 0; i < parsedActions.children.length; i++) {
  18948. var triggerParams;
  18949. var trigger = parsedActions.children[i];
  18950. if (trigger.properties.length > 0) {
  18951. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18952. }
  18953. else
  18954. triggerParams = BABYLON.ActionManager[trigger.name];
  18955. for (var j = 0; j < trigger.children.length; j++)
  18956. traverse(trigger.children[j], triggerParams, null, null);
  18957. }
  18958. };
  18959. var parseSound = function (parsedSound, scene, rootUrl) {
  18960. var soundName = parsedSound.name;
  18961. var soundUrl = rootUrl + soundName;
  18962. var options = {
  18963. autoplay: parsedSound.autoplay,
  18964. loop: parsedSound.loop,
  18965. volume: parsedSound.volume,
  18966. spatialSound: parsedSound.spatialSound,
  18967. maxDistance: parsedSound.maxDistance,
  18968. rolloffFactor: parsedSound.rolloffFactor,
  18969. refDistance: parsedSound.refDistance,
  18970. distanceModel: parsedSound.distanceModel,
  18971. panningModel: parsedSound.panningModel,
  18972. playbackRate: parsedSound.playbackRate
  18973. };
  18974. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18975. scene._removePendingData(newSound);
  18976. }, options);
  18977. scene._addPendingData(newSound);
  18978. if (parsedSound.position) {
  18979. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18980. newSound.setPosition(soundPosition);
  18981. }
  18982. if (parsedSound.isDirectional) {
  18983. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18984. if (parsedSound.localDirectionToMesh) {
  18985. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18986. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18987. }
  18988. }
  18989. if (parsedSound.connectedMeshId) {
  18990. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18991. if (connectedMesh) {
  18992. newSound.attachToMesh(connectedMesh);
  18993. }
  18994. }
  18995. };
  18996. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18997. names = (names instanceof Array) ? names : [names];
  18998. for (var i in names) {
  18999. if (mesh.name === names[i]) {
  19000. hierarchyIds.push(mesh.id);
  19001. return true;
  19002. }
  19003. }
  19004. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19005. hierarchyIds.push(mesh.id);
  19006. return true;
  19007. }
  19008. return false;
  19009. };
  19010. var importVertexData = function (parsedVertexData, geometry) {
  19011. var vertexData = new BABYLON.VertexData();
  19012. // positions
  19013. var positions = parsedVertexData.positions;
  19014. if (positions) {
  19015. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19016. }
  19017. // normals
  19018. var normals = parsedVertexData.normals;
  19019. if (normals) {
  19020. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19021. }
  19022. // uvs
  19023. var uvs = parsedVertexData.uvs;
  19024. if (uvs) {
  19025. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19026. }
  19027. // uv2s
  19028. var uv2s = parsedVertexData.uv2s;
  19029. if (uv2s) {
  19030. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19031. }
  19032. // colors
  19033. var colors = parsedVertexData.colors;
  19034. if (colors) {
  19035. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19036. }
  19037. // matricesIndices
  19038. var matricesIndices = parsedVertexData.matricesIndices;
  19039. if (matricesIndices) {
  19040. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19041. }
  19042. // matricesWeights
  19043. var matricesWeights = parsedVertexData.matricesWeights;
  19044. if (matricesWeights) {
  19045. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19046. }
  19047. // indices
  19048. var indices = parsedVertexData.indices;
  19049. if (indices) {
  19050. vertexData.indices = indices;
  19051. }
  19052. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19053. };
  19054. var importGeometry = function (parsedGeometry, mesh) {
  19055. var scene = mesh.getScene();
  19056. // Geometry
  19057. var geometryId = parsedGeometry.geometryId;
  19058. if (geometryId) {
  19059. var geometry = scene.getGeometryByID(geometryId);
  19060. if (geometry) {
  19061. geometry.applyToMesh(mesh);
  19062. }
  19063. }
  19064. else if (parsedGeometry instanceof ArrayBuffer) {
  19065. var binaryInfo = mesh._binaryInfo;
  19066. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19067. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19068. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19069. }
  19070. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19071. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19072. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19073. }
  19074. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19075. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19076. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19077. }
  19078. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19079. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19080. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19081. }
  19082. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19083. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19084. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19085. }
  19086. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19087. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19089. }
  19090. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19091. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19093. }
  19094. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19095. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19096. mesh.setIndices(indicesData);
  19097. }
  19098. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19099. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19100. mesh.subMeshes = [];
  19101. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19102. var materialIndex = subMeshesData[(i * 5) + 0];
  19103. var verticesStart = subMeshesData[(i * 5) + 1];
  19104. var verticesCount = subMeshesData[(i * 5) + 2];
  19105. var indexStart = subMeshesData[(i * 5) + 3];
  19106. var indexCount = subMeshesData[(i * 5) + 4];
  19107. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19108. }
  19109. }
  19110. }
  19111. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19112. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19113. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19114. if (parsedGeometry.uvs) {
  19115. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19116. }
  19117. if (parsedGeometry.uvs2) {
  19118. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19119. }
  19120. if (parsedGeometry.colors) {
  19121. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19122. }
  19123. if (parsedGeometry.matricesIndices) {
  19124. if (!parsedGeometry.matricesIndices._isExpanded) {
  19125. var floatIndices = [];
  19126. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19127. var matricesIndex = parsedGeometry.matricesIndices[i];
  19128. floatIndices.push(matricesIndex & 0x000000FF);
  19129. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19130. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19131. floatIndices.push(matricesIndex >> 24);
  19132. }
  19133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19134. }
  19135. else {
  19136. delete parsedGeometry.matricesIndices._isExpanded;
  19137. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19138. }
  19139. }
  19140. if (parsedGeometry.matricesWeights) {
  19141. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19142. }
  19143. mesh.setIndices(parsedGeometry.indices);
  19144. // SubMeshes
  19145. if (parsedGeometry.subMeshes) {
  19146. mesh.subMeshes = [];
  19147. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19148. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19149. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19150. }
  19151. }
  19152. }
  19153. // Flat shading
  19154. if (mesh._shouldGenerateFlatShading) {
  19155. mesh.convertToFlatShadedMesh();
  19156. delete mesh._shouldGenerateFlatShading;
  19157. }
  19158. // Update
  19159. mesh.computeWorldMatrix(true);
  19160. // Octree
  19161. if (scene._selectionOctree) {
  19162. scene._selectionOctree.addMesh(mesh);
  19163. }
  19164. };
  19165. BABYLON.SceneLoader.RegisterPlugin({
  19166. extensions: ".babylon",
  19167. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19168. var parsedData = JSON.parse(data);
  19169. var loadedSkeletonsIds = [];
  19170. var loadedMaterialsIds = [];
  19171. var hierarchyIds = [];
  19172. for (var index = 0; index < parsedData.meshes.length; index++) {
  19173. var parsedMesh = parsedData.meshes[index];
  19174. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19175. if (meshesNames instanceof Array) {
  19176. // Remove found mesh name from list.
  19177. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19178. }
  19179. // Material ?
  19180. if (parsedMesh.materialId) {
  19181. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19182. if (!materialFound) {
  19183. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19184. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19185. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19186. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19187. var subMatId = parsedMultiMaterial.materials[matIndex];
  19188. loadedMaterialsIds.push(subMatId);
  19189. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19190. }
  19191. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19192. parseMultiMaterial(parsedMultiMaterial, scene);
  19193. materialFound = true;
  19194. break;
  19195. }
  19196. }
  19197. }
  19198. if (!materialFound) {
  19199. loadedMaterialsIds.push(parsedMesh.materialId);
  19200. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19201. }
  19202. }
  19203. // Skeleton ?
  19204. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19205. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19206. if (!skeletonAlreadyLoaded) {
  19207. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19208. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19209. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19210. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19211. loadedSkeletonsIds.push(parsedSkeleton.id);
  19212. }
  19213. }
  19214. }
  19215. }
  19216. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19217. meshes.push(mesh);
  19218. }
  19219. }
  19220. for (index = 0; index < scene.meshes.length; index++) {
  19221. var currentMesh = scene.meshes[index];
  19222. if (currentMesh._waitingParentId) {
  19223. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19224. currentMesh._waitingParentId = undefined;
  19225. }
  19226. }
  19227. // Particles
  19228. if (parsedData.particleSystems) {
  19229. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19230. var parsedParticleSystem = parsedData.particleSystems[index];
  19231. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19232. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19233. }
  19234. }
  19235. }
  19236. return true;
  19237. },
  19238. load: function (scene, data, rootUrl) {
  19239. var parsedData = JSON.parse(data);
  19240. // Scene
  19241. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19242. scene.autoClear = parsedData.autoClear;
  19243. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19244. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19245. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19246. // Fog
  19247. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19248. scene.fogMode = parsedData.fogMode;
  19249. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19250. scene.fogStart = parsedData.fogStart;
  19251. scene.fogEnd = parsedData.fogEnd;
  19252. scene.fogDensity = parsedData.fogDensity;
  19253. }
  19254. for (var index = 0; index < parsedData.lights.length; index++) {
  19255. var parsedLight = parsedData.lights[index];
  19256. parseLight(parsedLight, scene);
  19257. }
  19258. // Materials
  19259. if (parsedData.materials) {
  19260. for (index = 0; index < parsedData.materials.length; index++) {
  19261. var parsedMaterial = parsedData.materials[index];
  19262. parseMaterial(parsedMaterial, scene, rootUrl);
  19263. }
  19264. }
  19265. if (parsedData.multiMaterials) {
  19266. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19267. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19268. parseMultiMaterial(parsedMultiMaterial, scene);
  19269. }
  19270. }
  19271. // Skeletons
  19272. if (parsedData.skeletons) {
  19273. for (index = 0; index < parsedData.skeletons.length; index++) {
  19274. var parsedSkeleton = parsedData.skeletons[index];
  19275. parseSkeleton(parsedSkeleton, scene);
  19276. }
  19277. }
  19278. // Geometries
  19279. var geometries = parsedData.geometries;
  19280. if (geometries) {
  19281. // Boxes
  19282. var boxes = geometries.boxes;
  19283. if (boxes) {
  19284. for (index = 0; index < boxes.length; index++) {
  19285. var parsedBox = boxes[index];
  19286. parseBox(parsedBox, scene);
  19287. }
  19288. }
  19289. // Spheres
  19290. var spheres = geometries.spheres;
  19291. if (spheres) {
  19292. for (index = 0; index < spheres.length; index++) {
  19293. var parsedSphere = spheres[index];
  19294. parseSphere(parsedSphere, scene);
  19295. }
  19296. }
  19297. // Cylinders
  19298. var cylinders = geometries.cylinders;
  19299. if (cylinders) {
  19300. for (index = 0; index < cylinders.length; index++) {
  19301. var parsedCylinder = cylinders[index];
  19302. parseCylinder(parsedCylinder, scene);
  19303. }
  19304. }
  19305. // Toruses
  19306. var toruses = geometries.toruses;
  19307. if (toruses) {
  19308. for (index = 0; index < toruses.length; index++) {
  19309. var parsedTorus = toruses[index];
  19310. parseTorus(parsedTorus, scene);
  19311. }
  19312. }
  19313. // Grounds
  19314. var grounds = geometries.grounds;
  19315. if (grounds) {
  19316. for (index = 0; index < grounds.length; index++) {
  19317. var parsedGround = grounds[index];
  19318. parseGround(parsedGround, scene);
  19319. }
  19320. }
  19321. // Planes
  19322. var planes = geometries.planes;
  19323. if (planes) {
  19324. for (index = 0; index < planes.length; index++) {
  19325. var parsedPlane = planes[index];
  19326. parsePlane(parsedPlane, scene);
  19327. }
  19328. }
  19329. // TorusKnots
  19330. var torusKnots = geometries.torusKnots;
  19331. if (torusKnots) {
  19332. for (index = 0; index < torusKnots.length; index++) {
  19333. var parsedTorusKnot = torusKnots[index];
  19334. parseTorusKnot(parsedTorusKnot, scene);
  19335. }
  19336. }
  19337. // VertexData
  19338. var vertexData = geometries.vertexData;
  19339. if (vertexData) {
  19340. for (index = 0; index < vertexData.length; index++) {
  19341. var parsedVertexData = vertexData[index];
  19342. parseVertexData(parsedVertexData, scene, rootUrl);
  19343. }
  19344. }
  19345. }
  19346. for (index = 0; index < parsedData.meshes.length; index++) {
  19347. var parsedMesh = parsedData.meshes[index];
  19348. parseMesh(parsedMesh, scene, rootUrl);
  19349. }
  19350. for (index = 0; index < parsedData.cameras.length; index++) {
  19351. var parsedCamera = parsedData.cameras[index];
  19352. parseCamera(parsedCamera, scene);
  19353. }
  19354. if (parsedData.activeCameraID) {
  19355. scene.setActiveCameraByID(parsedData.activeCameraID);
  19356. }
  19357. for (index = 0; index < scene.cameras.length; index++) {
  19358. var camera = scene.cameras[index];
  19359. if (camera._waitingParentId) {
  19360. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19361. camera._waitingParentId = undefined;
  19362. }
  19363. }
  19364. for (index = 0; index < scene.lights.length; index++) {
  19365. var light = scene.lights[index];
  19366. if (light._waitingParentId) {
  19367. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19368. light._waitingParentId = undefined;
  19369. }
  19370. }
  19371. // Sounds
  19372. if (parsedData.sounds) {
  19373. for (index = 0; index < parsedData.sounds.length; index++) {
  19374. var parsedSound = parsedData.sounds[index];
  19375. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19376. parseSound(parsedSound, scene, rootUrl);
  19377. }
  19378. else {
  19379. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19380. }
  19381. }
  19382. }
  19383. for (index = 0; index < scene.meshes.length; index++) {
  19384. var mesh = scene.meshes[index];
  19385. if (mesh._waitingParentId) {
  19386. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19387. mesh._waitingParentId = undefined;
  19388. }
  19389. if (mesh._waitingActions) {
  19390. parseActions(mesh._waitingActions, mesh, scene);
  19391. mesh._waitingActions = undefined;
  19392. }
  19393. }
  19394. // Particles Systems
  19395. if (parsedData.particleSystems) {
  19396. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19397. var parsedParticleSystem = parsedData.particleSystems[index];
  19398. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19399. }
  19400. }
  19401. // Lens flares
  19402. if (parsedData.lensFlareSystems) {
  19403. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19404. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19405. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19406. }
  19407. }
  19408. // Shadows
  19409. if (parsedData.shadowGenerators) {
  19410. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19411. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19412. parseShadowGenerator(parsedShadowGenerator, scene);
  19413. }
  19414. }
  19415. // Actions (scene)
  19416. if (parsedData.actions) {
  19417. parseActions(parsedData.actions, null, scene);
  19418. }
  19419. // Finish
  19420. return true;
  19421. }
  19422. });
  19423. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19424. })(BABYLON || (BABYLON = {}));
  19425. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19426. (function (BABYLON) {
  19427. // Unique ID when we import meshes from Babylon to CSG
  19428. var currentCSGMeshId = 0;
  19429. // # class Vertex
  19430. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19431. // one to provide additional features like texture coordinates and vertex
  19432. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19433. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19434. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19435. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19436. // is not used anywhere else.
  19437. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19438. var Vertex = (function () {
  19439. function Vertex(pos, normal, uv) {
  19440. this.pos = pos;
  19441. this.normal = normal;
  19442. this.uv = uv;
  19443. }
  19444. Vertex.prototype.clone = function () {
  19445. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19446. };
  19447. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19448. // orientation of a polygon is flipped.
  19449. Vertex.prototype.flip = function () {
  19450. this.normal = this.normal.scale(-1);
  19451. };
  19452. // Create a new vertex between this vertex and `other` by linearly
  19453. // interpolating all properties using a parameter of `t`. Subclasses should
  19454. // override this to interpolate additional properties.
  19455. Vertex.prototype.interpolate = function (other, t) {
  19456. 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));
  19457. };
  19458. return Vertex;
  19459. })();
  19460. // # class Plane
  19461. // Represents a plane in 3D space.
  19462. var Plane = (function () {
  19463. function Plane(normal, w) {
  19464. this.normal = normal;
  19465. this.w = w;
  19466. }
  19467. Plane.FromPoints = function (a, b, c) {
  19468. var v0 = c.subtract(a);
  19469. var v1 = b.subtract(a);
  19470. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19471. return null;
  19472. }
  19473. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19474. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19475. };
  19476. Plane.prototype.clone = function () {
  19477. return new Plane(this.normal.clone(), this.w);
  19478. };
  19479. Plane.prototype.flip = function () {
  19480. this.normal.scaleInPlace(-1);
  19481. this.w = -this.w;
  19482. };
  19483. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19484. // fragments in the appropriate lists. Coplanar polygons go into either
  19485. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19486. // respect to this plane. Polygons in front or in back of this plane go into
  19487. // either `front` or `back`.
  19488. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19489. var COPLANAR = 0;
  19490. var FRONT = 1;
  19491. var BACK = 2;
  19492. var SPANNING = 3;
  19493. // Classify each point as well as the entire polygon into one of the above
  19494. // four classes.
  19495. var polygonType = 0;
  19496. var types = [];
  19497. for (var i = 0; i < polygon.vertices.length; i++) {
  19498. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19499. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19500. polygonType |= type;
  19501. types.push(type);
  19502. }
  19503. switch (polygonType) {
  19504. case COPLANAR:
  19505. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19506. break;
  19507. case FRONT:
  19508. front.push(polygon);
  19509. break;
  19510. case BACK:
  19511. back.push(polygon);
  19512. break;
  19513. case SPANNING:
  19514. var f = [], b = [];
  19515. for (i = 0; i < polygon.vertices.length; i++) {
  19516. var j = (i + 1) % polygon.vertices.length;
  19517. var ti = types[i], tj = types[j];
  19518. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19519. if (ti != BACK)
  19520. f.push(vi);
  19521. if (ti != FRONT)
  19522. b.push(ti != BACK ? vi.clone() : vi);
  19523. if ((ti | tj) == SPANNING) {
  19524. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19525. var v = vi.interpolate(vj, t);
  19526. f.push(v);
  19527. b.push(v.clone());
  19528. }
  19529. }
  19530. if (f.length >= 3) {
  19531. var poly = new Polygon(f, polygon.shared);
  19532. if (poly.plane)
  19533. front.push(poly);
  19534. }
  19535. if (b.length >= 3) {
  19536. poly = new Polygon(b, polygon.shared);
  19537. if (poly.plane)
  19538. back.push(poly);
  19539. }
  19540. break;
  19541. }
  19542. };
  19543. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19544. // point is on the plane.
  19545. Plane.EPSILON = 1e-5;
  19546. return Plane;
  19547. })();
  19548. // # class Polygon
  19549. // Represents a convex polygon. The vertices used to initialize a polygon must
  19550. // be coplanar and form a convex loop.
  19551. //
  19552. // Each convex polygon has a `shared` property, which is shared between all
  19553. // polygons that are clones of each other or were split from the same polygon.
  19554. // This can be used to define per-polygon properties (such as surface color).
  19555. var Polygon = (function () {
  19556. function Polygon(vertices, shared) {
  19557. this.vertices = vertices;
  19558. this.shared = shared;
  19559. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19560. }
  19561. Polygon.prototype.clone = function () {
  19562. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19563. return new Polygon(vertices, this.shared);
  19564. };
  19565. Polygon.prototype.flip = function () {
  19566. this.vertices.reverse().map(function (v) {
  19567. v.flip();
  19568. });
  19569. this.plane.flip();
  19570. };
  19571. return Polygon;
  19572. })();
  19573. // # class Node
  19574. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19575. // by picking a polygon to split along. That polygon (and all other coplanar
  19576. // polygons) are added directly to that node and the other polygons are added to
  19577. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19578. // no distinction between internal and leaf nodes.
  19579. var Node = (function () {
  19580. function Node(polygons) {
  19581. this.plane = null;
  19582. this.front = null;
  19583. this.back = null;
  19584. this.polygons = [];
  19585. if (polygons) {
  19586. this.build(polygons);
  19587. }
  19588. }
  19589. Node.prototype.clone = function () {
  19590. var node = new Node();
  19591. node.plane = this.plane && this.plane.clone();
  19592. node.front = this.front && this.front.clone();
  19593. node.back = this.back && this.back.clone();
  19594. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19595. return node;
  19596. };
  19597. // Convert solid space to empty space and empty space to solid space.
  19598. Node.prototype.invert = function () {
  19599. for (var i = 0; i < this.polygons.length; i++) {
  19600. this.polygons[i].flip();
  19601. }
  19602. if (this.plane) {
  19603. this.plane.flip();
  19604. }
  19605. if (this.front) {
  19606. this.front.invert();
  19607. }
  19608. if (this.back) {
  19609. this.back.invert();
  19610. }
  19611. var temp = this.front;
  19612. this.front = this.back;
  19613. this.back = temp;
  19614. };
  19615. // Recursively remove all polygons in `polygons` that are inside this BSP
  19616. // tree.
  19617. Node.prototype.clipPolygons = function (polygons) {
  19618. if (!this.plane)
  19619. return polygons.slice();
  19620. var front = [], back = [];
  19621. for (var i = 0; i < polygons.length; i++) {
  19622. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19623. }
  19624. if (this.front) {
  19625. front = this.front.clipPolygons(front);
  19626. }
  19627. if (this.back) {
  19628. back = this.back.clipPolygons(back);
  19629. }
  19630. else {
  19631. back = [];
  19632. }
  19633. return front.concat(back);
  19634. };
  19635. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19636. // `bsp`.
  19637. Node.prototype.clipTo = function (bsp) {
  19638. this.polygons = bsp.clipPolygons(this.polygons);
  19639. if (this.front)
  19640. this.front.clipTo(bsp);
  19641. if (this.back)
  19642. this.back.clipTo(bsp);
  19643. };
  19644. // Return a list of all polygons in this BSP tree.
  19645. Node.prototype.allPolygons = function () {
  19646. var polygons = this.polygons.slice();
  19647. if (this.front)
  19648. polygons = polygons.concat(this.front.allPolygons());
  19649. if (this.back)
  19650. polygons = polygons.concat(this.back.allPolygons());
  19651. return polygons;
  19652. };
  19653. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19654. // new polygons are filtered down to the bottom of the tree and become new
  19655. // nodes there. Each set of polygons is partitioned using the first polygon
  19656. // (no heuristic is used to pick a good split).
  19657. Node.prototype.build = function (polygons) {
  19658. if (!polygons.length)
  19659. return;
  19660. if (!this.plane)
  19661. this.plane = polygons[0].plane.clone();
  19662. var front = [], back = [];
  19663. for (var i = 0; i < polygons.length; i++) {
  19664. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19665. }
  19666. if (front.length) {
  19667. if (!this.front)
  19668. this.front = new Node();
  19669. this.front.build(front);
  19670. }
  19671. if (back.length) {
  19672. if (!this.back)
  19673. this.back = new Node();
  19674. this.back.build(back);
  19675. }
  19676. };
  19677. return Node;
  19678. })();
  19679. var CSG = (function () {
  19680. function CSG() {
  19681. this.polygons = new Array();
  19682. }
  19683. // Convert BABYLON.Mesh to BABYLON.CSG
  19684. CSG.FromMesh = function (mesh) {
  19685. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19686. if (mesh instanceof BABYLON.Mesh) {
  19687. mesh.computeWorldMatrix(true);
  19688. var matrix = mesh.getWorldMatrix();
  19689. var meshPosition = mesh.position.clone();
  19690. var meshRotation = mesh.rotation.clone();
  19691. var meshScaling = mesh.scaling.clone();
  19692. }
  19693. else {
  19694. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19695. }
  19696. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19697. var subMeshes = mesh.subMeshes;
  19698. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19699. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19700. vertices = [];
  19701. for (var j = 0; j < 3; j++) {
  19702. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19703. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19704. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19705. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19706. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19707. vertex = new Vertex(position, normal, uv);
  19708. vertices.push(vertex);
  19709. }
  19710. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19711. // To handle the case of degenerated triangle
  19712. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19713. if (polygon.plane)
  19714. polygons.push(polygon);
  19715. }
  19716. }
  19717. var csg = CSG.FromPolygons(polygons);
  19718. csg.matrix = matrix;
  19719. csg.position = meshPosition;
  19720. csg.rotation = meshRotation;
  19721. csg.scaling = meshScaling;
  19722. currentCSGMeshId++;
  19723. return csg;
  19724. };
  19725. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19726. CSG.FromPolygons = function (polygons) {
  19727. var csg = new BABYLON.CSG();
  19728. csg.polygons = polygons;
  19729. return csg;
  19730. };
  19731. CSG.prototype.clone = function () {
  19732. var csg = new BABYLON.CSG();
  19733. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19734. csg.copyTransformAttributes(this);
  19735. return csg;
  19736. };
  19737. CSG.prototype.toPolygons = function () {
  19738. return this.polygons;
  19739. };
  19740. CSG.prototype.union = function (csg) {
  19741. var a = new Node(this.clone().polygons);
  19742. var b = new Node(csg.clone().polygons);
  19743. a.clipTo(b);
  19744. b.clipTo(a);
  19745. b.invert();
  19746. b.clipTo(a);
  19747. b.invert();
  19748. a.build(b.allPolygons());
  19749. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19750. };
  19751. CSG.prototype.unionInPlace = function (csg) {
  19752. var a = new Node(this.polygons);
  19753. var b = new Node(csg.polygons);
  19754. a.clipTo(b);
  19755. b.clipTo(a);
  19756. b.invert();
  19757. b.clipTo(a);
  19758. b.invert();
  19759. a.build(b.allPolygons());
  19760. this.polygons = a.allPolygons();
  19761. };
  19762. CSG.prototype.subtract = function (csg) {
  19763. var a = new Node(this.clone().polygons);
  19764. var b = new Node(csg.clone().polygons);
  19765. a.invert();
  19766. a.clipTo(b);
  19767. b.clipTo(a);
  19768. b.invert();
  19769. b.clipTo(a);
  19770. b.invert();
  19771. a.build(b.allPolygons());
  19772. a.invert();
  19773. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19774. };
  19775. CSG.prototype.subtractInPlace = function (csg) {
  19776. var a = new Node(this.polygons);
  19777. var b = new Node(csg.polygons);
  19778. a.invert();
  19779. a.clipTo(b);
  19780. b.clipTo(a);
  19781. b.invert();
  19782. b.clipTo(a);
  19783. b.invert();
  19784. a.build(b.allPolygons());
  19785. a.invert();
  19786. this.polygons = a.allPolygons();
  19787. };
  19788. CSG.prototype.intersect = function (csg) {
  19789. var a = new Node(this.clone().polygons);
  19790. var b = new Node(csg.clone().polygons);
  19791. a.invert();
  19792. b.clipTo(a);
  19793. b.invert();
  19794. a.clipTo(b);
  19795. b.clipTo(a);
  19796. a.build(b.allPolygons());
  19797. a.invert();
  19798. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19799. };
  19800. CSG.prototype.intersectInPlace = function (csg) {
  19801. var a = new Node(this.polygons);
  19802. var b = new Node(csg.polygons);
  19803. a.invert();
  19804. b.clipTo(a);
  19805. b.invert();
  19806. a.clipTo(b);
  19807. b.clipTo(a);
  19808. a.build(b.allPolygons());
  19809. a.invert();
  19810. this.polygons = a.allPolygons();
  19811. };
  19812. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19813. // not modified.
  19814. CSG.prototype.inverse = function () {
  19815. var csg = this.clone();
  19816. csg.inverseInPlace();
  19817. return csg;
  19818. };
  19819. CSG.prototype.inverseInPlace = function () {
  19820. this.polygons.map(function (p) {
  19821. p.flip();
  19822. });
  19823. };
  19824. // This is used to keep meshes transformations so they can be restored
  19825. // when we build back a Babylon Mesh
  19826. // NB : All CSG operations are performed in world coordinates
  19827. CSG.prototype.copyTransformAttributes = function (csg) {
  19828. this.matrix = csg.matrix;
  19829. this.position = csg.position;
  19830. this.rotation = csg.rotation;
  19831. this.scaling = csg.scaling;
  19832. return this;
  19833. };
  19834. // Build Raw mesh from CSG
  19835. // Coordinates here are in world space
  19836. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19837. var matrix = this.matrix.clone();
  19838. matrix.invert();
  19839. 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;
  19840. if (keepSubMeshes) {
  19841. // Sort Polygons, since subMeshes are indices range
  19842. polygons.sort(function (a, b) {
  19843. if (a.shared.meshId === b.shared.meshId) {
  19844. return a.shared.subMeshId - b.shared.subMeshId;
  19845. }
  19846. else {
  19847. return a.shared.meshId - b.shared.meshId;
  19848. }
  19849. });
  19850. }
  19851. for (var i = 0, il = polygons.length; i < il; i++) {
  19852. polygon = polygons[i];
  19853. // Building SubMeshes
  19854. if (!subMesh_dict[polygon.shared.meshId]) {
  19855. subMesh_dict[polygon.shared.meshId] = {};
  19856. }
  19857. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19858. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19859. indexStart: +Infinity,
  19860. indexEnd: -Infinity,
  19861. materialIndex: polygon.shared.materialIndex
  19862. };
  19863. }
  19864. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19865. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19866. polygonIndices[0] = 0;
  19867. polygonIndices[1] = j - 1;
  19868. polygonIndices[2] = j;
  19869. for (var k = 0; k < 3; k++) {
  19870. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19871. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19872. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19873. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19874. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19875. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19876. // Check if 2 points can be merged
  19877. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  19878. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19879. uvs.push(uv.x, uv.y);
  19880. normals.push(normal.x, normal.y, normal.z);
  19881. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19882. }
  19883. indices.push(vertex_idx);
  19884. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19885. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19886. currentIndex++;
  19887. }
  19888. }
  19889. }
  19890. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19891. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19892. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19893. mesh.setIndices(indices);
  19894. if (keepSubMeshes) {
  19895. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19896. var materialIndexOffset = 0, materialMaxIndex;
  19897. mesh.subMeshes.length = 0;
  19898. for (var m in subMesh_dict) {
  19899. materialMaxIndex = -1;
  19900. for (var sm in subMesh_dict[m]) {
  19901. subMesh_obj = subMesh_dict[m][sm];
  19902. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19903. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19904. }
  19905. materialIndexOffset += ++materialMaxIndex;
  19906. }
  19907. }
  19908. return mesh;
  19909. };
  19910. // Build Mesh from CSG taking material and transforms into account
  19911. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19912. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19913. mesh.material = material;
  19914. mesh.position.copyFrom(this.position);
  19915. mesh.rotation.copyFrom(this.rotation);
  19916. mesh.scaling.copyFrom(this.scaling);
  19917. mesh.computeWorldMatrix(true);
  19918. return mesh;
  19919. };
  19920. return CSG;
  19921. })();
  19922. BABYLON.CSG = CSG;
  19923. })(BABYLON || (BABYLON = {}));
  19924. //# sourceMappingURL=babylon.csg.js.map
  19925. var BABYLON;
  19926. (function (BABYLON) {
  19927. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19928. __extends(OculusDistortionCorrectionPostProcess, _super);
  19929. //ANY
  19930. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19931. var _this = this;
  19932. _super.call(this, name, "oculusDistortionCorrection", [
  19933. 'LensCenter',
  19934. 'Scale',
  19935. 'ScaleIn',
  19936. 'HmdWarpParam'
  19937. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19938. this._isRightEye = isRightEye;
  19939. this._distortionFactors = cameraSettings.DistortionK;
  19940. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19941. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19942. this.onSizeChanged = function () {
  19943. _this.aspectRatio = _this.width * .5 / _this.height;
  19944. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19945. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19946. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19947. };
  19948. this.onApply = function (effect) {
  19949. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19950. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19951. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19952. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19953. };
  19954. }
  19955. return OculusDistortionCorrectionPostProcess;
  19956. })(BABYLON.PostProcess);
  19957. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19958. })(BABYLON || (BABYLON = {}));
  19959. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19960. // 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
  19961. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19962. var BABYLON;
  19963. (function (BABYLON) {
  19964. (function (JoystickAxis) {
  19965. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19966. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19967. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19968. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19969. var JoystickAxis = BABYLON.JoystickAxis;
  19970. var VirtualJoystick = (function () {
  19971. function VirtualJoystick(leftJoystick) {
  19972. var _this = this;
  19973. if (leftJoystick) {
  19974. this._leftJoystick = true;
  19975. }
  19976. else {
  19977. this._leftJoystick = false;
  19978. }
  19979. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19980. VirtualJoystick._globalJoystickIndex++;
  19981. // By default left & right arrow keys are moving the X
  19982. // and up & down keys are moving the Y
  19983. this._axisTargetedByLeftAndRight = 0 /* X */;
  19984. this._axisTargetedByUpAndDown = 1 /* Y */;
  19985. this.reverseLeftRight = false;
  19986. this.reverseUpDown = false;
  19987. // collections of pointers
  19988. this._touches = new BABYLON.VirtualJoystick.Collection();
  19989. this.deltaPosition = BABYLON.Vector3.Zero();
  19990. this._joystickSensibility = 25;
  19991. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19992. this._rotationSpeed = 25;
  19993. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19994. this._rotateOnAxisRelativeToMesh = false;
  19995. // injecting a canvas element on top of the canvas 3D game
  19996. if (!VirtualJoystick.vjCanvas) {
  19997. window.addEventListener("resize", function () {
  19998. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19999. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20000. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20001. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20002. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20003. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20004. }, false);
  20005. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20006. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20007. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20008. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20009. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20010. VirtualJoystick.vjCanvas.style.width = "100%";
  20011. VirtualJoystick.vjCanvas.style.height = "100%";
  20012. VirtualJoystick.vjCanvas.style.position = "absolute";
  20013. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20014. VirtualJoystick.vjCanvas.style.top = "0px";
  20015. VirtualJoystick.vjCanvas.style.left = "0px";
  20016. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20017. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20018. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20019. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20020. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20021. document.body.appendChild(VirtualJoystick.vjCanvas);
  20022. }
  20023. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20024. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20025. this.pressed = false;
  20026. // default joystick color
  20027. this._joystickColor = "cyan";
  20028. this._joystickPointerID = -1;
  20029. // current joystick position
  20030. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20031. // origin joystick position
  20032. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20033. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20034. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20035. _this._onPointerDown(evt);
  20036. }, false);
  20037. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20038. _this._onPointerMove(evt);
  20039. }, false);
  20040. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20041. _this._onPointerUp(evt);
  20042. }, false);
  20043. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20044. _this._onPointerUp(evt);
  20045. }, false);
  20046. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20047. evt.preventDefault(); // Disables system menu
  20048. }, false);
  20049. requestAnimationFrame(function () {
  20050. _this._drawVirtualJoystick();
  20051. });
  20052. }
  20053. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20054. this._joystickSensibility = newJoystickSensibility;
  20055. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20056. };
  20057. VirtualJoystick.prototype._onPointerDown = function (e) {
  20058. var positionOnScreenCondition;
  20059. e.preventDefault();
  20060. if (this._leftJoystick === true) {
  20061. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20062. }
  20063. else {
  20064. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20065. }
  20066. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20067. // First contact will be dedicated to the virtual joystick
  20068. this._joystickPointerID = e.pointerId;
  20069. this._joystickPointerStartPos.x = e.clientX;
  20070. this._joystickPointerStartPos.y = e.clientY;
  20071. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20072. this._deltaJoystickVector.x = 0;
  20073. this._deltaJoystickVector.y = 0;
  20074. this.pressed = true;
  20075. this._touches.add(e.pointerId.toString(), e);
  20076. }
  20077. else {
  20078. // You can only trigger the action buttons with a joystick declared
  20079. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20080. this._action();
  20081. this._touches.add(e.pointerId.toString(), e);
  20082. }
  20083. }
  20084. };
  20085. VirtualJoystick.prototype._onPointerMove = function (e) {
  20086. // If the current pointer is the one associated to the joystick (first touch contact)
  20087. if (this._joystickPointerID == e.pointerId) {
  20088. this._joystickPointerPos.x = e.clientX;
  20089. this._joystickPointerPos.y = e.clientY;
  20090. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20091. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20092. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20093. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20094. switch (this._axisTargetedByLeftAndRight) {
  20095. case 0 /* X */:
  20096. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20097. break;
  20098. case 1 /* Y */:
  20099. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20100. break;
  20101. case 2 /* Z */:
  20102. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20103. break;
  20104. }
  20105. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20106. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20107. switch (this._axisTargetedByUpAndDown) {
  20108. case 0 /* X */:
  20109. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20110. break;
  20111. case 1 /* Y */:
  20112. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20113. break;
  20114. case 2 /* Z */:
  20115. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20116. break;
  20117. }
  20118. }
  20119. else {
  20120. if (this._touches.item(e.pointerId.toString())) {
  20121. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20122. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20123. }
  20124. }
  20125. };
  20126. VirtualJoystick.prototype._onPointerUp = function (e) {
  20127. this._clearCanvas();
  20128. if (this._joystickPointerID == e.pointerId) {
  20129. this._joystickPointerID = -1;
  20130. this.pressed = false;
  20131. }
  20132. this._deltaJoystickVector.x = 0;
  20133. this._deltaJoystickVector.y = 0;
  20134. this._touches.remove(e.pointerId.toString());
  20135. };
  20136. /**
  20137. * Change the color of the virtual joystick
  20138. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20139. */
  20140. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20141. this._joystickColor = newColor;
  20142. };
  20143. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20144. this._action = action;
  20145. };
  20146. // Define which axis you'd like to control for left & right
  20147. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20148. switch (axis) {
  20149. case 0 /* X */:
  20150. case 1 /* Y */:
  20151. case 2 /* Z */:
  20152. this._axisTargetedByLeftAndRight = axis;
  20153. break;
  20154. default:
  20155. this._axisTargetedByLeftAndRight = 0 /* X */;
  20156. break;
  20157. }
  20158. };
  20159. // Define which axis you'd like to control for up & down
  20160. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20161. switch (axis) {
  20162. case 0 /* X */:
  20163. case 1 /* Y */:
  20164. case 2 /* Z */:
  20165. this._axisTargetedByUpAndDown = axis;
  20166. break;
  20167. default:
  20168. this._axisTargetedByUpAndDown = 1 /* Y */;
  20169. break;
  20170. }
  20171. };
  20172. VirtualJoystick.prototype._clearCanvas = function () {
  20173. if (this._leftJoystick) {
  20174. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20175. }
  20176. else {
  20177. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20178. }
  20179. };
  20180. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20181. var _this = this;
  20182. if (this.pressed) {
  20183. this._clearCanvas();
  20184. this._touches.forEach(function (touch) {
  20185. if (touch.pointerId === _this._joystickPointerID) {
  20186. VirtualJoystick.vjCanvasContext.beginPath();
  20187. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20188. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20189. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20190. VirtualJoystick.vjCanvasContext.stroke();
  20191. VirtualJoystick.vjCanvasContext.beginPath();
  20192. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20193. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20194. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20195. VirtualJoystick.vjCanvasContext.stroke();
  20196. VirtualJoystick.vjCanvasContext.beginPath();
  20197. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20198. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20199. VirtualJoystick.vjCanvasContext.stroke();
  20200. }
  20201. else {
  20202. VirtualJoystick.vjCanvasContext.beginPath();
  20203. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20204. VirtualJoystick.vjCanvasContext.beginPath();
  20205. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20206. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20207. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20208. VirtualJoystick.vjCanvasContext.stroke();
  20209. }
  20210. ;
  20211. });
  20212. }
  20213. requestAnimationFrame(function () {
  20214. _this._drawVirtualJoystick();
  20215. });
  20216. };
  20217. VirtualJoystick.prototype.releaseCanvas = function () {
  20218. if (VirtualJoystick.vjCanvas) {
  20219. document.body.removeChild(VirtualJoystick.vjCanvas);
  20220. VirtualJoystick.vjCanvas = null;
  20221. }
  20222. };
  20223. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20224. VirtualJoystick._globalJoystickIndex = 0;
  20225. return VirtualJoystick;
  20226. })();
  20227. BABYLON.VirtualJoystick = VirtualJoystick;
  20228. })(BABYLON || (BABYLON = {}));
  20229. var BABYLON;
  20230. (function (BABYLON) {
  20231. var VirtualJoystick;
  20232. (function (VirtualJoystick) {
  20233. var Collection = (function () {
  20234. function Collection() {
  20235. this._count = 0;
  20236. this._collection = new Array();
  20237. }
  20238. Collection.prototype.Count = function () {
  20239. return this._count;
  20240. };
  20241. Collection.prototype.add = function (key, item) {
  20242. if (this._collection[key] != undefined) {
  20243. return undefined;
  20244. }
  20245. this._collection[key] = item;
  20246. return ++this._count;
  20247. };
  20248. Collection.prototype.remove = function (key) {
  20249. if (this._collection[key] == undefined) {
  20250. return undefined;
  20251. }
  20252. delete this._collection[key];
  20253. return --this._count;
  20254. };
  20255. Collection.prototype.item = function (key) {
  20256. return this._collection[key];
  20257. };
  20258. Collection.prototype.forEach = function (block) {
  20259. var key;
  20260. for (key in this._collection) {
  20261. if (this._collection.hasOwnProperty(key)) {
  20262. block(this._collection[key]);
  20263. }
  20264. }
  20265. };
  20266. return Collection;
  20267. })();
  20268. VirtualJoystick.Collection = Collection;
  20269. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20270. })(BABYLON || (BABYLON = {}));
  20271. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20272. var BABYLON;
  20273. (function (BABYLON) {
  20274. var OculusRiftDevKit2013_Metric = {
  20275. HResolution: 1280,
  20276. VResolution: 800,
  20277. HScreenSize: 0.149759993,
  20278. VScreenSize: 0.0935999975,
  20279. VScreenCenter: 0.0467999987,
  20280. EyeToScreenDistance: 0.0410000011,
  20281. LensSeparationDistance: 0.0635000020,
  20282. InterpupillaryDistance: 0.0640000030,
  20283. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20284. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20285. PostProcessScaleFactor: 1.714605507808412,
  20286. LensCenterOffset: 0.151976421
  20287. };
  20288. var _OculusInnerCamera = (function (_super) {
  20289. __extends(_OculusInnerCamera, _super);
  20290. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20291. _super.call(this, name, position, scene);
  20292. this._workMatrix = new BABYLON.Matrix();
  20293. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20294. // Constants
  20295. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20296. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20297. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20298. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20299. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20300. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20301. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20302. // Postprocess
  20303. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20304. }
  20305. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20306. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20307. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20308. return this._projectionMatrix;
  20309. };
  20310. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20311. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20312. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20313. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20314. // Computing target and final matrix
  20315. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20316. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20317. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20318. return this._viewMatrix;
  20319. };
  20320. return _OculusInnerCamera;
  20321. })(BABYLON.FreeCamera);
  20322. var OculusCamera = (function (_super) {
  20323. __extends(OculusCamera, _super);
  20324. function OculusCamera(name, position, scene) {
  20325. _super.call(this, name, position, scene);
  20326. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20327. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20328. this.subCameras.push(this._leftCamera);
  20329. this.subCameras.push(this._rightCamera);
  20330. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20331. }
  20332. OculusCamera.prototype._update = function () {
  20333. this._leftCamera.position.copyFrom(this.position);
  20334. this._rightCamera.position.copyFrom(this.position);
  20335. this._updateCamera(this._leftCamera);
  20336. this._updateCamera(this._rightCamera);
  20337. _super.prototype._update.call(this);
  20338. };
  20339. OculusCamera.prototype._updateCamera = function (camera) {
  20340. camera.minZ = this.minZ;
  20341. camera.maxZ = this.maxZ;
  20342. camera.rotation.x = this.rotation.x;
  20343. camera.rotation.y = this.rotation.y;
  20344. camera.rotation.z = this.rotation.z;
  20345. };
  20346. // Oculus events
  20347. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20348. var yaw = evt.alpha / 180 * Math.PI;
  20349. var pitch = evt.beta / 180 * Math.PI;
  20350. var roll = evt.gamma / 180 * Math.PI;
  20351. if (!this._offsetOrientation) {
  20352. this._offsetOrientation = {
  20353. yaw: yaw,
  20354. pitch: pitch,
  20355. roll: roll
  20356. };
  20357. return;
  20358. }
  20359. else {
  20360. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20361. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20362. this.rotation.z += this._offsetOrientation.roll - roll;
  20363. this._offsetOrientation.yaw = yaw;
  20364. this._offsetOrientation.pitch = pitch;
  20365. this._offsetOrientation.roll = roll;
  20366. }
  20367. };
  20368. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20369. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20370. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20371. };
  20372. OculusCamera.prototype.detachControl = function (element) {
  20373. _super.prototype.detachControl.call(this, element);
  20374. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20375. };
  20376. return OculusCamera;
  20377. })(BABYLON.FreeCamera);
  20378. BABYLON.OculusCamera = OculusCamera;
  20379. })(BABYLON || (BABYLON = {}));
  20380. //# sourceMappingURL=babylon.oculusCamera.js.map
  20381. var BABYLON;
  20382. (function (BABYLON) {
  20383. var OculusRiftDevKit2013_Metric = {
  20384. HResolution: 1280,
  20385. VResolution: 800,
  20386. HScreenSize: 0.149759993,
  20387. VScreenSize: 0.0935999975,
  20388. VScreenCenter: 0.0467999987,
  20389. EyeToScreenDistance: 0.0410000011,
  20390. LensSeparationDistance: 0.0635000020,
  20391. InterpupillaryDistance: 0.0640000030,
  20392. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20393. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20394. PostProcessScaleFactor: 1.714605507808412,
  20395. LensCenterOffset: 0.151976421
  20396. };
  20397. var _OculusInnerGamepadCamera = (function (_super) {
  20398. __extends(_OculusInnerGamepadCamera, _super);
  20399. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20400. _super.call(this, name, position, scene);
  20401. this._workMatrix = new BABYLON.Matrix();
  20402. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20403. // Constants
  20404. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20405. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20406. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20407. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20408. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20409. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20410. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20411. // Postprocess
  20412. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20413. }
  20414. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20415. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20416. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20417. return this._projectionMatrix;
  20418. };
  20419. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20420. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20421. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20422. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20423. // Computing target and final matrix
  20424. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20425. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20426. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20427. return this._viewMatrix;
  20428. };
  20429. return _OculusInnerGamepadCamera;
  20430. })(BABYLON.FreeCamera);
  20431. var OculusGamepadCamera = (function (_super) {
  20432. __extends(OculusGamepadCamera, _super);
  20433. function OculusGamepadCamera(name, position, scene) {
  20434. var _this = this;
  20435. _super.call(this, name, position, scene);
  20436. this.angularSensibility = 200;
  20437. this.moveSensibility = 75;
  20438. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20439. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20440. this.subCameras.push(this._leftCamera);
  20441. this.subCameras.push(this._rightCamera);
  20442. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20443. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20444. _this._onNewGameConnected(gamepad);
  20445. });
  20446. }
  20447. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20448. // Only the first gamepad can control the camera
  20449. if (gamepad.index === 0) {
  20450. this._gamepad = gamepad;
  20451. }
  20452. };
  20453. OculusGamepadCamera.prototype._update = function () {
  20454. this._leftCamera.position.copyFrom(this.position);
  20455. this._rightCamera.position.copyFrom(this.position);
  20456. this._updateCamera(this._leftCamera);
  20457. this._updateCamera(this._rightCamera);
  20458. _super.prototype._update.call(this);
  20459. };
  20460. OculusGamepadCamera.prototype._checkInputs = function () {
  20461. if (!this._gamepad) {
  20462. return;
  20463. }
  20464. var LSValues = this._gamepad.leftStick;
  20465. var normalizedLX = LSValues.x / this.moveSensibility;
  20466. var normalizedLY = LSValues.y / this.moveSensibility;
  20467. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20468. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20469. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20470. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20471. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20472. };
  20473. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20474. camera.minZ = this.minZ;
  20475. camera.maxZ = this.maxZ;
  20476. camera.rotation.x = this.rotation.x;
  20477. camera.rotation.y = this.rotation.y;
  20478. camera.rotation.z = this.rotation.z;
  20479. };
  20480. // Oculus events
  20481. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20482. var yaw = evt.alpha / 180 * Math.PI;
  20483. var pitch = evt.beta / 180 * Math.PI;
  20484. var roll = evt.gamma / 180 * Math.PI;
  20485. if (!this._offsetOrientation) {
  20486. this._offsetOrientation = {
  20487. yaw: yaw,
  20488. pitch: pitch,
  20489. roll: roll
  20490. };
  20491. return;
  20492. }
  20493. else {
  20494. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20495. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20496. this.rotation.z += this._offsetOrientation.roll - roll;
  20497. this._offsetOrientation.yaw = yaw;
  20498. this._offsetOrientation.pitch = pitch;
  20499. this._offsetOrientation.roll = roll;
  20500. }
  20501. };
  20502. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20503. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20504. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20505. };
  20506. OculusGamepadCamera.prototype.detachControl = function (element) {
  20507. _super.prototype.detachControl.call(this, element);
  20508. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20509. };
  20510. OculusGamepadCamera.prototype.dispose = function () {
  20511. this._gamepads.dispose();
  20512. _super.prototype.dispose.call(this);
  20513. };
  20514. return OculusGamepadCamera;
  20515. })(BABYLON.FreeCamera);
  20516. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20517. })(BABYLON || (BABYLON = {}));
  20518. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20519. var BABYLON;
  20520. (function (BABYLON) {
  20521. // We're mainly based on the logic defined into the FreeCamera code
  20522. var VirtualJoysticksCamera = (function (_super) {
  20523. __extends(VirtualJoysticksCamera, _super);
  20524. function VirtualJoysticksCamera(name, position, scene) {
  20525. _super.call(this, name, position, scene);
  20526. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20527. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20528. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20529. this._leftjoystick.setJoystickSensibility(0.15);
  20530. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20531. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20532. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20533. this._rightjoystick.reverseUpDown = true;
  20534. this._rightjoystick.setJoystickSensibility(0.05);
  20535. this._rightjoystick.setJoystickColor("yellow");
  20536. }
  20537. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20538. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20539. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20540. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20541. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20542. if (!this._leftjoystick.pressed) {
  20543. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20544. }
  20545. if (!this._rightjoystick.pressed) {
  20546. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20547. }
  20548. };
  20549. VirtualJoysticksCamera.prototype.dispose = function () {
  20550. this._leftjoystick.releaseCanvas();
  20551. _super.prototype.dispose.call(this);
  20552. };
  20553. return VirtualJoysticksCamera;
  20554. })(BABYLON.FreeCamera);
  20555. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20556. })(BABYLON || (BABYLON = {}));
  20557. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20558. var BABYLON;
  20559. (function (BABYLON) {
  20560. var ShaderMaterial = (function (_super) {
  20561. __extends(ShaderMaterial, _super);
  20562. function ShaderMaterial(name, scene, shaderPath, options) {
  20563. _super.call(this, name, scene);
  20564. this._textures = new Array();
  20565. this._floats = new Array();
  20566. this._floatsArrays = {};
  20567. this._colors3 = new Array();
  20568. this._colors4 = new Array();
  20569. this._vectors2 = new Array();
  20570. this._vectors3 = new Array();
  20571. this._matrices = new Array();
  20572. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20573. this._shaderPath = shaderPath;
  20574. options.needAlphaBlending = options.needAlphaBlending || false;
  20575. options.needAlphaTesting = options.needAlphaTesting || false;
  20576. options.attributes = options.attributes || ["position", "normal", "uv"];
  20577. options.uniforms = options.uniforms || ["worldViewProjection"];
  20578. options.samplers = options.samplers || [];
  20579. this._options = options;
  20580. }
  20581. ShaderMaterial.prototype.needAlphaBlending = function () {
  20582. return this._options.needAlphaBlending;
  20583. };
  20584. ShaderMaterial.prototype.needAlphaTesting = function () {
  20585. return this._options.needAlphaTesting;
  20586. };
  20587. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20588. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20589. this._options.uniforms.push(uniformName);
  20590. }
  20591. };
  20592. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20593. if (this._options.samplers.indexOf(name) === -1) {
  20594. this._options.samplers.push(name);
  20595. }
  20596. this._textures[name] = texture;
  20597. return this;
  20598. };
  20599. ShaderMaterial.prototype.setFloat = function (name, value) {
  20600. this._checkUniform(name);
  20601. this._floats[name] = value;
  20602. return this;
  20603. };
  20604. ShaderMaterial.prototype.setFloats = function (name, value) {
  20605. this._checkUniform(name);
  20606. this._floatsArrays[name] = value;
  20607. return this;
  20608. };
  20609. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20610. this._checkUniform(name);
  20611. this._colors3[name] = value;
  20612. return this;
  20613. };
  20614. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20615. this._checkUniform(name);
  20616. this._colors4[name] = value;
  20617. return this;
  20618. };
  20619. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20620. this._checkUniform(name);
  20621. this._vectors2[name] = value;
  20622. return this;
  20623. };
  20624. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20625. this._checkUniform(name);
  20626. this._vectors3[name] = value;
  20627. return this;
  20628. };
  20629. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20630. this._checkUniform(name);
  20631. this._matrices[name] = value;
  20632. return this;
  20633. };
  20634. ShaderMaterial.prototype.isReady = function () {
  20635. var scene = this.getScene();
  20636. var engine = scene.getEngine();
  20637. if (!this.checkReadyOnEveryCall) {
  20638. if (this._renderId === scene.getRenderId()) {
  20639. return true;
  20640. }
  20641. }
  20642. var previousEffect = this._effect;
  20643. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20644. if (!this._effect.isReady()) {
  20645. return false;
  20646. }
  20647. if (previousEffect !== this._effect) {
  20648. scene.resetCachedMaterial();
  20649. }
  20650. this._renderId = scene.getRenderId();
  20651. return true;
  20652. };
  20653. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20654. var scene = this.getScene();
  20655. if (this._options.uniforms.indexOf("world") !== -1) {
  20656. this._effect.setMatrix("world", world);
  20657. }
  20658. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20659. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20660. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20661. }
  20662. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20663. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20664. }
  20665. };
  20666. ShaderMaterial.prototype.bind = function (world) {
  20667. // Std values
  20668. this.bindOnlyWorldMatrix(world);
  20669. if (this.getScene().getCachedMaterial() !== this) {
  20670. if (this._options.uniforms.indexOf("view") !== -1) {
  20671. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20672. }
  20673. if (this._options.uniforms.indexOf("projection") !== -1) {
  20674. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20675. }
  20676. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20677. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20678. }
  20679. for (var name in this._textures) {
  20680. this._effect.setTexture(name, this._textures[name]);
  20681. }
  20682. for (name in this._floats) {
  20683. this._effect.setFloat(name, this._floats[name]);
  20684. }
  20685. for (name in this._floatsArrays) {
  20686. this._effect.setArray(name, this._floatsArrays[name]);
  20687. }
  20688. for (name in this._colors3) {
  20689. this._effect.setColor3(name, this._colors3[name]);
  20690. }
  20691. for (name in this._colors4) {
  20692. var color = this._colors4[name];
  20693. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20694. }
  20695. for (name in this._vectors2) {
  20696. this._effect.setVector2(name, this._vectors2[name]);
  20697. }
  20698. for (name in this._vectors3) {
  20699. this._effect.setVector3(name, this._vectors3[name]);
  20700. }
  20701. for (name in this._matrices) {
  20702. this._effect.setMatrix(name, this._matrices[name]);
  20703. }
  20704. }
  20705. _super.prototype.bind.call(this, world, null);
  20706. };
  20707. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20708. for (var name in this._textures) {
  20709. this._textures[name].dispose();
  20710. }
  20711. this._textures = [];
  20712. _super.prototype.dispose.call(this, forceDisposeEffect);
  20713. };
  20714. return ShaderMaterial;
  20715. })(BABYLON.Material);
  20716. BABYLON.ShaderMaterial = ShaderMaterial;
  20717. })(BABYLON || (BABYLON = {}));
  20718. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20719. (function (BABYLON) {
  20720. var VertexData = (function () {
  20721. function VertexData() {
  20722. }
  20723. VertexData.prototype.set = function (data, kind) {
  20724. switch (kind) {
  20725. case BABYLON.VertexBuffer.PositionKind:
  20726. this.positions = data;
  20727. break;
  20728. case BABYLON.VertexBuffer.NormalKind:
  20729. this.normals = data;
  20730. break;
  20731. case BABYLON.VertexBuffer.UVKind:
  20732. this.uvs = data;
  20733. break;
  20734. case BABYLON.VertexBuffer.UV2Kind:
  20735. this.uv2s = data;
  20736. break;
  20737. case BABYLON.VertexBuffer.ColorKind:
  20738. this.colors = data;
  20739. break;
  20740. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20741. this.matricesIndices = data;
  20742. break;
  20743. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20744. this.matricesWeights = data;
  20745. break;
  20746. }
  20747. };
  20748. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20749. this._applyTo(mesh, updatable);
  20750. };
  20751. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20752. this._applyTo(geometry, updatable);
  20753. };
  20754. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20755. this._update(mesh);
  20756. };
  20757. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20758. this._update(geometry);
  20759. };
  20760. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20761. if (this.positions) {
  20762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20763. }
  20764. if (this.normals) {
  20765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20766. }
  20767. if (this.uvs) {
  20768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20769. }
  20770. if (this.uv2s) {
  20771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20772. }
  20773. if (this.colors) {
  20774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20775. }
  20776. if (this.matricesIndices) {
  20777. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20778. }
  20779. if (this.matricesWeights) {
  20780. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20781. }
  20782. if (this.indices) {
  20783. meshOrGeometry.setIndices(this.indices);
  20784. }
  20785. };
  20786. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20787. if (this.positions) {
  20788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20789. }
  20790. if (this.normals) {
  20791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20792. }
  20793. if (this.uvs) {
  20794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20795. }
  20796. if (this.uv2s) {
  20797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20798. }
  20799. if (this.colors) {
  20800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20801. }
  20802. if (this.matricesIndices) {
  20803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20804. }
  20805. if (this.matricesWeights) {
  20806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20807. }
  20808. if (this.indices) {
  20809. meshOrGeometry.setIndices(this.indices);
  20810. }
  20811. };
  20812. VertexData.prototype.transform = function (matrix) {
  20813. var transformed = BABYLON.Vector3.Zero();
  20814. if (this.positions) {
  20815. var position = BABYLON.Vector3.Zero();
  20816. for (var index = 0; index < this.positions.length; index += 3) {
  20817. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20818. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20819. this.positions[index] = transformed.x;
  20820. this.positions[index + 1] = transformed.y;
  20821. this.positions[index + 2] = transformed.z;
  20822. }
  20823. }
  20824. if (this.normals) {
  20825. var normal = BABYLON.Vector3.Zero();
  20826. for (index = 0; index < this.normals.length; index += 3) {
  20827. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20828. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20829. this.normals[index] = transformed.x;
  20830. this.normals[index + 1] = transformed.y;
  20831. this.normals[index + 2] = transformed.z;
  20832. }
  20833. }
  20834. };
  20835. VertexData.prototype.merge = function (other) {
  20836. if (other.indices) {
  20837. if (!this.indices) {
  20838. this.indices = [];
  20839. }
  20840. var offset = this.positions ? this.positions.length / 3 : 0;
  20841. for (var index = 0; index < other.indices.length; index++) {
  20842. this.indices.push(other.indices[index] + offset);
  20843. }
  20844. }
  20845. if (other.positions) {
  20846. if (!this.positions) {
  20847. this.positions = [];
  20848. }
  20849. for (index = 0; index < other.positions.length; index++) {
  20850. this.positions.push(other.positions[index]);
  20851. }
  20852. }
  20853. if (other.normals) {
  20854. if (!this.normals) {
  20855. this.normals = [];
  20856. }
  20857. for (index = 0; index < other.normals.length; index++) {
  20858. this.normals.push(other.normals[index]);
  20859. }
  20860. }
  20861. if (other.uvs) {
  20862. if (!this.uvs) {
  20863. this.uvs = [];
  20864. }
  20865. for (index = 0; index < other.uvs.length; index++) {
  20866. this.uvs.push(other.uvs[index]);
  20867. }
  20868. }
  20869. if (other.uv2s) {
  20870. if (!this.uv2s) {
  20871. this.uv2s = [];
  20872. }
  20873. for (index = 0; index < other.uv2s.length; index++) {
  20874. this.uv2s.push(other.uv2s[index]);
  20875. }
  20876. }
  20877. if (other.matricesIndices) {
  20878. if (!this.matricesIndices) {
  20879. this.matricesIndices = [];
  20880. }
  20881. for (index = 0; index < other.matricesIndices.length; index++) {
  20882. this.matricesIndices.push(other.matricesIndices[index]);
  20883. }
  20884. }
  20885. if (other.matricesWeights) {
  20886. if (!this.matricesWeights) {
  20887. this.matricesWeights = [];
  20888. }
  20889. for (index = 0; index < other.matricesWeights.length; index++) {
  20890. this.matricesWeights.push(other.matricesWeights[index]);
  20891. }
  20892. }
  20893. if (other.colors) {
  20894. if (!this.colors) {
  20895. this.colors = [];
  20896. }
  20897. for (index = 0; index < other.colors.length; index++) {
  20898. this.colors.push(other.colors[index]);
  20899. }
  20900. }
  20901. };
  20902. // Statics
  20903. VertexData.ExtractFromMesh = function (mesh) {
  20904. return VertexData._ExtractFrom(mesh);
  20905. };
  20906. VertexData.ExtractFromGeometry = function (geometry) {
  20907. return VertexData._ExtractFrom(geometry);
  20908. };
  20909. VertexData._ExtractFrom = function (meshOrGeometry) {
  20910. var result = new VertexData();
  20911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20912. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20913. }
  20914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20915. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20916. }
  20917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20918. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20919. }
  20920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20921. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20922. }
  20923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20924. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20925. }
  20926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20927. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20928. }
  20929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20930. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20931. }
  20932. result.indices = meshOrGeometry.getIndices();
  20933. return result;
  20934. };
  20935. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset) {
  20936. closeArray = closeArray || false;
  20937. closePath = closePath || false;
  20938. var defaultOffset = Math.floor(pathArray[0].length / 2);
  20939. offset = offset || defaultOffset;
  20940. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  20941. var positions = [];
  20942. var indices = [];
  20943. var normals = [];
  20944. var uvs = [];
  20945. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  20946. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  20947. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  20948. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  20949. var minlg; // minimal length among all paths from pathArray
  20950. var lg = []; // array of path lengths : nb of vertex per path
  20951. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  20952. // if single path in pathArray
  20953. if (pathArray.length < 2) {
  20954. var ar1 = [];
  20955. var ar2 = [];
  20956. for (var i = 0; i < pathArray[0].length - offset; i++) {
  20957. ar1.push(pathArray[0][i]);
  20958. ar2.push(pathArray[0][i + offset]);
  20959. }
  20960. pathArray = [ar1, ar2];
  20961. }
  20962. // positions and horizontal distances (u)
  20963. var idc = 0;
  20964. minlg = pathArray[0].length;
  20965. for (p = 0; p < pathArray.length; p++) {
  20966. uTotalDistance[p] = 0;
  20967. us[p] = [0];
  20968. var path = pathArray[p];
  20969. var l = path.length;
  20970. minlg = (minlg < l) ? minlg : l;
  20971. lg[p] = l;
  20972. idx[p] = idc;
  20973. var j = 0;
  20974. while (j < l) {
  20975. positions.push(path[j].x, path[j].y, path[j].z);
  20976. if (j > 0) {
  20977. var vectlg = path[j].subtract(path[j - 1]).length();
  20978. var dist = vectlg + uTotalDistance[p];
  20979. us[p].push(dist);
  20980. uTotalDistance[p] = dist;
  20981. }
  20982. j++;
  20983. }
  20984. if (closePath) {
  20985. vectlg = path[0].subtract(path[j - 1]).length();
  20986. dist = vectlg + uTotalDistance[p];
  20987. uTotalDistance[p] = dist;
  20988. }
  20989. idc += l;
  20990. }
  20991. for (i = 0; i < minlg; i++) {
  20992. vTotalDistance[i] = 0;
  20993. vs[i] = [0];
  20994. for (p = 0; p < pathArray.length - 1; p++) {
  20995. var path1 = pathArray[p];
  20996. var path2 = pathArray[p + 1];
  20997. vectlg = path2[i].subtract(path1[i]).length();
  20998. dist = vectlg + vTotalDistance[i];
  20999. vs[i].push(dist);
  21000. vTotalDistance[i] = dist;
  21001. }
  21002. if (closeArray) {
  21003. path1 = pathArray[p];
  21004. path2 = pathArray[0];
  21005. vectlg = path2[i].subtract(path1[i]).length();
  21006. dist = vectlg + vTotalDistance[i];
  21007. vTotalDistance[i] = dist;
  21008. }
  21009. }
  21010. for (p = 0; p < pathArray.length; p++) {
  21011. for (i = 0; i < minlg; i++) {
  21012. var u = us[p][i] / uTotalDistance[p];
  21013. var v = vs[i][p] / vTotalDistance[i];
  21014. uvs.push(u, v);
  21015. }
  21016. }
  21017. // indices
  21018. var p = 0; // path index
  21019. var i = 0; // positions array index
  21020. var l1 = lg[p] - 1; // path1 length
  21021. var l2 = lg[p + 1] - 1; // path2 length
  21022. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21023. var shft = idx[1] - idx[0]; // shift
  21024. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21025. while (i <= min && p < path1nb) {
  21026. // draw two triangles between path1 (p1) and path2 (p2) : (p1.i, p2.i, p1.i+1) and (p2.i+1, p1.i+1, p2.i) clockwise
  21027. var t1 = i;
  21028. var t2 = i + shft;
  21029. var t3 = i + 1;
  21030. var t4 = i + shft + 1;
  21031. indices.push(i, i + shft, i + 1);
  21032. indices.push(i + shft + 1, i + 1, i + shft);
  21033. i += 1;
  21034. if (i === min) {
  21035. if (closePath) {
  21036. indices.push(i, i + shft, idx[p]);
  21037. indices.push(idx[p] + shft, idx[p], i + shft);
  21038. t3 = idx[p];
  21039. t4 = idx[p] + shft;
  21040. }
  21041. p++;
  21042. if (p === lg.length - 1) {
  21043. shft = idx[0] - idx[p];
  21044. l1 = lg[p] - 1;
  21045. l2 = lg[0] - 1;
  21046. }
  21047. else {
  21048. shft = idx[p + 1] - idx[p];
  21049. l1 = lg[p] - 1;
  21050. l2 = lg[p + 1] - 1;
  21051. }
  21052. i = idx[p];
  21053. min = (l1 < l2) ? l1 + i : l2 + i;
  21054. }
  21055. }
  21056. // normals
  21057. VertexData.ComputeNormals(positions, indices, normals);
  21058. // Result
  21059. var vertexData = new VertexData();
  21060. vertexData.indices = indices;
  21061. vertexData.positions = positions;
  21062. vertexData.normals = normals;
  21063. vertexData.uvs = uvs;
  21064. return vertexData;
  21065. };
  21066. VertexData.CreateBox = function (size) {
  21067. var normalsSource = [
  21068. new BABYLON.Vector3(0, 0, 1),
  21069. new BABYLON.Vector3(0, 0, -1),
  21070. new BABYLON.Vector3(1, 0, 0),
  21071. new BABYLON.Vector3(-1, 0, 0),
  21072. new BABYLON.Vector3(0, 1, 0),
  21073. new BABYLON.Vector3(0, -1, 0)
  21074. ];
  21075. var indices = [];
  21076. var positions = [];
  21077. var normals = [];
  21078. var uvs = [];
  21079. size = size || 1;
  21080. for (var index = 0; index < normalsSource.length; index++) {
  21081. var normal = normalsSource[index];
  21082. // Get two vectors perpendicular to the face normal and to each other.
  21083. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21084. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21085. // Six indices (two triangles) per face.
  21086. var verticesLength = positions.length / 3;
  21087. indices.push(verticesLength);
  21088. indices.push(verticesLength + 1);
  21089. indices.push(verticesLength + 2);
  21090. indices.push(verticesLength);
  21091. indices.push(verticesLength + 2);
  21092. indices.push(verticesLength + 3);
  21093. // Four vertices per face.
  21094. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21095. positions.push(vertex.x, vertex.y, vertex.z);
  21096. normals.push(normal.x, normal.y, normal.z);
  21097. uvs.push(1.0, 1.0);
  21098. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21099. positions.push(vertex.x, vertex.y, vertex.z);
  21100. normals.push(normal.x, normal.y, normal.z);
  21101. uvs.push(0.0, 1.0);
  21102. vertex = normal.add(side1).add(side2).scale(size / 2);
  21103. positions.push(vertex.x, vertex.y, vertex.z);
  21104. normals.push(normal.x, normal.y, normal.z);
  21105. uvs.push(0.0, 0.0);
  21106. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21107. positions.push(vertex.x, vertex.y, vertex.z);
  21108. normals.push(normal.x, normal.y, normal.z);
  21109. uvs.push(1.0, 0.0);
  21110. }
  21111. // Result
  21112. var vertexData = new VertexData();
  21113. vertexData.indices = indices;
  21114. vertexData.positions = positions;
  21115. vertexData.normals = normals;
  21116. vertexData.uvs = uvs;
  21117. return vertexData;
  21118. };
  21119. VertexData.CreateSphere = function (segments, diameter) {
  21120. segments = segments || 32;
  21121. diameter = diameter || 1;
  21122. var radius = diameter / 2;
  21123. var totalZRotationSteps = 2 + segments;
  21124. var totalYRotationSteps = 2 * totalZRotationSteps;
  21125. var indices = [];
  21126. var positions = [];
  21127. var normals = [];
  21128. var uvs = [];
  21129. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21130. var normalizedZ = zRotationStep / totalZRotationSteps;
  21131. var angleZ = (normalizedZ * Math.PI);
  21132. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21133. var normalizedY = yRotationStep / totalYRotationSteps;
  21134. var angleY = normalizedY * Math.PI * 2;
  21135. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21136. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21137. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21138. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21139. var vertex = complete.scale(radius);
  21140. var normal = BABYLON.Vector3.Normalize(vertex);
  21141. positions.push(vertex.x, vertex.y, vertex.z);
  21142. normals.push(normal.x, normal.y, normal.z);
  21143. uvs.push(normalizedZ, normalizedY);
  21144. }
  21145. if (zRotationStep > 0) {
  21146. var verticesCount = positions.length / 3;
  21147. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21148. indices.push((firstIndex));
  21149. indices.push((firstIndex + 1));
  21150. indices.push(firstIndex + totalYRotationSteps + 1);
  21151. indices.push((firstIndex + totalYRotationSteps + 1));
  21152. indices.push((firstIndex + 1));
  21153. indices.push((firstIndex + totalYRotationSteps + 2));
  21154. }
  21155. }
  21156. }
  21157. // Result
  21158. var vertexData = new VertexData();
  21159. vertexData.indices = indices;
  21160. vertexData.positions = positions;
  21161. vertexData.normals = normals;
  21162. vertexData.uvs = uvs;
  21163. return vertexData;
  21164. };
  21165. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  21166. if (subdivisions === void 0) { subdivisions = 1; }
  21167. var radiusTop = diameterTop / 2;
  21168. var radiusBottom = diameterBottom / 2;
  21169. var indices = [];
  21170. var positions = [];
  21171. var normals = [];
  21172. var uvs = [];
  21173. height = height || 1;
  21174. diameterTop = diameterTop || 0.5;
  21175. diameterBottom = diameterBottom || 1;
  21176. tessellation = tessellation || 16;
  21177. subdivisions = subdivisions || 1;
  21178. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21179. var getCircleVector = function (i) {
  21180. var angle = (i * 2.0 * Math.PI / tessellation);
  21181. var dx = Math.cos(angle);
  21182. var dz = Math.sin(angle);
  21183. return new BABYLON.Vector3(dx, 0, dz);
  21184. };
  21185. var createCylinderCap = function (isTop) {
  21186. var radius = isTop ? radiusTop : radiusBottom;
  21187. if (radius === 0) {
  21188. return;
  21189. }
  21190. var vbase = positions.length / 3;
  21191. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21192. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21193. if (!isTop) {
  21194. offset.scaleInPlace(-1);
  21195. textureScale.x = -textureScale.x;
  21196. }
  21197. for (var i = 0; i < tessellation; i++) {
  21198. var circleVector = getCircleVector(i);
  21199. var position = circleVector.scale(radius).add(offset);
  21200. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21201. positions.push(position.x, position.y, position.z);
  21202. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21203. }
  21204. for (i = 0; i < tessellation - 2; i++) {
  21205. if (!isTop) {
  21206. indices.push(vbase);
  21207. indices.push(vbase + (i + 2) % tessellation);
  21208. indices.push(vbase + (i + 1) % tessellation);
  21209. }
  21210. else {
  21211. indices.push(vbase);
  21212. indices.push(vbase + (i + 1) % tessellation);
  21213. indices.push(vbase + (i + 2) % tessellation);
  21214. }
  21215. }
  21216. };
  21217. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21218. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21219. var stride = tessellation + 1;
  21220. for (var i = 0; i <= tessellation; i++) {
  21221. var circleVector = getCircleVector(i);
  21222. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21223. var position, radius = radiusBottom;
  21224. for (var s = 0; s <= subdivisions; s++) {
  21225. // Update variables
  21226. position = circleVector.scale(radius);
  21227. position.addInPlace(base.add(offset.scale(s)));
  21228. textureCoordinate.y += 1 / subdivisions;
  21229. radius += (radiusTop - radiusBottom) / subdivisions;
  21230. // Push in arrays
  21231. positions.push(position.x, position.y, position.z);
  21232. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21233. }
  21234. }
  21235. subdivisions += 1;
  21236. for (s = 0; s < subdivisions - 1; s++) {
  21237. for (i = 0; i <= tessellation; i++) {
  21238. indices.push(i * subdivisions + s);
  21239. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21240. indices.push(i * subdivisions + (s + 1));
  21241. indices.push(i * subdivisions + (s + 1));
  21242. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21243. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21244. }
  21245. }
  21246. // Create flat triangle fan caps to seal the top and bottom.
  21247. createCylinderCap(true);
  21248. createCylinderCap(false);
  21249. // Normals
  21250. VertexData.ComputeNormals(positions, indices, normals);
  21251. // Result
  21252. var vertexData = new VertexData();
  21253. vertexData.indices = indices;
  21254. vertexData.positions = positions;
  21255. vertexData.normals = normals;
  21256. vertexData.uvs = uvs;
  21257. return vertexData;
  21258. };
  21259. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  21260. var indices = [];
  21261. var positions = [];
  21262. var normals = [];
  21263. var uvs = [];
  21264. diameter = diameter || 1;
  21265. thickness = thickness || 0.5;
  21266. tessellation = tessellation || 16;
  21267. var stride = tessellation + 1;
  21268. for (var i = 0; i <= tessellation; i++) {
  21269. var u = i / tessellation;
  21270. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21271. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21272. for (var j = 0; j <= tessellation; j++) {
  21273. var v = 1 - j / tessellation;
  21274. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21275. var dx = Math.cos(innerAngle);
  21276. var dy = Math.sin(innerAngle);
  21277. // Create a vertex.
  21278. var normal = new BABYLON.Vector3(dx, dy, 0);
  21279. var position = normal.scale(thickness / 2);
  21280. var textureCoordinate = new BABYLON.Vector2(u, v);
  21281. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21282. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21283. positions.push(position.x, position.y, position.z);
  21284. normals.push(normal.x, normal.y, normal.z);
  21285. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21286. // And create indices for two triangles.
  21287. var nextI = (i + 1) % stride;
  21288. var nextJ = (j + 1) % stride;
  21289. indices.push(i * stride + j);
  21290. indices.push(i * stride + nextJ);
  21291. indices.push(nextI * stride + j);
  21292. indices.push(i * stride + nextJ);
  21293. indices.push(nextI * stride + nextJ);
  21294. indices.push(nextI * stride + j);
  21295. }
  21296. }
  21297. // Result
  21298. var vertexData = new VertexData();
  21299. vertexData.indices = indices;
  21300. vertexData.positions = positions;
  21301. vertexData.normals = normals;
  21302. vertexData.uvs = uvs;
  21303. return vertexData;
  21304. };
  21305. VertexData.CreateLines = function (points) {
  21306. var indices = [];
  21307. var positions = [];
  21308. for (var index = 0; index < points.length; index++) {
  21309. positions.push(points[index].x, points[index].y, points[index].z);
  21310. if (index > 0) {
  21311. indices.push(index - 1);
  21312. indices.push(index);
  21313. }
  21314. }
  21315. // Result
  21316. var vertexData = new VertexData();
  21317. vertexData.indices = indices;
  21318. vertexData.positions = positions;
  21319. return vertexData;
  21320. };
  21321. VertexData.CreateGround = function (width, height, subdivisions) {
  21322. var indices = [];
  21323. var positions = [];
  21324. var normals = [];
  21325. var uvs = [];
  21326. var row, col;
  21327. width = width || 1;
  21328. height = height || 1;
  21329. subdivisions = subdivisions || 1;
  21330. for (row = 0; row <= subdivisions; row++) {
  21331. for (col = 0; col <= subdivisions; col++) {
  21332. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21333. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21334. positions.push(position.x, position.y, position.z);
  21335. normals.push(normal.x, normal.y, normal.z);
  21336. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21337. }
  21338. }
  21339. for (row = 0; row < subdivisions; row++) {
  21340. for (col = 0; col < subdivisions; col++) {
  21341. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21342. indices.push(col + 1 + row * (subdivisions + 1));
  21343. indices.push(col + row * (subdivisions + 1));
  21344. indices.push(col + (row + 1) * (subdivisions + 1));
  21345. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21346. indices.push(col + row * (subdivisions + 1));
  21347. }
  21348. }
  21349. // Result
  21350. var vertexData = new VertexData();
  21351. vertexData.indices = indices;
  21352. vertexData.positions = positions;
  21353. vertexData.normals = normals;
  21354. vertexData.uvs = uvs;
  21355. return vertexData;
  21356. };
  21357. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21358. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21359. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21360. var indices = [];
  21361. var positions = [];
  21362. var normals = [];
  21363. var uvs = [];
  21364. var row, col, tileRow, tileCol;
  21365. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21366. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21367. precision.w = (precision.w < 1) ? 1 : precision.w;
  21368. precision.h = (precision.h < 1) ? 1 : precision.h;
  21369. var tileSize = {
  21370. 'w': (xmax - xmin) / subdivisions.w,
  21371. 'h': (zmax - zmin) / subdivisions.h
  21372. };
  21373. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21374. // Indices
  21375. var base = positions.length / 3;
  21376. var rowLength = precision.w + 1;
  21377. for (row = 0; row < precision.h; row++) {
  21378. for (col = 0; col < precision.w; col++) {
  21379. var square = [
  21380. base + col + row * rowLength,
  21381. base + (col + 1) + row * rowLength,
  21382. base + (col + 1) + (row + 1) * rowLength,
  21383. base + col + (row + 1) * rowLength
  21384. ];
  21385. indices.push(square[1]);
  21386. indices.push(square[2]);
  21387. indices.push(square[3]);
  21388. indices.push(square[0]);
  21389. indices.push(square[1]);
  21390. indices.push(square[3]);
  21391. }
  21392. }
  21393. // Position, normals and uvs
  21394. var position = BABYLON.Vector3.Zero();
  21395. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21396. for (row = 0; row <= precision.h; row++) {
  21397. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21398. for (col = 0; col <= precision.w; col++) {
  21399. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21400. position.y = 0;
  21401. positions.push(position.x, position.y, position.z);
  21402. normals.push(normal.x, normal.y, normal.z);
  21403. uvs.push(col / precision.w, row / precision.h);
  21404. }
  21405. }
  21406. }
  21407. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21408. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21409. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21410. }
  21411. }
  21412. // Result
  21413. var vertexData = new VertexData();
  21414. vertexData.indices = indices;
  21415. vertexData.positions = positions;
  21416. vertexData.normals = normals;
  21417. vertexData.uvs = uvs;
  21418. return vertexData;
  21419. };
  21420. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21421. var indices = [];
  21422. var positions = [];
  21423. var normals = [];
  21424. var uvs = [];
  21425. var row, col;
  21426. for (row = 0; row <= subdivisions; row++) {
  21427. for (col = 0; col <= subdivisions; col++) {
  21428. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21429. // Compute height
  21430. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21431. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21432. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21433. var r = buffer[pos] / 255.0;
  21434. var g = buffer[pos + 1] / 255.0;
  21435. var b = buffer[pos + 2] / 255.0;
  21436. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21437. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21438. // Add vertex
  21439. positions.push(position.x, position.y, position.z);
  21440. normals.push(0, 0, 0);
  21441. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21442. }
  21443. }
  21444. for (row = 0; row < subdivisions; row++) {
  21445. for (col = 0; col < subdivisions; col++) {
  21446. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21447. indices.push(col + 1 + row * (subdivisions + 1));
  21448. indices.push(col + row * (subdivisions + 1));
  21449. indices.push(col + (row + 1) * (subdivisions + 1));
  21450. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21451. indices.push(col + row * (subdivisions + 1));
  21452. }
  21453. }
  21454. // Normals
  21455. VertexData.ComputeNormals(positions, indices, normals);
  21456. // Result
  21457. var vertexData = new VertexData();
  21458. vertexData.indices = indices;
  21459. vertexData.positions = positions;
  21460. vertexData.normals = normals;
  21461. vertexData.uvs = uvs;
  21462. return vertexData;
  21463. };
  21464. VertexData.CreatePlane = function (size) {
  21465. var indices = [];
  21466. var positions = [];
  21467. var normals = [];
  21468. var uvs = [];
  21469. size = size || 1;
  21470. // Vertices
  21471. var halfSize = size / 2.0;
  21472. positions.push(-halfSize, -halfSize, 0);
  21473. normals.push(0, 0, -1.0);
  21474. uvs.push(0.0, 0.0);
  21475. positions.push(halfSize, -halfSize, 0);
  21476. normals.push(0, 0, -1.0);
  21477. uvs.push(1.0, 0.0);
  21478. positions.push(halfSize, halfSize, 0);
  21479. normals.push(0, 0, -1.0);
  21480. uvs.push(1.0, 1.0);
  21481. positions.push(-halfSize, halfSize, 0);
  21482. normals.push(0, 0, -1.0);
  21483. uvs.push(0.0, 1.0);
  21484. // Indices
  21485. indices.push(0);
  21486. indices.push(1);
  21487. indices.push(2);
  21488. indices.push(0);
  21489. indices.push(2);
  21490. indices.push(3);
  21491. // Result
  21492. var vertexData = new VertexData();
  21493. vertexData.indices = indices;
  21494. vertexData.positions = positions;
  21495. vertexData.normals = normals;
  21496. vertexData.uvs = uvs;
  21497. return vertexData;
  21498. };
  21499. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21500. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21501. var indices = [];
  21502. var positions = [];
  21503. var normals = [];
  21504. var uvs = [];
  21505. radius = radius || 2;
  21506. tube = tube || 0.5;
  21507. radialSegments = radialSegments || 32;
  21508. tubularSegments = tubularSegments || 32;
  21509. p = p || 2;
  21510. q = q || 3;
  21511. // Helper
  21512. var getPos = function (angle) {
  21513. var cu = Math.cos(angle);
  21514. var su = Math.sin(angle);
  21515. var quOverP = q / p * angle;
  21516. var cs = Math.cos(quOverP);
  21517. var tx = radius * (2 + cs) * 0.5 * cu;
  21518. var ty = radius * (2 + cs) * su * 0.5;
  21519. var tz = radius * Math.sin(quOverP) * 0.5;
  21520. return new BABYLON.Vector3(tx, ty, tz);
  21521. };
  21522. for (var i = 0; i <= radialSegments; i++) {
  21523. var modI = i % radialSegments;
  21524. var u = modI / radialSegments * 2 * p * Math.PI;
  21525. var p1 = getPos(u);
  21526. var p2 = getPos(u + 0.01);
  21527. var tang = p2.subtract(p1);
  21528. var n = p2.add(p1);
  21529. var bitan = BABYLON.Vector3.Cross(tang, n);
  21530. n = BABYLON.Vector3.Cross(bitan, tang);
  21531. bitan.normalize();
  21532. n.normalize();
  21533. for (var j = 0; j < tubularSegments; j++) {
  21534. var modJ = j % tubularSegments;
  21535. var v = modJ / tubularSegments * 2 * Math.PI;
  21536. var cx = -tube * Math.cos(v);
  21537. var cy = tube * Math.sin(v);
  21538. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21539. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21540. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21541. uvs.push(i / radialSegments);
  21542. uvs.push(j / tubularSegments);
  21543. }
  21544. }
  21545. for (i = 0; i < radialSegments; i++) {
  21546. for (j = 0; j < tubularSegments; j++) {
  21547. var jNext = (j + 1) % tubularSegments;
  21548. var a = i * tubularSegments + j;
  21549. var b = (i + 1) * tubularSegments + j;
  21550. var c = (i + 1) * tubularSegments + jNext;
  21551. var d = i * tubularSegments + jNext;
  21552. indices.push(d);
  21553. indices.push(b);
  21554. indices.push(a);
  21555. indices.push(d);
  21556. indices.push(c);
  21557. indices.push(b);
  21558. }
  21559. }
  21560. // Normals
  21561. VertexData.ComputeNormals(positions, indices, normals);
  21562. // Result
  21563. var vertexData = new VertexData();
  21564. vertexData.indices = indices;
  21565. vertexData.positions = positions;
  21566. vertexData.normals = normals;
  21567. vertexData.uvs = uvs;
  21568. return vertexData;
  21569. };
  21570. // Tools
  21571. VertexData.ComputeNormals = function (positions, indices, normals) {
  21572. var positionVectors = [];
  21573. var facesOfVertices = [];
  21574. var index;
  21575. for (index = 0; index < positions.length; index += 3) {
  21576. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21577. positionVectors.push(vector3);
  21578. facesOfVertices.push([]);
  21579. }
  21580. // Compute normals
  21581. var facesNormals = [];
  21582. for (index = 0; index < indices.length / 3; index++) {
  21583. var i1 = indices[index * 3];
  21584. var i2 = indices[index * 3 + 1];
  21585. var i3 = indices[index * 3 + 2];
  21586. var p1 = positionVectors[i1];
  21587. var p2 = positionVectors[i2];
  21588. var p3 = positionVectors[i3];
  21589. var p1p2 = p1.subtract(p2);
  21590. var p3p2 = p3.subtract(p2);
  21591. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21592. facesOfVertices[i1].push(index);
  21593. facesOfVertices[i2].push(index);
  21594. facesOfVertices[i3].push(index);
  21595. }
  21596. for (index = 0; index < positionVectors.length; index++) {
  21597. var faces = facesOfVertices[index];
  21598. var normal = BABYLON.Vector3.Zero();
  21599. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21600. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21601. }
  21602. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21603. normals[index * 3] = normal.x;
  21604. normals[index * 3 + 1] = normal.y;
  21605. normals[index * 3 + 2] = normal.z;
  21606. }
  21607. };
  21608. return VertexData;
  21609. })();
  21610. BABYLON.VertexData = VertexData;
  21611. })(BABYLON || (BABYLON = {}));
  21612. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21613. var BABYLON;
  21614. (function (BABYLON) {
  21615. var buildCamera = function (that, name) {
  21616. that._leftCamera.isIntermediate = true;
  21617. that.subCameras.push(that._leftCamera);
  21618. that.subCameras.push(that._rightCamera);
  21619. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21620. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21621. that._anaglyphPostProcess.onApply = function (effect) {
  21622. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21623. };
  21624. that._update();
  21625. };
  21626. var AnaglyphArcRotateCamera = (function (_super) {
  21627. __extends(AnaglyphArcRotateCamera, _super);
  21628. // ANY
  21629. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21630. _super.call(this, name, alpha, beta, radius, target, scene);
  21631. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21632. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21633. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21634. buildCamera(this, name);
  21635. }
  21636. AnaglyphArcRotateCamera.prototype._update = function () {
  21637. this._updateCamera(this._leftCamera);
  21638. this._updateCamera(this._rightCamera);
  21639. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21640. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21641. _super.prototype._update.call(this);
  21642. };
  21643. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21644. camera.beta = this.beta;
  21645. camera.radius = this.radius;
  21646. camera.minZ = this.minZ;
  21647. camera.maxZ = this.maxZ;
  21648. camera.fov = this.fov;
  21649. camera.target = this.target;
  21650. };
  21651. return AnaglyphArcRotateCamera;
  21652. })(BABYLON.ArcRotateCamera);
  21653. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21654. var AnaglyphFreeCamera = (function (_super) {
  21655. __extends(AnaglyphFreeCamera, _super);
  21656. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21657. _super.call(this, name, position, scene);
  21658. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21659. this._transformMatrix = new BABYLON.Matrix();
  21660. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21661. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21662. buildCamera(this, name);
  21663. }
  21664. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21665. var target = this.getTarget();
  21666. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21667. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21668. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21669. };
  21670. AnaglyphFreeCamera.prototype._update = function () {
  21671. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21672. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21673. this._updateCamera(this._leftCamera);
  21674. this._updateCamera(this._rightCamera);
  21675. _super.prototype._update.call(this);
  21676. };
  21677. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21678. camera.minZ = this.minZ;
  21679. camera.maxZ = this.maxZ;
  21680. camera.fov = this.fov;
  21681. camera.viewport = this.viewport;
  21682. camera.setTarget(this.getTarget());
  21683. };
  21684. return AnaglyphFreeCamera;
  21685. })(BABYLON.FreeCamera);
  21686. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21687. })(BABYLON || (BABYLON = {}));
  21688. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21689. var BABYLON;
  21690. (function (BABYLON) {
  21691. var AnaglyphPostProcess = (function (_super) {
  21692. __extends(AnaglyphPostProcess, _super);
  21693. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21694. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21695. }
  21696. return AnaglyphPostProcess;
  21697. })(BABYLON.PostProcess);
  21698. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21699. })(BABYLON || (BABYLON = {}));
  21700. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21701. (function (BABYLON) {
  21702. var Tags = (function () {
  21703. function Tags() {
  21704. }
  21705. Tags.EnableFor = function (obj) {
  21706. obj._tags = obj._tags || {};
  21707. obj.hasTags = function () {
  21708. return Tags.HasTags(obj);
  21709. };
  21710. obj.addTags = function (tagsString) {
  21711. return Tags.AddTagsTo(obj, tagsString);
  21712. };
  21713. obj.removeTags = function (tagsString) {
  21714. return Tags.RemoveTagsFrom(obj, tagsString);
  21715. };
  21716. obj.matchesTagsQuery = function (tagsQuery) {
  21717. return Tags.MatchesQuery(obj, tagsQuery);
  21718. };
  21719. };
  21720. Tags.DisableFor = function (obj) {
  21721. delete obj._tags;
  21722. delete obj.hasTags;
  21723. delete obj.addTags;
  21724. delete obj.removeTags;
  21725. delete obj.matchesTagsQuery;
  21726. };
  21727. Tags.HasTags = function (obj) {
  21728. if (!obj._tags) {
  21729. return false;
  21730. }
  21731. return !BABYLON.Tools.IsEmpty(obj._tags);
  21732. };
  21733. Tags.GetTags = function (obj) {
  21734. if (!obj._tags) {
  21735. return null;
  21736. }
  21737. return obj._tags;
  21738. };
  21739. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21740. // a tag cannot start with '||', '&&', and '!'
  21741. // it cannot contain whitespaces
  21742. Tags.AddTagsTo = function (obj, tagsString) {
  21743. if (!tagsString) {
  21744. return;
  21745. }
  21746. var tags = tagsString.split(" ");
  21747. for (var t in tags) {
  21748. Tags._AddTagTo(obj, tags[t]);
  21749. }
  21750. };
  21751. Tags._AddTagTo = function (obj, tag) {
  21752. tag = tag.trim();
  21753. if (tag === "" || tag === "true" || tag === "false") {
  21754. return;
  21755. }
  21756. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21757. return;
  21758. }
  21759. Tags.EnableFor(obj);
  21760. obj._tags[tag] = true;
  21761. };
  21762. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21763. if (!Tags.HasTags(obj)) {
  21764. return;
  21765. }
  21766. var tags = tagsString.split(" ");
  21767. for (var t in tags) {
  21768. Tags._RemoveTagFrom(obj, tags[t]);
  21769. }
  21770. };
  21771. Tags._RemoveTagFrom = function (obj, tag) {
  21772. delete obj._tags[tag];
  21773. };
  21774. Tags.MatchesQuery = function (obj, tagsQuery) {
  21775. if (tagsQuery === undefined) {
  21776. return true;
  21777. }
  21778. if (tagsQuery === "") {
  21779. return Tags.HasTags(obj);
  21780. }
  21781. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21782. };
  21783. return Tags;
  21784. })();
  21785. BABYLON.Tags = Tags;
  21786. })(BABYLON || (BABYLON = {}));
  21787. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21788. (function (BABYLON) {
  21789. var Internals;
  21790. (function (Internals) {
  21791. var AndOrNotEvaluator = (function () {
  21792. function AndOrNotEvaluator() {
  21793. }
  21794. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21795. if (!query.match(/\([^\(\)]*\)/g)) {
  21796. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21797. }
  21798. else {
  21799. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21800. // remove parenthesis
  21801. r = r.slice(1, r.length - 1);
  21802. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21803. });
  21804. }
  21805. if (query === "true") {
  21806. return true;
  21807. }
  21808. if (query === "false") {
  21809. return false;
  21810. }
  21811. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21812. };
  21813. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21814. evaluateCallback = evaluateCallback || (function (r) {
  21815. return r === "true" ? true : false;
  21816. });
  21817. var result;
  21818. var or = parenthesisContent.split("||");
  21819. for (var i in or) {
  21820. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21821. var and = ori.split("&&");
  21822. if (and.length > 1) {
  21823. for (var j = 0; j < and.length; ++j) {
  21824. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21825. if (andj !== "true" && andj !== "false") {
  21826. if (andj[0] === "!") {
  21827. result = !evaluateCallback(andj.substring(1));
  21828. }
  21829. else {
  21830. result = evaluateCallback(andj);
  21831. }
  21832. }
  21833. else {
  21834. result = andj === "true" ? true : false;
  21835. }
  21836. if (!result) {
  21837. ori = "false";
  21838. break;
  21839. }
  21840. }
  21841. }
  21842. if (result || ori === "true") {
  21843. result = true;
  21844. break;
  21845. }
  21846. // result equals false (or undefined)
  21847. if (ori !== "true" && ori !== "false") {
  21848. if (ori[0] === "!") {
  21849. result = !evaluateCallback(ori.substring(1));
  21850. }
  21851. else {
  21852. result = evaluateCallback(ori);
  21853. }
  21854. }
  21855. else {
  21856. result = ori === "true" ? true : false;
  21857. }
  21858. }
  21859. // the whole parenthesis scope is replaced by 'true' or 'false'
  21860. return result ? "true" : "false";
  21861. };
  21862. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21863. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21864. // remove whitespaces
  21865. r = r.replace(/[\s]/g, function () { return ""; });
  21866. return r.length % 2 ? "!" : "";
  21867. });
  21868. booleanString = booleanString.trim();
  21869. if (booleanString === "!true") {
  21870. booleanString = "false";
  21871. }
  21872. else if (booleanString === "!false") {
  21873. booleanString = "true";
  21874. }
  21875. return booleanString;
  21876. };
  21877. return AndOrNotEvaluator;
  21878. })();
  21879. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21880. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21881. })(BABYLON || (BABYLON = {}));
  21882. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21883. (function (BABYLON) {
  21884. var PostProcessRenderPass = (function () {
  21885. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21886. this._enabled = true;
  21887. this._refCount = 0;
  21888. this._name = name;
  21889. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21890. this.setRenderList(renderList);
  21891. this._renderTexture.onBeforeRender = beforeRender;
  21892. this._renderTexture.onAfterRender = afterRender;
  21893. this._scene = scene;
  21894. this._renderList = renderList;
  21895. }
  21896. // private
  21897. PostProcessRenderPass.prototype._incRefCount = function () {
  21898. if (this._refCount === 0) {
  21899. this._scene.customRenderTargets.push(this._renderTexture);
  21900. }
  21901. return ++this._refCount;
  21902. };
  21903. PostProcessRenderPass.prototype._decRefCount = function () {
  21904. this._refCount--;
  21905. if (this._refCount <= 0) {
  21906. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21907. }
  21908. return this._refCount;
  21909. };
  21910. PostProcessRenderPass.prototype._update = function () {
  21911. this.setRenderList(this._renderList);
  21912. };
  21913. // public
  21914. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21915. this._renderTexture.renderList = renderList;
  21916. };
  21917. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21918. return this._renderTexture;
  21919. };
  21920. return PostProcessRenderPass;
  21921. })();
  21922. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21923. })(BABYLON || (BABYLON = {}));
  21924. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21925. (function (BABYLON) {
  21926. var PostProcessRenderEffect = (function () {
  21927. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21928. this._engine = engine;
  21929. this._name = name;
  21930. this._singleInstance = singleInstance || true;
  21931. this._getPostProcess = getPostProcess;
  21932. this._cameras = [];
  21933. this._indicesForCamera = [];
  21934. this._postProcesses = {};
  21935. this._renderPasses = {};
  21936. this._renderEffectAsPasses = {};
  21937. }
  21938. PostProcessRenderEffect.prototype._update = function () {
  21939. for (var renderPassName in this._renderPasses) {
  21940. this._renderPasses[renderPassName]._update();
  21941. }
  21942. };
  21943. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21944. this._renderPasses[renderPass._name] = renderPass;
  21945. this._linkParameters();
  21946. };
  21947. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21948. delete this._renderPasses[renderPass._name];
  21949. this._linkParameters();
  21950. };
  21951. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21952. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21953. this._linkParameters();
  21954. };
  21955. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21956. for (var renderPassName in this._renderPasses) {
  21957. if (renderPassName === passName) {
  21958. return this._renderPasses[passName];
  21959. }
  21960. }
  21961. };
  21962. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21963. this._renderPasses = {};
  21964. this._linkParameters();
  21965. };
  21966. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21967. var cameraKey;
  21968. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21969. for (var i = 0; i < _cam.length; i++) {
  21970. var camera = _cam[i];
  21971. var cameraName = camera.name;
  21972. if (this._singleInstance) {
  21973. cameraKey = 0;
  21974. }
  21975. else {
  21976. cameraKey = cameraName;
  21977. }
  21978. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21979. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21980. if (!this._indicesForCamera[cameraName]) {
  21981. this._indicesForCamera[cameraName] = [];
  21982. }
  21983. this._indicesForCamera[cameraName].push(index);
  21984. if (this._cameras.indexOf(camera) === -1) {
  21985. this._cameras[cameraName] = camera;
  21986. }
  21987. for (var passName in this._renderPasses) {
  21988. this._renderPasses[passName]._incRefCount();
  21989. }
  21990. }
  21991. this._linkParameters();
  21992. };
  21993. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21994. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21995. for (var i = 0; i < _cam.length; i++) {
  21996. var camera = _cam[i];
  21997. var cameraName = camera.name;
  21998. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21999. var index = this._cameras.indexOf(cameraName);
  22000. this._indicesForCamera.splice(index, 1);
  22001. this._cameras.splice(index, 1);
  22002. for (var passName in this._renderPasses) {
  22003. this._renderPasses[passName]._decRefCount();
  22004. }
  22005. }
  22006. };
  22007. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22008. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22009. for (var i = 0; i < _cam.length; i++) {
  22010. var camera = _cam[i];
  22011. var cameraName = camera.name;
  22012. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22013. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22014. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22015. }
  22016. }
  22017. for (var passName in this._renderPasses) {
  22018. this._renderPasses[passName]._incRefCount();
  22019. }
  22020. }
  22021. };
  22022. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22023. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22024. for (var i = 0; i < _cam.length; i++) {
  22025. var camera = _cam[i];
  22026. var cameraName = camera.Name;
  22027. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22028. for (var passName in this._renderPasses) {
  22029. this._renderPasses[passName]._decRefCount();
  22030. }
  22031. }
  22032. };
  22033. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22034. if (this._singleInstance) {
  22035. return this._postProcesses[0];
  22036. }
  22037. else {
  22038. return this._postProcesses[camera.name];
  22039. }
  22040. };
  22041. PostProcessRenderEffect.prototype._linkParameters = function () {
  22042. var _this = this;
  22043. for (var index in this._postProcesses) {
  22044. if (this.applyParameters) {
  22045. this.applyParameters(this._postProcesses[index]);
  22046. }
  22047. this._postProcesses[index].onBeforeRender = function (effect) {
  22048. _this._linkTextures(effect);
  22049. };
  22050. }
  22051. };
  22052. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22053. for (var renderPassName in this._renderPasses) {
  22054. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22055. }
  22056. for (var renderEffectName in this._renderEffectAsPasses) {
  22057. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22058. }
  22059. };
  22060. return PostProcessRenderEffect;
  22061. })();
  22062. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22063. })(BABYLON || (BABYLON = {}));
  22064. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22065. (function (BABYLON) {
  22066. var PostProcessRenderPipeline = (function () {
  22067. function PostProcessRenderPipeline(engine, name) {
  22068. this._engine = engine;
  22069. this._name = name;
  22070. this._renderEffects = {};
  22071. this._renderEffectsForIsolatedPass = {};
  22072. this._cameras = [];
  22073. }
  22074. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22075. this._renderEffects[renderEffect._name] = renderEffect;
  22076. };
  22077. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22078. var renderEffects = this._renderEffects[renderEffectName];
  22079. if (!renderEffects) {
  22080. return;
  22081. }
  22082. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22083. };
  22084. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22085. var renderEffects = this._renderEffects[renderEffectName];
  22086. if (!renderEffects) {
  22087. return;
  22088. }
  22089. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22090. };
  22091. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22092. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22093. var indicesToDelete = [];
  22094. for (var i = 0; i < _cam.length; i++) {
  22095. var camera = _cam[i];
  22096. var cameraName = camera.name;
  22097. if (this._cameras.indexOf(camera) === -1) {
  22098. this._cameras[cameraName] = camera;
  22099. }
  22100. else if (unique) {
  22101. indicesToDelete.push(i);
  22102. }
  22103. }
  22104. for (var i = 0; i < indicesToDelete.length; i++) {
  22105. cameras.splice(indicesToDelete[i], 1);
  22106. }
  22107. for (var renderEffectName in this._renderEffects) {
  22108. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22109. }
  22110. };
  22111. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22112. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22113. for (var renderEffectName in this._renderEffects) {
  22114. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22115. }
  22116. for (var i = 0; i < _cam.length; i++) {
  22117. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22118. }
  22119. };
  22120. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22121. var _this = this;
  22122. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22123. var pass = null;
  22124. for (var renderEffectName in this._renderEffects) {
  22125. pass = this._renderEffects[renderEffectName].getPass(passName);
  22126. if (pass != null) {
  22127. break;
  22128. }
  22129. }
  22130. if (pass === null) {
  22131. return;
  22132. }
  22133. for (var renderEffectName in this._renderEffects) {
  22134. this._renderEffects[renderEffectName]._disable(_cam);
  22135. }
  22136. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22137. for (var i = 0; i < _cam.length; i++) {
  22138. var camera = _cam[i];
  22139. var cameraName = camera.name;
  22140. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22141. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22142. });
  22143. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22144. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22145. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22146. }
  22147. };
  22148. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22149. var _this = this;
  22150. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22151. for (var i = 0; i < _cam.length; i++) {
  22152. var camera = _cam[i];
  22153. var cameraName = camera.name;
  22154. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22155. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22156. });
  22157. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22158. }
  22159. for (var renderEffectName in this._renderEffects) {
  22160. this._renderEffects[renderEffectName]._enable(_cam);
  22161. }
  22162. };
  22163. PostProcessRenderPipeline.prototype._update = function () {
  22164. for (var renderEffectName in this._renderEffects) {
  22165. this._renderEffects[renderEffectName]._update();
  22166. }
  22167. for (var i = 0; i < this._cameras.length; i++) {
  22168. var cameraName = this._cameras[i].name;
  22169. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22170. this._renderEffectsForIsolatedPass[cameraName]._update();
  22171. }
  22172. }
  22173. };
  22174. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22175. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22176. return PostProcessRenderPipeline;
  22177. })();
  22178. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22179. })(BABYLON || (BABYLON = {}));
  22180. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22181. (function (BABYLON) {
  22182. var PostProcessRenderPipelineManager = (function () {
  22183. function PostProcessRenderPipelineManager() {
  22184. this._renderPipelines = {};
  22185. }
  22186. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22187. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22188. };
  22189. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22190. var renderPipeline = this._renderPipelines[renderPipelineName];
  22191. if (!renderPipeline) {
  22192. return;
  22193. }
  22194. renderPipeline._attachCameras(cameras, unique);
  22195. };
  22196. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22197. var renderPipeline = this._renderPipelines[renderPipelineName];
  22198. if (!renderPipeline) {
  22199. return;
  22200. }
  22201. renderPipeline._detachCameras(cameras);
  22202. };
  22203. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22204. var renderPipeline = this._renderPipelines[renderPipelineName];
  22205. if (!renderPipeline) {
  22206. return;
  22207. }
  22208. renderPipeline._enableEffect(renderEffectName, cameras);
  22209. };
  22210. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22211. var renderPipeline = this._renderPipelines[renderPipelineName];
  22212. if (!renderPipeline) {
  22213. return;
  22214. }
  22215. renderPipeline._disableEffect(renderEffectName, cameras);
  22216. };
  22217. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22218. var renderPipeline = this._renderPipelines[renderPipelineName];
  22219. if (!renderPipeline) {
  22220. return;
  22221. }
  22222. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22223. };
  22224. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22225. var renderPipeline = this._renderPipelines[renderPipelineName];
  22226. if (!renderPipeline) {
  22227. return;
  22228. }
  22229. renderPipeline._disableDisplayOnlyPass(cameras);
  22230. };
  22231. PostProcessRenderPipelineManager.prototype.update = function () {
  22232. for (var renderPipelineName in this._renderPipelines) {
  22233. this._renderPipelines[renderPipelineName]._update();
  22234. }
  22235. };
  22236. return PostProcessRenderPipelineManager;
  22237. })();
  22238. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22239. })(BABYLON || (BABYLON = {}));
  22240. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22241. var BABYLON;
  22242. (function (BABYLON) {
  22243. var DisplayPassPostProcess = (function (_super) {
  22244. __extends(DisplayPassPostProcess, _super);
  22245. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22246. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22247. }
  22248. return DisplayPassPostProcess;
  22249. })(BABYLON.PostProcess);
  22250. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22251. })(BABYLON || (BABYLON = {}));
  22252. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22253. (function (BABYLON) {
  22254. var BoundingBoxRenderer = (function () {
  22255. function BoundingBoxRenderer(scene) {
  22256. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22257. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22258. this.showBackLines = true;
  22259. this.renderList = new BABYLON.SmartArray(32);
  22260. this._scene = scene;
  22261. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22262. attributes: ["position"],
  22263. uniforms: ["worldViewProjection", "color"]
  22264. });
  22265. var engine = this._scene.getEngine();
  22266. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22267. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22268. 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]);
  22269. }
  22270. BoundingBoxRenderer.prototype.reset = function () {
  22271. this.renderList.reset();
  22272. };
  22273. BoundingBoxRenderer.prototype.render = function () {
  22274. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22275. return;
  22276. }
  22277. var engine = this._scene.getEngine();
  22278. engine.setDepthWrite(false);
  22279. this._colorShader._preBind();
  22280. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22281. var boundingBox = this.renderList.data[boundingBoxIndex];
  22282. var min = boundingBox.minimum;
  22283. var max = boundingBox.maximum;
  22284. var diff = max.subtract(min);
  22285. var median = min.add(diff.scale(0.5));
  22286. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22287. // VBOs
  22288. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22289. if (this.showBackLines) {
  22290. // Back
  22291. engine.setDepthFunctionToGreaterOrEqual();
  22292. this._scene.resetCachedMaterial();
  22293. this._colorShader.setColor4("color", this.backColor.toColor4());
  22294. this._colorShader.bind(worldMatrix);
  22295. // Draw order
  22296. engine.draw(false, 0, 24);
  22297. }
  22298. // Front
  22299. engine.setDepthFunctionToLess();
  22300. this._scene.resetCachedMaterial();
  22301. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22302. this._colorShader.bind(worldMatrix);
  22303. // Draw order
  22304. engine.draw(false, 0, 24);
  22305. }
  22306. this._colorShader.unbind();
  22307. engine.setDepthFunctionToLessOrEqual();
  22308. engine.setDepthWrite(true);
  22309. };
  22310. BoundingBoxRenderer.prototype.dispose = function () {
  22311. this._colorShader.dispose();
  22312. this._vb.dispose();
  22313. this._scene.getEngine()._releaseBuffer(this._ib);
  22314. };
  22315. return BoundingBoxRenderer;
  22316. })();
  22317. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22318. })(BABYLON || (BABYLON = {}));
  22319. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22320. (function (BABYLON) {
  22321. var Internals;
  22322. (function (Internals) {
  22323. /*
  22324. * Based on jsTGALoader - Javascript loader for TGA file
  22325. * By Vincent Thibault
  22326. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22327. */
  22328. var TGATools = (function () {
  22329. function TGATools() {
  22330. }
  22331. TGATools.GetTGAHeader = function (data) {
  22332. var offset = 0;
  22333. var header = {
  22334. id_length: data[offset++],
  22335. colormap_type: data[offset++],
  22336. image_type: data[offset++],
  22337. colormap_index: data[offset++] | data[offset++] << 8,
  22338. colormap_length: data[offset++] | data[offset++] << 8,
  22339. colormap_size: data[offset++],
  22340. origin: [
  22341. data[offset++] | data[offset++] << 8,
  22342. data[offset++] | data[offset++] << 8
  22343. ],
  22344. width: data[offset++] | data[offset++] << 8,
  22345. height: data[offset++] | data[offset++] << 8,
  22346. pixel_size: data[offset++],
  22347. flags: data[offset++]
  22348. };
  22349. return header;
  22350. };
  22351. TGATools.UploadContent = function (gl, data) {
  22352. // Not enough data to contain header ?
  22353. if (data.length < 19) {
  22354. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22355. return;
  22356. }
  22357. // Read Header
  22358. var offset = 18;
  22359. var header = TGATools.GetTGAHeader(data);
  22360. // Assume it's a valid Targa file.
  22361. if (header.id_length + offset > data.length) {
  22362. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22363. return;
  22364. }
  22365. // Skip not needed data
  22366. offset += header.id_length;
  22367. var use_rle = false;
  22368. var use_pal = false;
  22369. var use_rgb = false;
  22370. var use_grey = false;
  22371. switch (header.image_type) {
  22372. case TGATools._TYPE_RLE_INDEXED:
  22373. use_rle = true;
  22374. case TGATools._TYPE_INDEXED:
  22375. use_pal = true;
  22376. break;
  22377. case TGATools._TYPE_RLE_RGB:
  22378. use_rle = true;
  22379. case TGATools._TYPE_RGB:
  22380. use_rgb = true;
  22381. break;
  22382. case TGATools._TYPE_RLE_GREY:
  22383. use_rle = true;
  22384. case TGATools._TYPE_GREY:
  22385. use_grey = true;
  22386. break;
  22387. }
  22388. var pixel_data;
  22389. var numAlphaBits = header.flags & 0xf;
  22390. var pixel_size = header.pixel_size >> 3;
  22391. var pixel_total = header.width * header.height * pixel_size;
  22392. // Read palettes
  22393. var palettes;
  22394. if (use_pal) {
  22395. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22396. }
  22397. // Read LRE
  22398. if (use_rle) {
  22399. pixel_data = new Uint8Array(pixel_total);
  22400. var c, count, i;
  22401. var localOffset = 0;
  22402. var pixels = new Uint8Array(pixel_size);
  22403. while (offset < pixel_total && localOffset < pixel_total) {
  22404. c = data[offset++];
  22405. count = (c & 0x7f) + 1;
  22406. // RLE pixels
  22407. if (c & 0x80) {
  22408. for (i = 0; i < pixel_size; ++i) {
  22409. pixels[i] = data[offset++];
  22410. }
  22411. for (i = 0; i < count; ++i) {
  22412. pixel_data.set(pixels, localOffset + i * pixel_size);
  22413. }
  22414. localOffset += pixel_size * count;
  22415. }
  22416. else {
  22417. count *= pixel_size;
  22418. for (i = 0; i < count; ++i) {
  22419. pixel_data[localOffset + i] = data[offset++];
  22420. }
  22421. localOffset += count;
  22422. }
  22423. }
  22424. }
  22425. else {
  22426. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22427. }
  22428. // Load to texture
  22429. var x_start, y_start, x_step, y_step, y_end, x_end;
  22430. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22431. default:
  22432. case TGATools._ORIGIN_UL:
  22433. x_start = 0;
  22434. x_step = 1;
  22435. x_end = header.width;
  22436. y_start = 0;
  22437. y_step = 1;
  22438. y_end = header.height;
  22439. break;
  22440. case TGATools._ORIGIN_BL:
  22441. x_start = 0;
  22442. x_step = 1;
  22443. x_end = header.width;
  22444. y_start = header.height - 1;
  22445. y_step = -1;
  22446. y_end = -1;
  22447. break;
  22448. case TGATools._ORIGIN_UR:
  22449. x_start = header.width - 1;
  22450. x_step = -1;
  22451. x_end = -1;
  22452. y_start = 0;
  22453. y_step = 1;
  22454. y_end = header.height;
  22455. break;
  22456. case TGATools._ORIGIN_BR:
  22457. x_start = header.width - 1;
  22458. x_step = -1;
  22459. x_end = -1;
  22460. y_start = header.height - 1;
  22461. y_step = -1;
  22462. y_end = -1;
  22463. break;
  22464. }
  22465. // Load the specify method
  22466. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22467. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22468. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22469. };
  22470. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22471. var image = pixel_data, colormap = palettes;
  22472. var width = header.width, height = header.height;
  22473. var color, i = 0, x, y;
  22474. var imageData = new Uint8Array(width * height * 4);
  22475. for (y = y_start; y !== y_end; y += y_step) {
  22476. for (x = x_start; x !== x_end; x += x_step, i++) {
  22477. color = image[i];
  22478. imageData[(x + width * y) * 4 + 3] = 255;
  22479. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22480. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22481. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22482. }
  22483. }
  22484. return imageData;
  22485. };
  22486. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22487. var image = pixel_data;
  22488. var width = header.width, height = header.height;
  22489. var color, i = 0, x, y;
  22490. var imageData = new Uint8Array(width * height * 4);
  22491. for (y = y_start; y !== y_end; y += y_step) {
  22492. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22493. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22494. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22495. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22496. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22497. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22498. }
  22499. }
  22500. return imageData;
  22501. };
  22502. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22503. var image = pixel_data;
  22504. var width = header.width, height = header.height;
  22505. var i = 0, x, y;
  22506. var imageData = new Uint8Array(width * height * 4);
  22507. for (y = y_start; y !== y_end; y += y_step) {
  22508. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22509. imageData[(x + width * y) * 4 + 3] = 255;
  22510. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22511. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22512. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22513. }
  22514. }
  22515. return imageData;
  22516. };
  22517. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22518. var image = pixel_data;
  22519. var width = header.width, height = header.height;
  22520. var i = 0, x, y;
  22521. var imageData = new Uint8Array(width * height * 4);
  22522. for (y = y_start; y !== y_end; y += y_step) {
  22523. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22524. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22525. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22526. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22527. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22528. }
  22529. }
  22530. return imageData;
  22531. };
  22532. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22533. var image = pixel_data;
  22534. var width = header.width, height = header.height;
  22535. var color, i = 0, x, y;
  22536. var imageData = new Uint8Array(width * height * 4);
  22537. for (y = y_start; y !== y_end; y += y_step) {
  22538. for (x = x_start; x !== x_end; x += x_step, i++) {
  22539. color = image[i];
  22540. imageData[(x + width * y) * 4 + 0] = color;
  22541. imageData[(x + width * y) * 4 + 1] = color;
  22542. imageData[(x + width * y) * 4 + 2] = color;
  22543. imageData[(x + width * y) * 4 + 3] = 255;
  22544. }
  22545. }
  22546. return imageData;
  22547. };
  22548. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22549. var image = pixel_data;
  22550. var width = header.width, height = header.height;
  22551. var i = 0, x, y;
  22552. var imageData = new Uint8Array(width * height * 4);
  22553. for (y = y_start; y !== y_end; y += y_step) {
  22554. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22555. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22556. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22557. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22558. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22559. }
  22560. }
  22561. return imageData;
  22562. };
  22563. TGATools._TYPE_NO_DATA = 0;
  22564. TGATools._TYPE_INDEXED = 1;
  22565. TGATools._TYPE_RGB = 2;
  22566. TGATools._TYPE_GREY = 3;
  22567. TGATools._TYPE_RLE_INDEXED = 9;
  22568. TGATools._TYPE_RLE_RGB = 10;
  22569. TGATools._TYPE_RLE_GREY = 11;
  22570. TGATools._ORIGIN_MASK = 0x30;
  22571. TGATools._ORIGIN_SHIFT = 0x04;
  22572. TGATools._ORIGIN_BL = 0x00;
  22573. TGATools._ORIGIN_BR = 0x01;
  22574. TGATools._ORIGIN_UL = 0x02;
  22575. TGATools._ORIGIN_UR = 0x03;
  22576. return TGATools;
  22577. })();
  22578. Internals.TGATools = TGATools;
  22579. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22580. })(BABYLON || (BABYLON = {}));
  22581. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22582. (function (BABYLON) {
  22583. var Internals;
  22584. (function (Internals) {
  22585. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22586. // All values and structures referenced from:
  22587. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22588. var DDS_MAGIC = 0x20534444;
  22589. 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;
  22590. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22591. 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;
  22592. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22593. function FourCCToInt32(value) {
  22594. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22595. }
  22596. function Int32ToFourCC(value) {
  22597. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22598. }
  22599. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22600. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22601. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22602. var headerLengthInt = 31; // The header length in 32 bit ints
  22603. // Offsets into the header array
  22604. var off_magic = 0;
  22605. var off_size = 1;
  22606. var off_flags = 2;
  22607. var off_height = 3;
  22608. var off_width = 4;
  22609. var off_mipmapCount = 7;
  22610. var off_pfFlags = 20;
  22611. var off_pfFourCC = 21;
  22612. var off_RGBbpp = 22;
  22613. var off_RMask = 23;
  22614. var off_GMask = 24;
  22615. var off_BMask = 25;
  22616. var off_AMask = 26;
  22617. var off_caps1 = 27;
  22618. var off_caps2 = 28;
  22619. ;
  22620. var DDSTools = (function () {
  22621. function DDSTools() {
  22622. }
  22623. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22624. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22625. var mipmapCount = 1;
  22626. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22627. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22628. }
  22629. return {
  22630. width: header[off_width],
  22631. height: header[off_height],
  22632. mipmapCount: mipmapCount,
  22633. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22634. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22635. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22636. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22637. };
  22638. };
  22639. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22640. var byteArray = new Uint8Array(dataLength);
  22641. var srcData = new Uint8Array(arrayBuffer);
  22642. var index = 0;
  22643. for (var y = height - 1; y >= 0; y--) {
  22644. for (var x = 0; x < width; x++) {
  22645. var srcPos = dataOffset + (x + y * width) * 4;
  22646. byteArray[index + 2] = srcData[srcPos];
  22647. byteArray[index + 1] = srcData[srcPos + 1];
  22648. byteArray[index] = srcData[srcPos + 2];
  22649. byteArray[index + 3] = srcData[srcPos + 3];
  22650. index += 4;
  22651. }
  22652. }
  22653. return byteArray;
  22654. };
  22655. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22656. var byteArray = new Uint8Array(dataLength);
  22657. var srcData = new Uint8Array(arrayBuffer);
  22658. var index = 0;
  22659. for (var y = height - 1; y >= 0; y--) {
  22660. for (var x = 0; x < width; x++) {
  22661. var srcPos = dataOffset + (x + y * width) * 3;
  22662. byteArray[index + 2] = srcData[srcPos];
  22663. byteArray[index + 1] = srcData[srcPos + 1];
  22664. byteArray[index] = srcData[srcPos + 2];
  22665. index += 3;
  22666. }
  22667. }
  22668. return byteArray;
  22669. };
  22670. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22671. var byteArray = new Uint8Array(dataLength);
  22672. var srcData = new Uint8Array(arrayBuffer);
  22673. var index = 0;
  22674. for (var y = height - 1; y >= 0; y--) {
  22675. for (var x = 0; x < width; x++) {
  22676. var srcPos = dataOffset + (x + y * width);
  22677. byteArray[index] = srcData[srcPos];
  22678. index++;
  22679. }
  22680. }
  22681. return byteArray;
  22682. };
  22683. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22684. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22685. if (header[off_magic] != DDS_MAGIC) {
  22686. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22687. return;
  22688. }
  22689. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22690. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22691. return;
  22692. }
  22693. if (info.isFourCC) {
  22694. fourCC = header[off_pfFourCC];
  22695. switch (fourCC) {
  22696. case FOURCC_DXT1:
  22697. blockBytes = 8;
  22698. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22699. break;
  22700. case FOURCC_DXT3:
  22701. blockBytes = 16;
  22702. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22703. break;
  22704. case FOURCC_DXT5:
  22705. blockBytes = 16;
  22706. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22707. break;
  22708. default:
  22709. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22710. return;
  22711. }
  22712. }
  22713. mipmapCount = 1;
  22714. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22715. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22716. }
  22717. var bpp = header[off_RGBbpp];
  22718. for (var face = 0; face < faces; face++) {
  22719. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22720. width = header[off_width];
  22721. height = header[off_height];
  22722. dataOffset = header[off_size] + 4;
  22723. for (i = 0; i < mipmapCount; ++i) {
  22724. if (info.isRGB) {
  22725. if (bpp == 24) {
  22726. dataLength = width * height * 3;
  22727. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22728. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22729. }
  22730. else {
  22731. dataLength = width * height * 4;
  22732. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22733. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22734. }
  22735. }
  22736. else if (info.isLuminance) {
  22737. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22738. var unpaddedRowSize = width;
  22739. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22740. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22741. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22742. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22743. }
  22744. else {
  22745. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22746. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22747. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22748. }
  22749. dataOffset += dataLength;
  22750. width *= 0.5;
  22751. height *= 0.5;
  22752. width = Math.max(1.0, width);
  22753. height = Math.max(1.0, height);
  22754. }
  22755. }
  22756. };
  22757. return DDSTools;
  22758. })();
  22759. Internals.DDSTools = DDSTools;
  22760. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22761. })(BABYLON || (BABYLON = {}));
  22762. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22763. (function (BABYLON) {
  22764. var SmartArray = (function () {
  22765. function SmartArray(capacity) {
  22766. this.length = 0;
  22767. this._duplicateId = 0;
  22768. this.data = new Array(capacity);
  22769. this._id = SmartArray._GlobalId++;
  22770. }
  22771. SmartArray.prototype.push = function (value) {
  22772. this.data[this.length++] = value;
  22773. if (this.length > this.data.length) {
  22774. this.data.length *= 2;
  22775. }
  22776. if (!value.__smartArrayFlags) {
  22777. value.__smartArrayFlags = {};
  22778. }
  22779. value.__smartArrayFlags[this._id] = this._duplicateId;
  22780. };
  22781. SmartArray.prototype.pushNoDuplicate = function (value) {
  22782. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22783. return;
  22784. }
  22785. this.push(value);
  22786. };
  22787. SmartArray.prototype.sort = function (compareFn) {
  22788. this.data.sort(compareFn);
  22789. };
  22790. SmartArray.prototype.reset = function () {
  22791. this.length = 0;
  22792. this._duplicateId++;
  22793. };
  22794. SmartArray.prototype.concat = function (array) {
  22795. if (array.length === 0) {
  22796. return;
  22797. }
  22798. if (this.length + array.length > this.data.length) {
  22799. this.data.length = (this.length + array.length) * 2;
  22800. }
  22801. for (var index = 0; index < array.length; index++) {
  22802. this.data[this.length++] = (array.data || array)[index];
  22803. }
  22804. };
  22805. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22806. if (array.length === 0) {
  22807. return;
  22808. }
  22809. if (this.length + array.length > this.data.length) {
  22810. this.data.length = (this.length + array.length) * 2;
  22811. }
  22812. for (var index = 0; index < array.length; index++) {
  22813. var item = (array.data || array)[index];
  22814. this.pushNoDuplicate(item);
  22815. }
  22816. };
  22817. SmartArray.prototype.indexOf = function (value) {
  22818. var position = this.data.indexOf(value);
  22819. if (position >= this.length) {
  22820. return -1;
  22821. }
  22822. return position;
  22823. };
  22824. // Statics
  22825. SmartArray._GlobalId = 0;
  22826. return SmartArray;
  22827. })();
  22828. BABYLON.SmartArray = SmartArray;
  22829. })(BABYLON || (BABYLON = {}));
  22830. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22831. (function (BABYLON) {
  22832. var CannonJSPlugin = (function () {
  22833. function CannonJSPlugin() {
  22834. this._registeredMeshes = [];
  22835. this._physicsMaterials = [];
  22836. this.updateBodyPosition = function (mesh) {
  22837. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22838. var registeredMesh = this._registeredMeshes[index];
  22839. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22840. var body = registeredMesh.body;
  22841. var center = mesh.getBoundingInfo().boundingBox.center;
  22842. body.position.set(center.x, center.z, center.y);
  22843. body.quaternion.x = mesh.rotationQuaternion.x;
  22844. body.quaternion.z = mesh.rotationQuaternion.y;
  22845. body.quaternion.y = mesh.rotationQuaternion.z;
  22846. body.quaternion.w = -mesh.rotationQuaternion.w;
  22847. return;
  22848. }
  22849. }
  22850. };
  22851. }
  22852. CannonJSPlugin.prototype.initialize = function (iterations) {
  22853. if (iterations === void 0) { iterations = 10; }
  22854. this._world = new CANNON.World();
  22855. this._world.broadphase = new CANNON.NaiveBroadphase();
  22856. this._world.solver.iterations = iterations;
  22857. };
  22858. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22859. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22860. };
  22861. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22862. this._world.step(delta);
  22863. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22864. var registeredMesh = this._registeredMeshes[index];
  22865. if (registeredMesh.isChild) {
  22866. continue;
  22867. }
  22868. // Body position
  22869. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22870. var deltaPos = registeredMesh.delta;
  22871. if (deltaPos) {
  22872. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22873. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22874. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22875. }
  22876. else {
  22877. registeredMesh.mesh.position.x = bodyX;
  22878. registeredMesh.mesh.position.y = bodyZ;
  22879. registeredMesh.mesh.position.z = bodyY;
  22880. }
  22881. if (!registeredMesh.mesh.rotationQuaternion) {
  22882. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22883. }
  22884. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22885. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22886. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22887. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22888. }
  22889. };
  22890. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22891. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22892. };
  22893. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22894. this.unregisterMesh(mesh);
  22895. mesh.computeWorldMatrix(true);
  22896. switch (impostor) {
  22897. case BABYLON.PhysicsEngine.SphereImpostor:
  22898. var bbox = mesh.getBoundingInfo().boundingBox;
  22899. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22900. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22901. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22902. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22903. case BABYLON.PhysicsEngine.BoxImpostor:
  22904. bbox = mesh.getBoundingInfo().boundingBox;
  22905. var min = bbox.minimumWorld;
  22906. var max = bbox.maximumWorld;
  22907. var box = max.subtract(min).scale(0.5);
  22908. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22909. case BABYLON.PhysicsEngine.PlaneImpostor:
  22910. return this._createPlane(mesh, options);
  22911. case BABYLON.PhysicsEngine.MeshImpostor:
  22912. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22913. var rawFaces = mesh.getIndices();
  22914. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22915. }
  22916. return null;
  22917. };
  22918. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22919. var shape = new CANNON.Sphere(radius);
  22920. if (!options) {
  22921. return shape;
  22922. }
  22923. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22924. };
  22925. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22926. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22927. if (!options) {
  22928. return shape;
  22929. }
  22930. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22931. };
  22932. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22933. var shape = new CANNON.Plane();
  22934. if (!options) {
  22935. return shape;
  22936. }
  22937. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22938. };
  22939. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22940. var verts = [], faces = [];
  22941. mesh.computeWorldMatrix(true);
  22942. for (var i = 0; i < rawVerts.length; i += 3) {
  22943. var transformed = BABYLON.Vector3.Zero();
  22944. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22945. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22946. }
  22947. for (var j = 0; j < rawFaces.length; j += 3) {
  22948. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22949. }
  22950. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22951. if (!options) {
  22952. return shape;
  22953. }
  22954. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22955. };
  22956. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22957. var index;
  22958. var mat;
  22959. for (index = 0; index < this._physicsMaterials.length; index++) {
  22960. mat = this._physicsMaterials[index];
  22961. if (mat.friction === friction && mat.restitution === restitution) {
  22962. return mat;
  22963. }
  22964. }
  22965. var currentMat = new CANNON.Material();
  22966. currentMat.friction = friction;
  22967. currentMat.restitution = restitution;
  22968. this._physicsMaterials.push(currentMat);
  22969. for (index = 0; index < this._physicsMaterials.length; index++) {
  22970. mat = this._physicsMaterials[index];
  22971. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22972. contactMaterial.contactEquationStiffness = 1e10;
  22973. contactMaterial.contactEquationRegularizationTime = 10;
  22974. this._world.addContactMaterial(contactMaterial);
  22975. }
  22976. return currentMat;
  22977. };
  22978. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22979. var initialRotation = null;
  22980. if (mesh.rotationQuaternion) {
  22981. initialRotation = mesh.rotationQuaternion.clone();
  22982. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22983. }
  22984. // The delta between the mesh position and the mesh bounding box center
  22985. var bbox = mesh.getBoundingInfo().boundingBox;
  22986. var deltaPosition = mesh.position.subtract(bbox.center);
  22987. var material = this._addMaterial(friction, restitution);
  22988. var body = new CANNON.RigidBody(mass, shape, material);
  22989. if (initialRotation) {
  22990. body.quaternion.x = initialRotation.x;
  22991. body.quaternion.z = initialRotation.y;
  22992. body.quaternion.y = initialRotation.z;
  22993. body.quaternion.w = -initialRotation.w;
  22994. }
  22995. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22996. this._world.add(body);
  22997. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22998. return body;
  22999. };
  23000. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23001. var compoundShape = new CANNON.Compound();
  23002. for (var index = 0; index < parts.length; index++) {
  23003. var mesh = parts[index].mesh;
  23004. var shape = this.registerMesh(mesh, parts[index].impostor);
  23005. if (index == 0) {
  23006. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23007. }
  23008. else {
  23009. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23010. }
  23011. }
  23012. var initialMesh = parts[0].mesh;
  23013. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23014. body.parts = parts;
  23015. return body;
  23016. };
  23017. CannonJSPlugin.prototype._unbindBody = function (body) {
  23018. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23019. var registeredMesh = this._registeredMeshes[index];
  23020. if (registeredMesh.body === body) {
  23021. registeredMesh.body = null;
  23022. registeredMesh.delta = 0;
  23023. }
  23024. }
  23025. };
  23026. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23027. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23028. var registeredMesh = this._registeredMeshes[index];
  23029. if (registeredMesh.mesh === mesh) {
  23030. // Remove body
  23031. if (registeredMesh.body) {
  23032. this._world.remove(registeredMesh.body);
  23033. this._unbindBody(registeredMesh.body);
  23034. }
  23035. this._registeredMeshes.splice(index, 1);
  23036. return;
  23037. }
  23038. }
  23039. };
  23040. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23041. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23042. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23043. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23044. var registeredMesh = this._registeredMeshes[index];
  23045. if (registeredMesh.mesh === mesh) {
  23046. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23047. return;
  23048. }
  23049. }
  23050. };
  23051. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23052. var body1 = null, body2 = null;
  23053. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23054. var registeredMesh = this._registeredMeshes[index];
  23055. if (registeredMesh.mesh === mesh1) {
  23056. body1 = registeredMesh.body;
  23057. }
  23058. else if (registeredMesh.mesh === mesh2) {
  23059. body2 = registeredMesh.body;
  23060. }
  23061. }
  23062. if (!body1 || !body2) {
  23063. return false;
  23064. }
  23065. 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));
  23066. this._world.addConstraint(constraint);
  23067. return true;
  23068. };
  23069. CannonJSPlugin.prototype.dispose = function () {
  23070. while (this._registeredMeshes.length) {
  23071. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23072. }
  23073. };
  23074. CannonJSPlugin.prototype.isSupported = function () {
  23075. return window.CANNON !== undefined;
  23076. };
  23077. return CannonJSPlugin;
  23078. })();
  23079. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23080. })(BABYLON || (BABYLON = {}));
  23081. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23082. var BABYLON;
  23083. (function (BABYLON) {
  23084. var Condition = (function () {
  23085. function Condition(actionManager) {
  23086. this._actionManager = actionManager;
  23087. }
  23088. Condition.prototype.isValid = function () {
  23089. return true;
  23090. };
  23091. Condition.prototype._getProperty = function (propertyPath) {
  23092. return this._actionManager._getProperty(propertyPath);
  23093. };
  23094. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23095. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23096. };
  23097. return Condition;
  23098. })();
  23099. BABYLON.Condition = Condition;
  23100. var ValueCondition = (function (_super) {
  23101. __extends(ValueCondition, _super);
  23102. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23103. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23104. _super.call(this, actionManager);
  23105. this.propertyPath = propertyPath;
  23106. this.value = value;
  23107. this.operator = operator;
  23108. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23109. this._property = this._getProperty(this.propertyPath);
  23110. }
  23111. Object.defineProperty(ValueCondition, "IsEqual", {
  23112. get: function () {
  23113. return ValueCondition._IsEqual;
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. Object.defineProperty(ValueCondition, "IsDifferent", {
  23119. get: function () {
  23120. return ValueCondition._IsDifferent;
  23121. },
  23122. enumerable: true,
  23123. configurable: true
  23124. });
  23125. Object.defineProperty(ValueCondition, "IsGreater", {
  23126. get: function () {
  23127. return ValueCondition._IsGreater;
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. Object.defineProperty(ValueCondition, "IsLesser", {
  23133. get: function () {
  23134. return ValueCondition._IsLesser;
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. // Methods
  23140. ValueCondition.prototype.isValid = function () {
  23141. switch (this.operator) {
  23142. case ValueCondition.IsGreater:
  23143. return this._target[this._property] > this.value;
  23144. case ValueCondition.IsLesser:
  23145. return this._target[this._property] < this.value;
  23146. case ValueCondition.IsEqual:
  23147. case ValueCondition.IsDifferent:
  23148. var check;
  23149. if (this.value.equals) {
  23150. check = this.value.equals(this._target[this._property]);
  23151. }
  23152. else {
  23153. check = this.value === this._target[this._property];
  23154. }
  23155. return this.operator === ValueCondition.IsEqual ? check : !check;
  23156. }
  23157. return false;
  23158. };
  23159. // Statics
  23160. ValueCondition._IsEqual = 0;
  23161. ValueCondition._IsDifferent = 1;
  23162. ValueCondition._IsGreater = 2;
  23163. ValueCondition._IsLesser = 3;
  23164. return ValueCondition;
  23165. })(Condition);
  23166. BABYLON.ValueCondition = ValueCondition;
  23167. var PredicateCondition = (function (_super) {
  23168. __extends(PredicateCondition, _super);
  23169. function PredicateCondition(actionManager, predicate) {
  23170. _super.call(this, actionManager);
  23171. this.predicate = predicate;
  23172. }
  23173. PredicateCondition.prototype.isValid = function () {
  23174. return this.predicate();
  23175. };
  23176. return PredicateCondition;
  23177. })(Condition);
  23178. BABYLON.PredicateCondition = PredicateCondition;
  23179. var StateCondition = (function (_super) {
  23180. __extends(StateCondition, _super);
  23181. function StateCondition(actionManager, target, value) {
  23182. _super.call(this, actionManager);
  23183. this.value = value;
  23184. this._target = target;
  23185. }
  23186. // Methods
  23187. StateCondition.prototype.isValid = function () {
  23188. return this._target.state === this.value;
  23189. };
  23190. return StateCondition;
  23191. })(Condition);
  23192. BABYLON.StateCondition = StateCondition;
  23193. })(BABYLON || (BABYLON = {}));
  23194. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23195. (function (BABYLON) {
  23196. var Action = (function () {
  23197. function Action(triggerOptions, condition) {
  23198. this.triggerOptions = triggerOptions;
  23199. if (triggerOptions.parameter) {
  23200. this.trigger = triggerOptions.trigger;
  23201. this._triggerParameter = triggerOptions.parameter;
  23202. }
  23203. else {
  23204. this.trigger = triggerOptions;
  23205. }
  23206. this._nextActiveAction = this;
  23207. this._condition = condition;
  23208. }
  23209. // Methods
  23210. Action.prototype._prepare = function () {
  23211. };
  23212. Action.prototype.getTriggerParameter = function () {
  23213. return this._triggerParameter;
  23214. };
  23215. Action.prototype._executeCurrent = function (evt) {
  23216. if (this._condition) {
  23217. var currentRenderId = this._actionManager.getScene().getRenderId();
  23218. // We cache the current evaluation for the current frame
  23219. if (this._condition._evaluationId === currentRenderId) {
  23220. if (!this._condition._currentResult) {
  23221. return;
  23222. }
  23223. }
  23224. else {
  23225. this._condition._evaluationId = currentRenderId;
  23226. if (!this._condition.isValid()) {
  23227. this._condition._currentResult = false;
  23228. return;
  23229. }
  23230. this._condition._currentResult = true;
  23231. }
  23232. }
  23233. this._nextActiveAction.execute(evt);
  23234. if (this._nextActiveAction._child) {
  23235. if (!this._nextActiveAction._child._actionManager) {
  23236. this._nextActiveAction._child._actionManager = this._actionManager;
  23237. }
  23238. this._nextActiveAction = this._nextActiveAction._child;
  23239. }
  23240. else {
  23241. this._nextActiveAction = this;
  23242. }
  23243. };
  23244. Action.prototype.execute = function (evt) {
  23245. };
  23246. Action.prototype.then = function (action) {
  23247. this._child = action;
  23248. action._actionManager = this._actionManager;
  23249. action._prepare();
  23250. return action;
  23251. };
  23252. Action.prototype._getProperty = function (propertyPath) {
  23253. return this._actionManager._getProperty(propertyPath);
  23254. };
  23255. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23256. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23257. };
  23258. return Action;
  23259. })();
  23260. BABYLON.Action = Action;
  23261. })(BABYLON || (BABYLON = {}));
  23262. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23263. (function (BABYLON) {
  23264. /**
  23265. * ActionEvent is the event beint sent when an action is triggered.
  23266. */
  23267. var ActionEvent = (function () {
  23268. /**
  23269. * @constructor
  23270. * @param source The mesh that triggered the action.
  23271. * @param pointerX the X mouse cursor position at the time of the event
  23272. * @param pointerY the Y mouse cursor position at the time of the event
  23273. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23274. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23275. */
  23276. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23277. this.source = source;
  23278. this.pointerX = pointerX;
  23279. this.pointerY = pointerY;
  23280. this.meshUnderPointer = meshUnderPointer;
  23281. this.sourceEvent = sourceEvent;
  23282. }
  23283. /**
  23284. * Helper function to auto-create an ActionEvent from a source mesh.
  23285. * @param source the source mesh that triggered the event
  23286. * @param evt {Event} The original (browser) event
  23287. */
  23288. ActionEvent.CreateNew = function (source, evt) {
  23289. var scene = source.getScene();
  23290. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23291. };
  23292. /**
  23293. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23294. * @param scene the scene where the event occurred
  23295. * @param evt {Event} The original (browser) event
  23296. */
  23297. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23298. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23299. };
  23300. return ActionEvent;
  23301. })();
  23302. BABYLON.ActionEvent = ActionEvent;
  23303. /**
  23304. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23305. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23306. */
  23307. var ActionManager = (function () {
  23308. function ActionManager(scene) {
  23309. // Members
  23310. this.actions = new Array();
  23311. this._scene = scene;
  23312. scene._actionManagers.push(this);
  23313. }
  23314. Object.defineProperty(ActionManager, "NothingTrigger", {
  23315. get: function () {
  23316. return ActionManager._NothingTrigger;
  23317. },
  23318. enumerable: true,
  23319. configurable: true
  23320. });
  23321. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23322. get: function () {
  23323. return ActionManager._OnPickTrigger;
  23324. },
  23325. enumerable: true,
  23326. configurable: true
  23327. });
  23328. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23329. get: function () {
  23330. return ActionManager._OnLeftPickTrigger;
  23331. },
  23332. enumerable: true,
  23333. configurable: true
  23334. });
  23335. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23336. get: function () {
  23337. return ActionManager._OnRightPickTrigger;
  23338. },
  23339. enumerable: true,
  23340. configurable: true
  23341. });
  23342. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23343. get: function () {
  23344. return ActionManager._OnCenterPickTrigger;
  23345. },
  23346. enumerable: true,
  23347. configurable: true
  23348. });
  23349. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23350. get: function () {
  23351. return ActionManager._OnPointerOverTrigger;
  23352. },
  23353. enumerable: true,
  23354. configurable: true
  23355. });
  23356. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23357. get: function () {
  23358. return ActionManager._OnPointerOutTrigger;
  23359. },
  23360. enumerable: true,
  23361. configurable: true
  23362. });
  23363. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23364. get: function () {
  23365. return ActionManager._OnEveryFrameTrigger;
  23366. },
  23367. enumerable: true,
  23368. configurable: true
  23369. });
  23370. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23371. get: function () {
  23372. return ActionManager._OnIntersectionEnterTrigger;
  23373. },
  23374. enumerable: true,
  23375. configurable: true
  23376. });
  23377. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23378. get: function () {
  23379. return ActionManager._OnIntersectionExitTrigger;
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23385. get: function () {
  23386. return ActionManager._OnKeyDownTrigger;
  23387. },
  23388. enumerable: true,
  23389. configurable: true
  23390. });
  23391. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23392. get: function () {
  23393. return ActionManager._OnKeyUpTrigger;
  23394. },
  23395. enumerable: true,
  23396. configurable: true
  23397. });
  23398. // Methods
  23399. ActionManager.prototype.dispose = function () {
  23400. var index = this._scene._actionManagers.indexOf(this);
  23401. if (index > -1) {
  23402. this._scene._actionManagers.splice(index, 1);
  23403. }
  23404. };
  23405. ActionManager.prototype.getScene = function () {
  23406. return this._scene;
  23407. };
  23408. /**
  23409. * Does this action manager handles actions of any of the given triggers
  23410. * @param {number[]} triggers - the triggers to be tested
  23411. * @return {boolean} whether one (or more) of the triggers is handeled
  23412. */
  23413. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23414. for (var index = 0; index < this.actions.length; index++) {
  23415. var action = this.actions[index];
  23416. if (triggers.indexOf(action.trigger) > -1) {
  23417. return true;
  23418. }
  23419. }
  23420. return false;
  23421. };
  23422. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23423. /**
  23424. * Does this action manager has pointer triggers
  23425. * @return {boolean} whether or not it has pointer triggers
  23426. */
  23427. get: function () {
  23428. for (var index = 0; index < this.actions.length; index++) {
  23429. var action = this.actions[index];
  23430. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23431. return true;
  23432. }
  23433. }
  23434. return false;
  23435. },
  23436. enumerable: true,
  23437. configurable: true
  23438. });
  23439. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23440. /**
  23441. * Does this action manager has pick triggers
  23442. * @return {boolean} whether or not it has pick triggers
  23443. */
  23444. get: function () {
  23445. for (var index = 0; index < this.actions.length; index++) {
  23446. var action = this.actions[index];
  23447. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23448. return true;
  23449. }
  23450. }
  23451. return false;
  23452. },
  23453. enumerable: true,
  23454. configurable: true
  23455. });
  23456. /**
  23457. * Registers an action to this action manager
  23458. * @param {BABYLON.Action} action - the action to be registered
  23459. * @return {BABYLON.Action} the action amended (prepared) after registration
  23460. */
  23461. ActionManager.prototype.registerAction = function (action) {
  23462. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23463. if (this.getScene().actionManager !== this) {
  23464. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23465. return null;
  23466. }
  23467. }
  23468. this.actions.push(action);
  23469. action._actionManager = this;
  23470. action._prepare();
  23471. return action;
  23472. };
  23473. /**
  23474. * Process a specific trigger
  23475. * @param {number} trigger - the trigger to process
  23476. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23477. */
  23478. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23479. for (var index = 0; index < this.actions.length; index++) {
  23480. var action = this.actions[index];
  23481. if (action.trigger === trigger) {
  23482. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23483. var parameter = action.getTriggerParameter();
  23484. if (parameter) {
  23485. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23486. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23487. if (actualkey !== parameter.toLowerCase()) {
  23488. continue;
  23489. }
  23490. }
  23491. }
  23492. action._executeCurrent(evt);
  23493. }
  23494. }
  23495. };
  23496. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23497. var properties = propertyPath.split(".");
  23498. for (var index = 0; index < properties.length - 1; index++) {
  23499. target = target[properties[index]];
  23500. }
  23501. return target;
  23502. };
  23503. ActionManager.prototype._getProperty = function (propertyPath) {
  23504. var properties = propertyPath.split(".");
  23505. return properties[properties.length - 1];
  23506. };
  23507. // Statics
  23508. ActionManager._NothingTrigger = 0;
  23509. ActionManager._OnPickTrigger = 1;
  23510. ActionManager._OnLeftPickTrigger = 2;
  23511. ActionManager._OnRightPickTrigger = 3;
  23512. ActionManager._OnCenterPickTrigger = 4;
  23513. ActionManager._OnPointerOverTrigger = 5;
  23514. ActionManager._OnPointerOutTrigger = 6;
  23515. ActionManager._OnEveryFrameTrigger = 7;
  23516. ActionManager._OnIntersectionEnterTrigger = 8;
  23517. ActionManager._OnIntersectionExitTrigger = 9;
  23518. ActionManager._OnKeyDownTrigger = 10;
  23519. ActionManager._OnKeyUpTrigger = 11;
  23520. return ActionManager;
  23521. })();
  23522. BABYLON.ActionManager = ActionManager;
  23523. })(BABYLON || (BABYLON = {}));
  23524. //# sourceMappingURL=babylon.actionManager.js.map
  23525. var BABYLON;
  23526. (function (BABYLON) {
  23527. var InterpolateValueAction = (function (_super) {
  23528. __extends(InterpolateValueAction, _super);
  23529. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23530. if (duration === void 0) { duration = 1000; }
  23531. _super.call(this, triggerOptions, condition);
  23532. this.propertyPath = propertyPath;
  23533. this.value = value;
  23534. this.duration = duration;
  23535. this.stopOtherAnimations = stopOtherAnimations;
  23536. this._target = target;
  23537. }
  23538. InterpolateValueAction.prototype._prepare = function () {
  23539. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23540. this._property = this._getProperty(this.propertyPath);
  23541. };
  23542. InterpolateValueAction.prototype.execute = function () {
  23543. var scene = this._actionManager.getScene();
  23544. var keys = [
  23545. {
  23546. frame: 0,
  23547. value: this._target[this._property]
  23548. },
  23549. {
  23550. frame: 100,
  23551. value: this.value
  23552. }
  23553. ];
  23554. var dataType;
  23555. if (typeof this.value === "number") {
  23556. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23557. }
  23558. else if (this.value instanceof BABYLON.Color3) {
  23559. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23560. }
  23561. else if (this.value instanceof BABYLON.Vector3) {
  23562. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23563. }
  23564. else if (this.value instanceof BABYLON.Matrix) {
  23565. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23566. }
  23567. else if (this.value instanceof BABYLON.Quaternion) {
  23568. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23569. }
  23570. else {
  23571. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23572. return;
  23573. }
  23574. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23575. animation.setKeys(keys);
  23576. if (this.stopOtherAnimations) {
  23577. scene.stopAnimation(this._target);
  23578. }
  23579. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23580. };
  23581. return InterpolateValueAction;
  23582. })(BABYLON.Action);
  23583. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23584. })(BABYLON || (BABYLON = {}));
  23585. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23586. var BABYLON;
  23587. (function (BABYLON) {
  23588. var SwitchBooleanAction = (function (_super) {
  23589. __extends(SwitchBooleanAction, _super);
  23590. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23591. _super.call(this, triggerOptions, condition);
  23592. this.propertyPath = propertyPath;
  23593. this._target = target;
  23594. }
  23595. SwitchBooleanAction.prototype._prepare = function () {
  23596. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23597. this._property = this._getProperty(this.propertyPath);
  23598. };
  23599. SwitchBooleanAction.prototype.execute = function () {
  23600. this._target[this._property] = !this._target[this._property];
  23601. };
  23602. return SwitchBooleanAction;
  23603. })(BABYLON.Action);
  23604. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23605. var SetStateAction = (function (_super) {
  23606. __extends(SetStateAction, _super);
  23607. function SetStateAction(triggerOptions, target, value, condition) {
  23608. _super.call(this, triggerOptions, condition);
  23609. this.value = value;
  23610. this._target = target;
  23611. }
  23612. SetStateAction.prototype.execute = function () {
  23613. this._target.state = this.value;
  23614. };
  23615. return SetStateAction;
  23616. })(BABYLON.Action);
  23617. BABYLON.SetStateAction = SetStateAction;
  23618. var SetValueAction = (function (_super) {
  23619. __extends(SetValueAction, _super);
  23620. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23621. _super.call(this, triggerOptions, condition);
  23622. this.propertyPath = propertyPath;
  23623. this.value = value;
  23624. this._target = target;
  23625. }
  23626. SetValueAction.prototype._prepare = function () {
  23627. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23628. this._property = this._getProperty(this.propertyPath);
  23629. };
  23630. SetValueAction.prototype.execute = function () {
  23631. this._target[this._property] = this.value;
  23632. };
  23633. return SetValueAction;
  23634. })(BABYLON.Action);
  23635. BABYLON.SetValueAction = SetValueAction;
  23636. var IncrementValueAction = (function (_super) {
  23637. __extends(IncrementValueAction, _super);
  23638. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23639. _super.call(this, triggerOptions, condition);
  23640. this.propertyPath = propertyPath;
  23641. this.value = value;
  23642. this._target = target;
  23643. }
  23644. IncrementValueAction.prototype._prepare = function () {
  23645. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23646. this._property = this._getProperty(this.propertyPath);
  23647. if (typeof this._target[this._property] !== "number") {
  23648. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23649. }
  23650. };
  23651. IncrementValueAction.prototype.execute = function () {
  23652. this._target[this._property] += this.value;
  23653. };
  23654. return IncrementValueAction;
  23655. })(BABYLON.Action);
  23656. BABYLON.IncrementValueAction = IncrementValueAction;
  23657. var PlayAnimationAction = (function (_super) {
  23658. __extends(PlayAnimationAction, _super);
  23659. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23660. _super.call(this, triggerOptions, condition);
  23661. this.from = from;
  23662. this.to = to;
  23663. this.loop = loop;
  23664. this._target = target;
  23665. }
  23666. PlayAnimationAction.prototype._prepare = function () {
  23667. };
  23668. PlayAnimationAction.prototype.execute = function () {
  23669. var scene = this._actionManager.getScene();
  23670. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23671. };
  23672. return PlayAnimationAction;
  23673. })(BABYLON.Action);
  23674. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23675. var StopAnimationAction = (function (_super) {
  23676. __extends(StopAnimationAction, _super);
  23677. function StopAnimationAction(triggerOptions, target, condition) {
  23678. _super.call(this, triggerOptions, condition);
  23679. this._target = target;
  23680. }
  23681. StopAnimationAction.prototype._prepare = function () {
  23682. };
  23683. StopAnimationAction.prototype.execute = function () {
  23684. var scene = this._actionManager.getScene();
  23685. scene.stopAnimation(this._target);
  23686. };
  23687. return StopAnimationAction;
  23688. })(BABYLON.Action);
  23689. BABYLON.StopAnimationAction = StopAnimationAction;
  23690. var DoNothingAction = (function (_super) {
  23691. __extends(DoNothingAction, _super);
  23692. function DoNothingAction(triggerOptions, condition) {
  23693. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23694. _super.call(this, triggerOptions, condition);
  23695. }
  23696. DoNothingAction.prototype.execute = function () {
  23697. };
  23698. return DoNothingAction;
  23699. })(BABYLON.Action);
  23700. BABYLON.DoNothingAction = DoNothingAction;
  23701. var CombineAction = (function (_super) {
  23702. __extends(CombineAction, _super);
  23703. function CombineAction(triggerOptions, children, condition) {
  23704. _super.call(this, triggerOptions, condition);
  23705. this.children = children;
  23706. }
  23707. CombineAction.prototype._prepare = function () {
  23708. for (var index = 0; index < this.children.length; index++) {
  23709. this.children[index]._actionManager = this._actionManager;
  23710. this.children[index]._prepare();
  23711. }
  23712. };
  23713. CombineAction.prototype.execute = function (evt) {
  23714. for (var index = 0; index < this.children.length; index++) {
  23715. this.children[index].execute(evt);
  23716. }
  23717. };
  23718. return CombineAction;
  23719. })(BABYLON.Action);
  23720. BABYLON.CombineAction = CombineAction;
  23721. var ExecuteCodeAction = (function (_super) {
  23722. __extends(ExecuteCodeAction, _super);
  23723. function ExecuteCodeAction(triggerOptions, func, condition) {
  23724. _super.call(this, triggerOptions, condition);
  23725. this.func = func;
  23726. }
  23727. ExecuteCodeAction.prototype.execute = function (evt) {
  23728. this.func(evt);
  23729. };
  23730. return ExecuteCodeAction;
  23731. })(BABYLON.Action);
  23732. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23733. var SetParentAction = (function (_super) {
  23734. __extends(SetParentAction, _super);
  23735. function SetParentAction(triggerOptions, target, parent, condition) {
  23736. _super.call(this, triggerOptions, condition);
  23737. this._target = target;
  23738. this._parent = parent;
  23739. }
  23740. SetParentAction.prototype._prepare = function () {
  23741. };
  23742. SetParentAction.prototype.execute = function () {
  23743. if (this._target.parent === this._parent) {
  23744. return;
  23745. }
  23746. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23747. invertParentWorldMatrix.invert();
  23748. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23749. this._target.parent = this._parent;
  23750. };
  23751. return SetParentAction;
  23752. })(BABYLON.Action);
  23753. BABYLON.SetParentAction = SetParentAction;
  23754. var PlaySoundAction = (function (_super) {
  23755. __extends(PlaySoundAction, _super);
  23756. function PlaySoundAction(triggerOptions, sound, condition) {
  23757. _super.call(this, triggerOptions, condition);
  23758. this._sound = sound;
  23759. }
  23760. PlaySoundAction.prototype._prepare = function () {
  23761. };
  23762. PlaySoundAction.prototype.execute = function () {
  23763. if (this._sound !== undefined)
  23764. this._sound.play();
  23765. };
  23766. return PlaySoundAction;
  23767. })(BABYLON.Action);
  23768. BABYLON.PlaySoundAction = PlaySoundAction;
  23769. var StopSoundAction = (function (_super) {
  23770. __extends(StopSoundAction, _super);
  23771. function StopSoundAction(triggerOptions, sound, condition) {
  23772. _super.call(this, triggerOptions, condition);
  23773. this._sound = sound;
  23774. }
  23775. StopSoundAction.prototype._prepare = function () {
  23776. };
  23777. StopSoundAction.prototype.execute = function () {
  23778. if (this._sound !== undefined)
  23779. this._sound.stop();
  23780. };
  23781. return StopSoundAction;
  23782. })(BABYLON.Action);
  23783. BABYLON.StopSoundAction = StopSoundAction;
  23784. })(BABYLON || (BABYLON = {}));
  23785. //# sourceMappingURL=babylon.directActions.js.map
  23786. var BABYLON;
  23787. (function (BABYLON) {
  23788. var Geometry = (function () {
  23789. function Geometry(id, scene, vertexData, updatable, mesh) {
  23790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23791. this._totalVertices = 0;
  23792. this._indices = [];
  23793. this.id = id;
  23794. this._engine = scene.getEngine();
  23795. this._meshes = [];
  23796. this._scene = scene;
  23797. // vertexData
  23798. if (vertexData) {
  23799. this.setAllVerticesData(vertexData, updatable);
  23800. }
  23801. else {
  23802. this._totalVertices = 0;
  23803. this._indices = [];
  23804. }
  23805. // applyToMesh
  23806. if (mesh) {
  23807. this.applyToMesh(mesh);
  23808. mesh.computeWorldMatrix(true);
  23809. }
  23810. }
  23811. Geometry.prototype.getScene = function () {
  23812. return this._scene;
  23813. };
  23814. Geometry.prototype.getEngine = function () {
  23815. return this._engine;
  23816. };
  23817. Geometry.prototype.isReady = function () {
  23818. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23819. };
  23820. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23821. vertexData.applyToGeometry(this, updatable);
  23822. };
  23823. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23824. this._vertexBuffers = this._vertexBuffers || {};
  23825. if (this._vertexBuffers[kind]) {
  23826. this._vertexBuffers[kind].dispose();
  23827. }
  23828. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23829. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23830. stride = this._vertexBuffers[kind].getStrideSize();
  23831. this._totalVertices = data.length / stride;
  23832. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23833. var meshes = this._meshes;
  23834. var numOfMeshes = meshes.length;
  23835. for (var index = 0; index < numOfMeshes; index++) {
  23836. var mesh = meshes[index];
  23837. mesh._resetPointsArrayCache();
  23838. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23839. mesh._createGlobalSubMesh();
  23840. mesh.computeWorldMatrix(true);
  23841. }
  23842. }
  23843. };
  23844. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23845. var vertexBuffer = this.getVertexBuffer(kind);
  23846. if (!vertexBuffer) {
  23847. return;
  23848. }
  23849. vertexBuffer.updateDirectly(data, offset);
  23850. };
  23851. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23852. var vertexBuffer = this.getVertexBuffer(kind);
  23853. if (!vertexBuffer) {
  23854. return;
  23855. }
  23856. vertexBuffer.update(data);
  23857. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23858. var extend;
  23859. var stride = vertexBuffer.getStrideSize();
  23860. this._totalVertices = data.length / stride;
  23861. if (updateExtends) {
  23862. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23863. }
  23864. var meshes = this._meshes;
  23865. var numOfMeshes = meshes.length;
  23866. for (var index = 0; index < numOfMeshes; index++) {
  23867. var mesh = meshes[index];
  23868. mesh._resetPointsArrayCache();
  23869. if (updateExtends) {
  23870. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23871. }
  23872. }
  23873. }
  23874. };
  23875. Geometry.prototype.getTotalVertices = function () {
  23876. if (!this.isReady()) {
  23877. return 0;
  23878. }
  23879. return this._totalVertices;
  23880. };
  23881. Geometry.prototype.getVerticesData = function (kind) {
  23882. var vertexBuffer = this.getVertexBuffer(kind);
  23883. if (!vertexBuffer) {
  23884. return null;
  23885. }
  23886. return vertexBuffer.getData();
  23887. };
  23888. Geometry.prototype.getVertexBuffer = function (kind) {
  23889. if (!this.isReady()) {
  23890. return null;
  23891. }
  23892. return this._vertexBuffers[kind];
  23893. };
  23894. Geometry.prototype.getVertexBuffers = function () {
  23895. if (!this.isReady()) {
  23896. return null;
  23897. }
  23898. return this._vertexBuffers;
  23899. };
  23900. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23901. if (!this._vertexBuffers) {
  23902. if (this._delayInfo) {
  23903. return this._delayInfo.indexOf(kind) !== -1;
  23904. }
  23905. return false;
  23906. }
  23907. return this._vertexBuffers[kind] !== undefined;
  23908. };
  23909. Geometry.prototype.getVerticesDataKinds = function () {
  23910. var result = [];
  23911. if (!this._vertexBuffers && this._delayInfo) {
  23912. for (var kind in this._delayInfo) {
  23913. result.push(kind);
  23914. }
  23915. }
  23916. else {
  23917. for (kind in this._vertexBuffers) {
  23918. result.push(kind);
  23919. }
  23920. }
  23921. return result;
  23922. };
  23923. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23924. if (this._indexBuffer) {
  23925. this._engine._releaseBuffer(this._indexBuffer);
  23926. }
  23927. this._indices = indices;
  23928. if (this._meshes.length !== 0 && this._indices) {
  23929. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23930. }
  23931. if (totalVertices !== undefined) {
  23932. this._totalVertices = totalVertices;
  23933. }
  23934. var meshes = this._meshes;
  23935. var numOfMeshes = meshes.length;
  23936. for (var index = 0; index < numOfMeshes; index++) {
  23937. meshes[index]._createGlobalSubMesh();
  23938. }
  23939. };
  23940. Geometry.prototype.getTotalIndices = function () {
  23941. if (!this.isReady()) {
  23942. return 0;
  23943. }
  23944. return this._indices.length;
  23945. };
  23946. Geometry.prototype.getIndices = function () {
  23947. if (!this.isReady()) {
  23948. return null;
  23949. }
  23950. return this._indices;
  23951. };
  23952. Geometry.prototype.getIndexBuffer = function () {
  23953. if (!this.isReady()) {
  23954. return null;
  23955. }
  23956. return this._indexBuffer;
  23957. };
  23958. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23959. var meshes = this._meshes;
  23960. var index = meshes.indexOf(mesh);
  23961. if (index === -1) {
  23962. return;
  23963. }
  23964. for (var kind in this._vertexBuffers) {
  23965. this._vertexBuffers[kind].dispose();
  23966. }
  23967. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23968. this._indexBuffer = null;
  23969. }
  23970. meshes.splice(index, 1);
  23971. mesh._geometry = null;
  23972. if (meshes.length === 0 && shouldDispose) {
  23973. this.dispose();
  23974. }
  23975. };
  23976. Geometry.prototype.applyToMesh = function (mesh) {
  23977. if (mesh._geometry === this) {
  23978. return;
  23979. }
  23980. var previousGeometry = mesh._geometry;
  23981. if (previousGeometry) {
  23982. previousGeometry.releaseForMesh(mesh);
  23983. }
  23984. var meshes = this._meshes;
  23985. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23986. mesh._geometry = this;
  23987. this._scene.pushGeometry(this);
  23988. meshes.push(mesh);
  23989. if (this.isReady()) {
  23990. this._applyToMesh(mesh);
  23991. }
  23992. else {
  23993. mesh._boundingInfo = this._boundingInfo;
  23994. }
  23995. };
  23996. Geometry.prototype._applyToMesh = function (mesh) {
  23997. var numOfMeshes = this._meshes.length;
  23998. for (var kind in this._vertexBuffers) {
  23999. if (numOfMeshes === 1) {
  24000. this._vertexBuffers[kind].create();
  24001. }
  24002. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24003. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24004. mesh._resetPointsArrayCache();
  24005. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24006. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24007. mesh._createGlobalSubMesh();
  24008. //bounding info was just created again, world matrix should be applied again.
  24009. mesh._updateBoundingInfo();
  24010. }
  24011. }
  24012. // indexBuffer
  24013. if (numOfMeshes === 1 && this._indices) {
  24014. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24015. }
  24016. if (this._indexBuffer) {
  24017. this._indexBuffer.references = numOfMeshes;
  24018. }
  24019. };
  24020. Geometry.prototype.load = function (scene, onLoaded) {
  24021. var _this = this;
  24022. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24023. return;
  24024. }
  24025. if (this.isReady()) {
  24026. if (onLoaded) {
  24027. onLoaded();
  24028. }
  24029. return;
  24030. }
  24031. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24032. scene._addPendingData(this);
  24033. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24034. _this._delayLoadingFunction(JSON.parse(data), _this);
  24035. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24036. _this._delayInfo = [];
  24037. scene._removePendingData(_this);
  24038. var meshes = _this._meshes;
  24039. var numOfMeshes = meshes.length;
  24040. for (var index = 0; index < numOfMeshes; index++) {
  24041. _this._applyToMesh(meshes[index]);
  24042. }
  24043. if (onLoaded) {
  24044. onLoaded();
  24045. }
  24046. }, function () {
  24047. }, scene.database);
  24048. };
  24049. Geometry.prototype.dispose = function () {
  24050. var meshes = this._meshes;
  24051. var numOfMeshes = meshes.length;
  24052. var index;
  24053. for (index = 0; index < numOfMeshes; index++) {
  24054. this.releaseForMesh(meshes[index]);
  24055. }
  24056. this._meshes = [];
  24057. for (var kind in this._vertexBuffers) {
  24058. this._vertexBuffers[kind].dispose();
  24059. }
  24060. this._vertexBuffers = [];
  24061. this._totalVertices = 0;
  24062. if (this._indexBuffer) {
  24063. this._engine._releaseBuffer(this._indexBuffer);
  24064. }
  24065. this._indexBuffer = null;
  24066. this._indices = [];
  24067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24068. this.delayLoadingFile = null;
  24069. this._delayLoadingFunction = null;
  24070. this._delayInfo = [];
  24071. this._boundingInfo = null; // todo: .dispose()
  24072. var geometries = this._scene.getGeometries();
  24073. index = geometries.indexOf(this);
  24074. if (index > -1) {
  24075. geometries.splice(index, 1);
  24076. }
  24077. };
  24078. Geometry.prototype.copy = function (id) {
  24079. var vertexData = new BABYLON.VertexData();
  24080. vertexData.indices = [];
  24081. var indices = this.getIndices();
  24082. for (var index = 0; index < indices.length; index++) {
  24083. vertexData.indices.push(indices[index]);
  24084. }
  24085. var updatable = false;
  24086. var stopChecking = false;
  24087. for (var kind in this._vertexBuffers) {
  24088. vertexData.set(this.getVerticesData(kind), kind);
  24089. if (!stopChecking) {
  24090. updatable = this.getVertexBuffer(kind).isUpdatable();
  24091. stopChecking = !updatable;
  24092. }
  24093. }
  24094. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24095. geometry.delayLoadState = this.delayLoadState;
  24096. geometry.delayLoadingFile = this.delayLoadingFile;
  24097. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24098. for (kind in this._delayInfo) {
  24099. geometry._delayInfo = geometry._delayInfo || [];
  24100. geometry._delayInfo.push(kind);
  24101. }
  24102. // Bounding info
  24103. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24104. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24105. return geometry;
  24106. };
  24107. // Statics
  24108. Geometry.ExtractFromMesh = function (mesh, id) {
  24109. var geometry = mesh._geometry;
  24110. if (!geometry) {
  24111. return null;
  24112. }
  24113. return geometry.copy(id);
  24114. };
  24115. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24116. // be aware Math.random() could cause collisions
  24117. Geometry.RandomId = function () {
  24118. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24119. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24120. return v.toString(16);
  24121. });
  24122. };
  24123. return Geometry;
  24124. })();
  24125. BABYLON.Geometry = Geometry;
  24126. /////// Primitives //////////////////////////////////////////////
  24127. var Geometry;
  24128. (function (Geometry) {
  24129. var Primitives;
  24130. (function (Primitives) {
  24131. /// Abstract class
  24132. var _Primitive = (function (_super) {
  24133. __extends(_Primitive, _super);
  24134. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24135. this._beingRegenerated = true;
  24136. this._canBeRegenerated = canBeRegenerated;
  24137. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24138. this._beingRegenerated = false;
  24139. }
  24140. _Primitive.prototype.canBeRegenerated = function () {
  24141. return this._canBeRegenerated;
  24142. };
  24143. _Primitive.prototype.regenerate = function () {
  24144. if (!this._canBeRegenerated) {
  24145. return;
  24146. }
  24147. this._beingRegenerated = true;
  24148. this.setAllVerticesData(this._regenerateVertexData(), false);
  24149. this._beingRegenerated = false;
  24150. };
  24151. _Primitive.prototype.asNewGeometry = function (id) {
  24152. return _super.prototype.copy.call(this, id);
  24153. };
  24154. // overrides
  24155. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24156. if (!this._beingRegenerated) {
  24157. return;
  24158. }
  24159. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24160. };
  24161. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24162. if (!this._beingRegenerated) {
  24163. return;
  24164. }
  24165. _super.prototype.setVerticesData.call(this, kind, data, false);
  24166. };
  24167. // to override
  24168. // protected
  24169. _Primitive.prototype._regenerateVertexData = function () {
  24170. throw new Error("Abstract method");
  24171. };
  24172. _Primitive.prototype.copy = function (id) {
  24173. throw new Error("Must be overriden in sub-classes.");
  24174. };
  24175. return _Primitive;
  24176. })(Geometry);
  24177. Primitives._Primitive = _Primitive;
  24178. var Box = (function (_super) {
  24179. __extends(Box, _super);
  24180. function Box(id, scene, size, canBeRegenerated, mesh) {
  24181. this.size = size;
  24182. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24183. }
  24184. Box.prototype._regenerateVertexData = function () {
  24185. return BABYLON.VertexData.CreateBox(this.size);
  24186. };
  24187. Box.prototype.copy = function (id) {
  24188. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24189. };
  24190. return Box;
  24191. })(_Primitive);
  24192. Primitives.Box = Box;
  24193. var Sphere = (function (_super) {
  24194. __extends(Sphere, _super);
  24195. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  24196. this.segments = segments;
  24197. this.diameter = diameter;
  24198. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24199. }
  24200. Sphere.prototype._regenerateVertexData = function () {
  24201. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  24202. };
  24203. Sphere.prototype.copy = function (id) {
  24204. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  24205. };
  24206. return Sphere;
  24207. })(_Primitive);
  24208. Primitives.Sphere = Sphere;
  24209. var Cylinder = (function (_super) {
  24210. __extends(Cylinder, _super);
  24211. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  24212. if (subdivisions === void 0) { subdivisions = 1; }
  24213. this.height = height;
  24214. this.diameterTop = diameterTop;
  24215. this.diameterBottom = diameterBottom;
  24216. this.tessellation = tessellation;
  24217. this.subdivisions = subdivisions;
  24218. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24219. }
  24220. Cylinder.prototype._regenerateVertexData = function () {
  24221. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  24222. };
  24223. Cylinder.prototype.copy = function (id) {
  24224. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  24225. };
  24226. return Cylinder;
  24227. })(_Primitive);
  24228. Primitives.Cylinder = Cylinder;
  24229. var Torus = (function (_super) {
  24230. __extends(Torus, _super);
  24231. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  24232. this.diameter = diameter;
  24233. this.thickness = thickness;
  24234. this.tessellation = tessellation;
  24235. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24236. }
  24237. Torus.prototype._regenerateVertexData = function () {
  24238. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  24239. };
  24240. Torus.prototype.copy = function (id) {
  24241. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  24242. };
  24243. return Torus;
  24244. })(_Primitive);
  24245. Primitives.Torus = Torus;
  24246. var Ground = (function (_super) {
  24247. __extends(Ground, _super);
  24248. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24249. this.width = width;
  24250. this.height = height;
  24251. this.subdivisions = subdivisions;
  24252. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24253. }
  24254. Ground.prototype._regenerateVertexData = function () {
  24255. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24256. };
  24257. Ground.prototype.copy = function (id) {
  24258. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24259. };
  24260. return Ground;
  24261. })(_Primitive);
  24262. Primitives.Ground = Ground;
  24263. var TiledGround = (function (_super) {
  24264. __extends(TiledGround, _super);
  24265. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24266. this.xmin = xmin;
  24267. this.zmin = zmin;
  24268. this.xmax = xmax;
  24269. this.zmax = zmax;
  24270. this.subdivisions = subdivisions;
  24271. this.precision = precision;
  24272. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24273. }
  24274. TiledGround.prototype._regenerateVertexData = function () {
  24275. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24276. };
  24277. TiledGround.prototype.copy = function (id) {
  24278. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24279. };
  24280. return TiledGround;
  24281. })(_Primitive);
  24282. Primitives.TiledGround = TiledGround;
  24283. var Plane = (function (_super) {
  24284. __extends(Plane, _super);
  24285. function Plane(id, scene, size, canBeRegenerated, mesh) {
  24286. this.size = size;
  24287. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24288. }
  24289. Plane.prototype._regenerateVertexData = function () {
  24290. return BABYLON.VertexData.CreatePlane(this.size);
  24291. };
  24292. Plane.prototype.copy = function (id) {
  24293. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24294. };
  24295. return Plane;
  24296. })(_Primitive);
  24297. Primitives.Plane = Plane;
  24298. var TorusKnot = (function (_super) {
  24299. __extends(TorusKnot, _super);
  24300. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  24301. this.radius = radius;
  24302. this.tube = tube;
  24303. this.radialSegments = radialSegments;
  24304. this.tubularSegments = tubularSegments;
  24305. this.p = p;
  24306. this.q = q;
  24307. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24308. }
  24309. TorusKnot.prototype._regenerateVertexData = function () {
  24310. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  24311. };
  24312. TorusKnot.prototype.copy = function (id) {
  24313. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  24314. };
  24315. return TorusKnot;
  24316. })(_Primitive);
  24317. Primitives.TorusKnot = TorusKnot;
  24318. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24319. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24320. })(BABYLON || (BABYLON = {}));
  24321. //# sourceMappingURL=babylon.geometry.js.map
  24322. var BABYLON;
  24323. (function (BABYLON) {
  24324. var Gamepads = (function () {
  24325. function Gamepads(ongamedpadconnected) {
  24326. var _this = this;
  24327. this.babylonGamepads = [];
  24328. this.oneGamepadConnected = false;
  24329. this.isMonitoring = false;
  24330. this.gamepadEventSupported = 'GamepadEvent' in window;
  24331. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24332. 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=";
  24333. this._callbackGamepadConnected = ongamedpadconnected;
  24334. if (this.gamepadSupportAvailable) {
  24335. // Checking if the gamepad connected event is supported (like in Firefox)
  24336. if (this.gamepadEventSupported) {
  24337. window.addEventListener('gamepadconnected', function (evt) {
  24338. _this._onGamepadConnected(evt);
  24339. }, false);
  24340. window.addEventListener('gamepaddisconnected', function (evt) {
  24341. _this._onGamepadDisconnected(evt);
  24342. }, false);
  24343. }
  24344. else {
  24345. this._startMonitoringGamepads();
  24346. }
  24347. if (!this.oneGamepadConnected) {
  24348. this._insertGamepadDOMInstructions();
  24349. }
  24350. }
  24351. else {
  24352. this._insertGamepadDOMNotSupported();
  24353. }
  24354. }
  24355. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24356. Gamepads.gamepadDOMInfo = document.createElement("div");
  24357. var buttonAImage = document.createElement("img");
  24358. buttonAImage.src = this.buttonADataURL;
  24359. var spanMessage = document.createElement("span");
  24360. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24361. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24362. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24363. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24364. Gamepads.gamepadDOMInfo.style.width = "100%";
  24365. Gamepads.gamepadDOMInfo.style.height = "48px";
  24366. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24367. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24368. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24369. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24370. buttonAImage.style.position = "relative";
  24371. buttonAImage.style.bottom = "8px";
  24372. spanMessage.style.position = "relative";
  24373. spanMessage.style.fontSize = "32px";
  24374. spanMessage.style.bottom = "32px";
  24375. spanMessage.style.color = "green";
  24376. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24377. };
  24378. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24379. Gamepads.gamepadDOMInfo = document.createElement("div");
  24380. var spanMessage = document.createElement("span");
  24381. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24382. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24383. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24384. Gamepads.gamepadDOMInfo.style.width = "100%";
  24385. Gamepads.gamepadDOMInfo.style.height = "40px";
  24386. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24387. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24388. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24389. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24390. spanMessage.style.position = "relative";
  24391. spanMessage.style.fontSize = "32px";
  24392. spanMessage.style.color = "red";
  24393. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24394. };
  24395. Gamepads.prototype.dispose = function () {
  24396. if (Gamepads.gamepadDOMInfo) {
  24397. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24398. }
  24399. };
  24400. Gamepads.prototype._onGamepadConnected = function (evt) {
  24401. var newGamepad = this._addNewGamepad(evt.gamepad);
  24402. if (this._callbackGamepadConnected)
  24403. this._callbackGamepadConnected(newGamepad);
  24404. this._startMonitoringGamepads();
  24405. };
  24406. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24407. if (!this.oneGamepadConnected) {
  24408. this.oneGamepadConnected = true;
  24409. if (Gamepads.gamepadDOMInfo) {
  24410. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24411. Gamepads.gamepadDOMInfo = null;
  24412. }
  24413. }
  24414. var newGamepad;
  24415. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24416. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24417. }
  24418. else {
  24419. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24420. }
  24421. this.babylonGamepads.push(newGamepad);
  24422. return newGamepad;
  24423. };
  24424. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24425. for (var i in this.babylonGamepads) {
  24426. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24427. this.babylonGamepads.splice(i, 1);
  24428. break;
  24429. }
  24430. }
  24431. // If no gamepads are left, stop the polling loop.
  24432. if (this.babylonGamepads.length == 0) {
  24433. this._stopMonitoringGamepads();
  24434. }
  24435. };
  24436. Gamepads.prototype._startMonitoringGamepads = function () {
  24437. if (!this.isMonitoring) {
  24438. this.isMonitoring = true;
  24439. this._checkGamepadsStatus();
  24440. }
  24441. };
  24442. Gamepads.prototype._stopMonitoringGamepads = function () {
  24443. this.isMonitoring = false;
  24444. };
  24445. Gamepads.prototype._checkGamepadsStatus = function () {
  24446. var _this = this;
  24447. // updating gamepad objects
  24448. this._updateGamepadObjects();
  24449. for (var i in this.babylonGamepads) {
  24450. this.babylonGamepads[i].update();
  24451. }
  24452. if (this.isMonitoring) {
  24453. if (window.requestAnimationFrame) {
  24454. window.requestAnimationFrame(function () {
  24455. _this._checkGamepadsStatus();
  24456. });
  24457. }
  24458. else if (window.mozRequestAnimationFrame) {
  24459. window.mozRequestAnimationFrame(function () {
  24460. _this._checkGamepadsStatus();
  24461. });
  24462. }
  24463. else if (window.webkitRequestAnimationFrame) {
  24464. window.webkitRequestAnimationFrame(function () {
  24465. _this._checkGamepadsStatus();
  24466. });
  24467. }
  24468. }
  24469. };
  24470. // This function is called only on Chrome, which does not yet support
  24471. // connection/disconnection events, but requires you to monitor
  24472. // an array for changes.
  24473. Gamepads.prototype._updateGamepadObjects = function () {
  24474. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24475. for (var i = 0; i < gamepads.length; i++) {
  24476. if (gamepads[i]) {
  24477. if (!(gamepads[i].index in this.babylonGamepads)) {
  24478. var newGamepad = this._addNewGamepad(gamepads[i]);
  24479. if (this._callbackGamepadConnected) {
  24480. this._callbackGamepadConnected(newGamepad);
  24481. }
  24482. }
  24483. else {
  24484. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24485. }
  24486. }
  24487. }
  24488. };
  24489. return Gamepads;
  24490. })();
  24491. BABYLON.Gamepads = Gamepads;
  24492. var StickValues = (function () {
  24493. function StickValues(x, y) {
  24494. this.x = x;
  24495. this.y = y;
  24496. }
  24497. return StickValues;
  24498. })();
  24499. BABYLON.StickValues = StickValues;
  24500. var Gamepad = (function () {
  24501. function Gamepad(id, index, browserGamepad) {
  24502. this.id = id;
  24503. this.index = index;
  24504. this.browserGamepad = browserGamepad;
  24505. if (this.browserGamepad.axes.length >= 2) {
  24506. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24507. }
  24508. if (this.browserGamepad.axes.length >= 4) {
  24509. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24510. }
  24511. }
  24512. Gamepad.prototype.onleftstickchanged = function (callback) {
  24513. this._onleftstickchanged = callback;
  24514. };
  24515. Gamepad.prototype.onrightstickchanged = function (callback) {
  24516. this._onrightstickchanged = callback;
  24517. };
  24518. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24519. get: function () {
  24520. return this._leftStick;
  24521. },
  24522. set: function (newValues) {
  24523. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24524. this._onleftstickchanged(newValues);
  24525. }
  24526. this._leftStick = newValues;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24532. get: function () {
  24533. return this._rightStick;
  24534. },
  24535. set: function (newValues) {
  24536. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24537. this._onrightstickchanged(newValues);
  24538. }
  24539. this._rightStick = newValues;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Gamepad.prototype.update = function () {
  24545. if (this._leftStick) {
  24546. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24547. }
  24548. if (this._rightStick) {
  24549. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24550. }
  24551. };
  24552. return Gamepad;
  24553. })();
  24554. BABYLON.Gamepad = Gamepad;
  24555. var GenericPad = (function (_super) {
  24556. __extends(GenericPad, _super);
  24557. function GenericPad(id, index, gamepad) {
  24558. _super.call(this, id, index, gamepad);
  24559. this.id = id;
  24560. this.index = index;
  24561. this.gamepad = gamepad;
  24562. this._buttons = new Array(gamepad.buttons.length);
  24563. }
  24564. GenericPad.prototype.onbuttondown = function (callback) {
  24565. this._onbuttondown = callback;
  24566. };
  24567. GenericPad.prototype.onbuttonup = function (callback) {
  24568. this._onbuttonup = callback;
  24569. };
  24570. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24571. if (newValue !== currentValue) {
  24572. if (this._onbuttondown && newValue === 1) {
  24573. this._onbuttondown(buttonIndex);
  24574. }
  24575. if (this._onbuttonup && newValue === 0) {
  24576. this._onbuttonup(buttonIndex);
  24577. }
  24578. }
  24579. return newValue;
  24580. };
  24581. GenericPad.prototype.update = function () {
  24582. _super.prototype.update.call(this);
  24583. for (var index = 0; index < this._buttons.length; index++) {
  24584. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24585. }
  24586. };
  24587. return GenericPad;
  24588. })(Gamepad);
  24589. BABYLON.GenericPad = GenericPad;
  24590. (function (Xbox360Button) {
  24591. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24592. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24593. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24594. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24595. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24596. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24597. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24598. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24599. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24600. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24601. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24602. var Xbox360Button = BABYLON.Xbox360Button;
  24603. (function (Xbox360Dpad) {
  24604. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24605. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24606. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24607. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24608. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24609. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24610. var Xbox360Pad = (function (_super) {
  24611. __extends(Xbox360Pad, _super);
  24612. function Xbox360Pad() {
  24613. _super.apply(this, arguments);
  24614. this._leftTrigger = 0;
  24615. this._rightTrigger = 0;
  24616. this._buttonA = 0;
  24617. this._buttonB = 0;
  24618. this._buttonX = 0;
  24619. this._buttonY = 0;
  24620. this._buttonBack = 0;
  24621. this._buttonStart = 0;
  24622. this._buttonLB = 0;
  24623. this._buttonRB = 0;
  24624. this._buttonLeftStick = 0;
  24625. this._buttonRightStick = 0;
  24626. this._dPadUp = 0;
  24627. this._dPadDown = 0;
  24628. this._dPadLeft = 0;
  24629. this._dPadRight = 0;
  24630. }
  24631. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24632. this._onlefttriggerchanged = callback;
  24633. };
  24634. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24635. this._onrighttriggerchanged = callback;
  24636. };
  24637. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24638. get: function () {
  24639. return this._leftTrigger;
  24640. },
  24641. set: function (newValue) {
  24642. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24643. this._onlefttriggerchanged(newValue);
  24644. }
  24645. this._leftTrigger = newValue;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24651. get: function () {
  24652. return this._rightTrigger;
  24653. },
  24654. set: function (newValue) {
  24655. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24656. this._onrighttriggerchanged(newValue);
  24657. }
  24658. this._rightTrigger = newValue;
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24664. this._onbuttondown = callback;
  24665. };
  24666. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24667. this._onbuttonup = callback;
  24668. };
  24669. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24670. this._ondpaddown = callback;
  24671. };
  24672. Xbox360Pad.prototype.ondpadup = function (callback) {
  24673. this._ondpadup = callback;
  24674. };
  24675. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24676. if (newValue !== currentValue) {
  24677. if (this._onbuttondown && newValue === 1) {
  24678. this._onbuttondown(buttonType);
  24679. }
  24680. if (this._onbuttonup && newValue === 0) {
  24681. this._onbuttonup(buttonType);
  24682. }
  24683. }
  24684. return newValue;
  24685. };
  24686. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24687. if (newValue !== currentValue) {
  24688. if (this._ondpaddown && newValue === 1) {
  24689. this._ondpaddown(buttonType);
  24690. }
  24691. if (this._ondpadup && newValue === 0) {
  24692. this._ondpadup(buttonType);
  24693. }
  24694. }
  24695. return newValue;
  24696. };
  24697. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24698. get: function () {
  24699. return this._buttonA;
  24700. },
  24701. set: function (value) {
  24702. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24708. get: function () {
  24709. return this._buttonB;
  24710. },
  24711. set: function (value) {
  24712. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24718. get: function () {
  24719. return this._buttonX;
  24720. },
  24721. set: function (value) {
  24722. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24728. get: function () {
  24729. return this._buttonY;
  24730. },
  24731. set: function (value) {
  24732. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24738. get: function () {
  24739. return this._buttonStart;
  24740. },
  24741. set: function (value) {
  24742. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24743. },
  24744. enumerable: true,
  24745. configurable: true
  24746. });
  24747. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24748. get: function () {
  24749. return this._buttonBack;
  24750. },
  24751. set: function (value) {
  24752. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24758. get: function () {
  24759. return this._buttonLB;
  24760. },
  24761. set: function (value) {
  24762. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24768. get: function () {
  24769. return this._buttonRB;
  24770. },
  24771. set: function (value) {
  24772. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24778. get: function () {
  24779. return this._buttonLeftStick;
  24780. },
  24781. set: function (value) {
  24782. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24788. get: function () {
  24789. return this._buttonRightStick;
  24790. },
  24791. set: function (value) {
  24792. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24798. get: function () {
  24799. return this._dPadUp;
  24800. },
  24801. set: function (value) {
  24802. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24808. get: function () {
  24809. return this._dPadDown;
  24810. },
  24811. set: function (value) {
  24812. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24818. get: function () {
  24819. return this._dPadLeft;
  24820. },
  24821. set: function (value) {
  24822. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24828. get: function () {
  24829. return this._dPadRight;
  24830. },
  24831. set: function (value) {
  24832. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24833. },
  24834. enumerable: true,
  24835. configurable: true
  24836. });
  24837. Xbox360Pad.prototype.update = function () {
  24838. _super.prototype.update.call(this);
  24839. this.buttonA = this.browserGamepad.buttons[0].value;
  24840. this.buttonB = this.browserGamepad.buttons[1].value;
  24841. this.buttonX = this.browserGamepad.buttons[2].value;
  24842. this.buttonY = this.browserGamepad.buttons[3].value;
  24843. this.buttonLB = this.browserGamepad.buttons[4].value;
  24844. this.buttonRB = this.browserGamepad.buttons[5].value;
  24845. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24846. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24847. this.buttonBack = this.browserGamepad.buttons[8].value;
  24848. this.buttonStart = this.browserGamepad.buttons[9].value;
  24849. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24850. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24851. this.dPadUp = this.browserGamepad.buttons[12].value;
  24852. this.dPadDown = this.browserGamepad.buttons[13].value;
  24853. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24854. this.dPadRight = this.browserGamepad.buttons[15].value;
  24855. };
  24856. return Xbox360Pad;
  24857. })(Gamepad);
  24858. BABYLON.Xbox360Pad = Xbox360Pad;
  24859. })(BABYLON || (BABYLON = {}));
  24860. //# sourceMappingURL=babylon.gamepads.js.map
  24861. var BABYLON;
  24862. (function (BABYLON) {
  24863. // We're mainly based on the logic defined into the FreeCamera code
  24864. var GamepadCamera = (function (_super) {
  24865. __extends(GamepadCamera, _super);
  24866. function GamepadCamera(name, position, scene) {
  24867. var _this = this;
  24868. _super.call(this, name, position, scene);
  24869. this.angularSensibility = 200;
  24870. this.moveSensibility = 75;
  24871. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24872. _this._onNewGameConnected(gamepad);
  24873. });
  24874. }
  24875. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24876. // Only the first gamepad can control the camera
  24877. if (gamepad.index === 0) {
  24878. this._gamepad = gamepad;
  24879. }
  24880. };
  24881. GamepadCamera.prototype._checkInputs = function () {
  24882. if (!this._gamepad) {
  24883. return;
  24884. }
  24885. var LSValues = this._gamepad.leftStick;
  24886. var normalizedLX = LSValues.x / this.moveSensibility;
  24887. var normalizedLY = LSValues.y / this.moveSensibility;
  24888. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24889. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24890. var RSValues = this._gamepad.rightStick;
  24891. var normalizedRX = RSValues.x / this.angularSensibility;
  24892. var normalizedRY = RSValues.y / this.angularSensibility;
  24893. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24894. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24895. ;
  24896. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24897. var speed = this._computeLocalCameraSpeed() * 50.0;
  24898. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  24899. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24900. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24901. };
  24902. GamepadCamera.prototype.dispose = function () {
  24903. this._gamepads.dispose();
  24904. _super.prototype.dispose.call(this);
  24905. };
  24906. return GamepadCamera;
  24907. })(BABYLON.FreeCamera);
  24908. BABYLON.GamepadCamera = GamepadCamera;
  24909. })(BABYLON || (BABYLON = {}));
  24910. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24911. var BABYLON;
  24912. (function (BABYLON) {
  24913. var LinesMesh = (function (_super) {
  24914. __extends(LinesMesh, _super);
  24915. function LinesMesh(name, scene, updatable) {
  24916. if (updatable === void 0) { updatable = false; }
  24917. _super.call(this, name, scene);
  24918. this.color = new BABYLON.Color3(1, 1, 1);
  24919. this.alpha = 1;
  24920. this._indices = new Array();
  24921. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24922. attributes: ["position"],
  24923. uniforms: ["worldViewProjection", "color"],
  24924. needAlphaBlending: true
  24925. });
  24926. }
  24927. Object.defineProperty(LinesMesh.prototype, "material", {
  24928. get: function () {
  24929. return this._colorShader;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24935. get: function () {
  24936. return false;
  24937. },
  24938. enumerable: true,
  24939. configurable: true
  24940. });
  24941. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24942. get: function () {
  24943. return false;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24949. var engine = this.getScene().getEngine();
  24950. var indexToBind = this._geometry.getIndexBuffer();
  24951. // VBOs
  24952. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24953. // Color
  24954. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24955. };
  24956. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24957. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24958. return;
  24959. }
  24960. var engine = this.getScene().getEngine();
  24961. // Draw order
  24962. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24963. };
  24964. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24965. return null;
  24966. };
  24967. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24968. this._colorShader.dispose();
  24969. _super.prototype.dispose.call(this, doNotRecurse);
  24970. };
  24971. return LinesMesh;
  24972. })(BABYLON.Mesh);
  24973. BABYLON.LinesMesh = LinesMesh;
  24974. })(BABYLON || (BABYLON = {}));
  24975. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24976. (function (BABYLON) {
  24977. var OutlineRenderer = (function () {
  24978. function OutlineRenderer(scene) {
  24979. this._scene = scene;
  24980. }
  24981. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24982. var _this = this;
  24983. if (useOverlay === void 0) { useOverlay = false; }
  24984. var scene = this._scene;
  24985. var engine = this._scene.getEngine();
  24986. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24987. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24988. return;
  24989. }
  24990. var mesh = subMesh.getRenderingMesh();
  24991. var material = subMesh.getMaterial();
  24992. engine.enableEffect(this._effect);
  24993. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24994. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24995. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24996. // Bones
  24997. if (mesh.useBones) {
  24998. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24999. }
  25000. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25001. // Alpha test
  25002. if (material && material.needAlphaTesting()) {
  25003. var alphaTexture = material.getAlphaTestTexture();
  25004. this._effect.setTexture("diffuseSampler", alphaTexture);
  25005. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25006. }
  25007. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25008. _this._effect.setMatrix("world", world);
  25009. });
  25010. };
  25011. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25012. var defines = [];
  25013. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25014. var mesh = subMesh.getMesh();
  25015. var material = subMesh.getMaterial();
  25016. // Alpha test
  25017. if (material && material.needAlphaTesting()) {
  25018. defines.push("#define ALPHATEST");
  25019. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25020. attribs.push(BABYLON.VertexBuffer.UVKind);
  25021. defines.push("#define UV1");
  25022. }
  25023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25024. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25025. defines.push("#define UV2");
  25026. }
  25027. }
  25028. // Bones
  25029. if (mesh.useBones) {
  25030. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25031. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25032. defines.push("#define BONES");
  25033. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25034. }
  25035. // Instances
  25036. if (useInstances) {
  25037. defines.push("#define INSTANCES");
  25038. attribs.push("world0");
  25039. attribs.push("world1");
  25040. attribs.push("world2");
  25041. attribs.push("world3");
  25042. }
  25043. // Get correct effect
  25044. var join = defines.join("\n");
  25045. if (this._cachedDefines !== join) {
  25046. this._cachedDefines = join;
  25047. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25048. }
  25049. return this._effect.isReady();
  25050. };
  25051. return OutlineRenderer;
  25052. })();
  25053. BABYLON.OutlineRenderer = OutlineRenderer;
  25054. })(BABYLON || (BABYLON = {}));
  25055. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25056. (function (BABYLON) {
  25057. var MeshAssetTask = (function () {
  25058. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25059. this.name = name;
  25060. this.meshesNames = meshesNames;
  25061. this.rootUrl = rootUrl;
  25062. this.sceneFilename = sceneFilename;
  25063. this.isCompleted = false;
  25064. }
  25065. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25066. var _this = this;
  25067. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25068. _this.loadedMeshes = meshes;
  25069. _this.loadedParticleSystems = particleSystems;
  25070. _this.loadedSkeletons = skeletons;
  25071. _this.isCompleted = true;
  25072. if (_this.onSuccess) {
  25073. _this.onSuccess(_this);
  25074. }
  25075. onSuccess();
  25076. }, null, function () {
  25077. if (_this.onError) {
  25078. _this.onError(_this);
  25079. }
  25080. onError();
  25081. });
  25082. };
  25083. return MeshAssetTask;
  25084. })();
  25085. BABYLON.MeshAssetTask = MeshAssetTask;
  25086. var TextFileAssetTask = (function () {
  25087. function TextFileAssetTask(name, url) {
  25088. this.name = name;
  25089. this.url = url;
  25090. this.isCompleted = false;
  25091. }
  25092. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25093. var _this = this;
  25094. BABYLON.Tools.LoadFile(this.url, function (data) {
  25095. _this.text = data;
  25096. _this.isCompleted = true;
  25097. if (_this.onSuccess) {
  25098. _this.onSuccess(_this);
  25099. }
  25100. onSuccess();
  25101. }, null, scene.database, false, function () {
  25102. if (_this.onError) {
  25103. _this.onError(_this);
  25104. }
  25105. onError();
  25106. });
  25107. };
  25108. return TextFileAssetTask;
  25109. })();
  25110. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25111. var BinaryFileAssetTask = (function () {
  25112. function BinaryFileAssetTask(name, url) {
  25113. this.name = name;
  25114. this.url = url;
  25115. this.isCompleted = false;
  25116. }
  25117. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25118. var _this = this;
  25119. BABYLON.Tools.LoadFile(this.url, function (data) {
  25120. _this.data = data;
  25121. _this.isCompleted = true;
  25122. if (_this.onSuccess) {
  25123. _this.onSuccess(_this);
  25124. }
  25125. onSuccess();
  25126. }, null, scene.database, true, function () {
  25127. if (_this.onError) {
  25128. _this.onError(_this);
  25129. }
  25130. onError();
  25131. });
  25132. };
  25133. return BinaryFileAssetTask;
  25134. })();
  25135. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25136. var ImageAssetTask = (function () {
  25137. function ImageAssetTask(name, url) {
  25138. this.name = name;
  25139. this.url = url;
  25140. this.isCompleted = false;
  25141. }
  25142. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25143. var _this = this;
  25144. var img = new Image();
  25145. img.onload = function () {
  25146. _this.image = img;
  25147. _this.isCompleted = true;
  25148. if (_this.onSuccess) {
  25149. _this.onSuccess(_this);
  25150. }
  25151. onSuccess();
  25152. };
  25153. img.onerror = function () {
  25154. if (_this.onError) {
  25155. _this.onError(_this);
  25156. }
  25157. onError();
  25158. };
  25159. img.src = this.url;
  25160. };
  25161. return ImageAssetTask;
  25162. })();
  25163. BABYLON.ImageAssetTask = ImageAssetTask;
  25164. var TextureAssetTask = (function () {
  25165. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25167. this.name = name;
  25168. this.url = url;
  25169. this.noMipmap = noMipmap;
  25170. this.invertY = invertY;
  25171. this.samplingMode = samplingMode;
  25172. this.isCompleted = false;
  25173. }
  25174. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25175. var _this = this;
  25176. var onload = function () {
  25177. _this.isCompleted = true;
  25178. if (_this.onSuccess) {
  25179. _this.onSuccess(_this);
  25180. }
  25181. onSuccess();
  25182. };
  25183. var onerror = function () {
  25184. if (_this.onError) {
  25185. _this.onError(_this);
  25186. }
  25187. onError();
  25188. };
  25189. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25190. };
  25191. return TextureAssetTask;
  25192. })();
  25193. BABYLON.TextureAssetTask = TextureAssetTask;
  25194. var AssetsManager = (function () {
  25195. function AssetsManager(scene) {
  25196. this._tasks = new Array();
  25197. this._waitingTasksCount = 0;
  25198. this.useDefaultLoadingScreen = true;
  25199. this._scene = scene;
  25200. }
  25201. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25202. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25203. this._tasks.push(task);
  25204. return task;
  25205. };
  25206. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25207. var task = new TextFileAssetTask(taskName, url);
  25208. this._tasks.push(task);
  25209. return task;
  25210. };
  25211. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25212. var task = new BinaryFileAssetTask(taskName, url);
  25213. this._tasks.push(task);
  25214. return task;
  25215. };
  25216. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25217. var task = new ImageAssetTask(taskName, url);
  25218. this._tasks.push(task);
  25219. return task;
  25220. };
  25221. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25223. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25224. this._tasks.push(task);
  25225. return task;
  25226. };
  25227. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25228. this._waitingTasksCount--;
  25229. if (this._waitingTasksCount === 0) {
  25230. if (this.onFinish) {
  25231. this.onFinish(this._tasks);
  25232. }
  25233. this._scene.getEngine().hideLoadingUI();
  25234. }
  25235. };
  25236. AssetsManager.prototype._runTask = function (task) {
  25237. var _this = this;
  25238. task.run(this._scene, function () {
  25239. if (_this.onTaskSuccess) {
  25240. _this.onTaskSuccess(task);
  25241. }
  25242. _this._decreaseWaitingTasksCount();
  25243. }, function () {
  25244. if (_this.onTaskError) {
  25245. _this.onTaskError(task);
  25246. }
  25247. _this._decreaseWaitingTasksCount();
  25248. });
  25249. };
  25250. AssetsManager.prototype.reset = function () {
  25251. this._tasks = new Array();
  25252. return this;
  25253. };
  25254. AssetsManager.prototype.load = function () {
  25255. this._waitingTasksCount = this._tasks.length;
  25256. if (this._waitingTasksCount === 0) {
  25257. if (this.onFinish) {
  25258. this.onFinish(this._tasks);
  25259. }
  25260. return this;
  25261. }
  25262. if (this.useDefaultLoadingScreen) {
  25263. this._scene.getEngine().displayLoadingUI();
  25264. }
  25265. for (var index = 0; index < this._tasks.length; index++) {
  25266. var task = this._tasks[index];
  25267. this._runTask(task);
  25268. }
  25269. return this;
  25270. };
  25271. return AssetsManager;
  25272. })();
  25273. BABYLON.AssetsManager = AssetsManager;
  25274. })(BABYLON || (BABYLON = {}));
  25275. //# sourceMappingURL=babylon.assetsManager.js.map
  25276. var BABYLON;
  25277. (function (BABYLON) {
  25278. var VRDeviceOrientationCamera = (function (_super) {
  25279. __extends(VRDeviceOrientationCamera, _super);
  25280. function VRDeviceOrientationCamera(name, position, scene) {
  25281. _super.call(this, name, position, scene);
  25282. this._alpha = 0;
  25283. this._beta = 0;
  25284. this._gamma = 0;
  25285. }
  25286. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25287. this._alpha = +evt.alpha | 0;
  25288. this._beta = +evt.beta | 0;
  25289. this._gamma = +evt.gamma | 0;
  25290. if (this._gamma < 0) {
  25291. this._gamma = 90 + this._gamma;
  25292. }
  25293. else {
  25294. // Incline it in the correct angle.
  25295. this._gamma = 270 - this._gamma;
  25296. }
  25297. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25298. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25299. this.rotation.z = this._beta / 180.0 * Math.PI;
  25300. };
  25301. return VRDeviceOrientationCamera;
  25302. })(BABYLON.OculusCamera);
  25303. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25304. })(BABYLON || (BABYLON = {}));
  25305. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25306. var BABYLON;
  25307. (function (BABYLON) {
  25308. var WebVRCamera = (function (_super) {
  25309. __extends(WebVRCamera, _super);
  25310. function WebVRCamera(name, position, scene) {
  25311. _super.call(this, name, position, scene);
  25312. this._hmdDevice = null;
  25313. this._sensorDevice = null;
  25314. this._cacheState = null;
  25315. this._cacheQuaternion = new BABYLON.Quaternion();
  25316. this._cacheRotation = BABYLON.Vector3.Zero();
  25317. this._vrEnabled = false;
  25318. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25319. }
  25320. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25321. var size = devices.length;
  25322. var i = 0;
  25323. // Reset devices.
  25324. this._sensorDevice = null;
  25325. this._hmdDevice = null;
  25326. while (i < size && this._hmdDevice === null) {
  25327. if (devices[i] instanceof HMDVRDevice) {
  25328. this._hmdDevice = devices[i];
  25329. }
  25330. i++;
  25331. }
  25332. i = 0;
  25333. while (i < size && this._sensorDevice === null) {
  25334. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25335. this._sensorDevice = devices[i];
  25336. }
  25337. i++;
  25338. }
  25339. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25340. };
  25341. WebVRCamera.prototype._update = function () {
  25342. if (this._vrEnabled) {
  25343. this._cacheState = this._sensorDevice.getState();
  25344. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25345. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25346. this.rotation.x = -this._cacheRotation.z;
  25347. this.rotation.y = -this._cacheRotation.y;
  25348. this.rotation.z = this._cacheRotation.x;
  25349. }
  25350. _super.prototype._update.call(this);
  25351. };
  25352. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25353. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25354. if (navigator.getVRDevices) {
  25355. navigator.getVRDevices().then(this._getWebVRDevices);
  25356. }
  25357. else if (navigator.mozGetVRDevices) {
  25358. navigator.mozGetVRDevices(this._getWebVRDevices);
  25359. }
  25360. };
  25361. WebVRCamera.prototype.detachControl = function (element) {
  25362. _super.prototype.detachControl.call(this, element);
  25363. this._vrEnabled = false;
  25364. };
  25365. return WebVRCamera;
  25366. })(BABYLON.OculusCamera);
  25367. BABYLON.WebVRCamera = WebVRCamera;
  25368. })(BABYLON || (BABYLON = {}));
  25369. //# sourceMappingURL=babylon.webVRCamera.js.map
  25370. var BABYLON;
  25371. (function (BABYLON) {
  25372. // Standard optimizations
  25373. var SceneOptimization = (function () {
  25374. function SceneOptimization(priority) {
  25375. if (priority === void 0) { priority = 0; }
  25376. this.priority = priority;
  25377. this.apply = function (scene) {
  25378. return true; // Return true if everything that can be done was applied
  25379. };
  25380. }
  25381. return SceneOptimization;
  25382. })();
  25383. BABYLON.SceneOptimization = SceneOptimization;
  25384. var TextureOptimization = (function (_super) {
  25385. __extends(TextureOptimization, _super);
  25386. function TextureOptimization(priority, maximumSize) {
  25387. var _this = this;
  25388. if (priority === void 0) { priority = 0; }
  25389. if (maximumSize === void 0) { maximumSize = 1024; }
  25390. _super.call(this, priority);
  25391. this.priority = priority;
  25392. this.maximumSize = maximumSize;
  25393. this.apply = function (scene) {
  25394. var allDone = true;
  25395. for (var index = 0; index < scene.textures.length; index++) {
  25396. var texture = scene.textures[index];
  25397. if (!texture.canRescale) {
  25398. continue;
  25399. }
  25400. var currentSize = texture.getSize();
  25401. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25402. if (maxDimension > _this.maximumSize) {
  25403. texture.scale(0.5);
  25404. allDone = false;
  25405. }
  25406. }
  25407. return allDone;
  25408. };
  25409. }
  25410. return TextureOptimization;
  25411. })(SceneOptimization);
  25412. BABYLON.TextureOptimization = TextureOptimization;
  25413. var HardwareScalingOptimization = (function (_super) {
  25414. __extends(HardwareScalingOptimization, _super);
  25415. function HardwareScalingOptimization(priority, maximumScale) {
  25416. var _this = this;
  25417. if (priority === void 0) { priority = 0; }
  25418. if (maximumScale === void 0) { maximumScale = 2; }
  25419. _super.call(this, priority);
  25420. this.priority = priority;
  25421. this.maximumScale = maximumScale;
  25422. this._currentScale = 1;
  25423. this.apply = function (scene) {
  25424. _this._currentScale++;
  25425. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25426. return _this._currentScale >= _this.maximumScale;
  25427. };
  25428. }
  25429. return HardwareScalingOptimization;
  25430. })(SceneOptimization);
  25431. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25432. var ShadowsOptimization = (function (_super) {
  25433. __extends(ShadowsOptimization, _super);
  25434. function ShadowsOptimization() {
  25435. _super.apply(this, arguments);
  25436. this.apply = function (scene) {
  25437. scene.shadowsEnabled = false;
  25438. return true;
  25439. };
  25440. }
  25441. return ShadowsOptimization;
  25442. })(SceneOptimization);
  25443. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25444. var PostProcessesOptimization = (function (_super) {
  25445. __extends(PostProcessesOptimization, _super);
  25446. function PostProcessesOptimization() {
  25447. _super.apply(this, arguments);
  25448. this.apply = function (scene) {
  25449. scene.postProcessesEnabled = false;
  25450. return true;
  25451. };
  25452. }
  25453. return PostProcessesOptimization;
  25454. })(SceneOptimization);
  25455. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25456. var LensFlaresOptimization = (function (_super) {
  25457. __extends(LensFlaresOptimization, _super);
  25458. function LensFlaresOptimization() {
  25459. _super.apply(this, arguments);
  25460. this.apply = function (scene) {
  25461. scene.lensFlaresEnabled = false;
  25462. return true;
  25463. };
  25464. }
  25465. return LensFlaresOptimization;
  25466. })(SceneOptimization);
  25467. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25468. var ParticlesOptimization = (function (_super) {
  25469. __extends(ParticlesOptimization, _super);
  25470. function ParticlesOptimization() {
  25471. _super.apply(this, arguments);
  25472. this.apply = function (scene) {
  25473. scene.particlesEnabled = false;
  25474. return true;
  25475. };
  25476. }
  25477. return ParticlesOptimization;
  25478. })(SceneOptimization);
  25479. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25480. var RenderTargetsOptimization = (function (_super) {
  25481. __extends(RenderTargetsOptimization, _super);
  25482. function RenderTargetsOptimization() {
  25483. _super.apply(this, arguments);
  25484. this.apply = function (scene) {
  25485. scene.renderTargetsEnabled = false;
  25486. return true;
  25487. };
  25488. }
  25489. return RenderTargetsOptimization;
  25490. })(SceneOptimization);
  25491. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25492. var MergeMeshesOptimization = (function (_super) {
  25493. __extends(MergeMeshesOptimization, _super);
  25494. function MergeMeshesOptimization() {
  25495. var _this = this;
  25496. _super.apply(this, arguments);
  25497. this._canBeMerged = function (abstractMesh) {
  25498. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25499. return false;
  25500. }
  25501. var mesh = abstractMesh;
  25502. if (!mesh.isVisible || !mesh.isEnabled()) {
  25503. return false;
  25504. }
  25505. if (mesh.instances.length > 0) {
  25506. return false;
  25507. }
  25508. if (mesh.skeleton || mesh.hasLODLevels) {
  25509. return false;
  25510. }
  25511. return true;
  25512. };
  25513. this.apply = function (scene) {
  25514. var globalPool = scene.meshes.slice(0);
  25515. var globalLength = globalPool.length;
  25516. for (var index = 0; index < globalLength; index++) {
  25517. var currentPool = new Array();
  25518. var current = globalPool[index];
  25519. // Checks
  25520. if (!_this._canBeMerged(current)) {
  25521. continue;
  25522. }
  25523. currentPool.push(current);
  25524. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25525. var otherMesh = globalPool[subIndex];
  25526. if (!_this._canBeMerged(otherMesh)) {
  25527. continue;
  25528. }
  25529. if (otherMesh.material !== current.material) {
  25530. continue;
  25531. }
  25532. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25533. continue;
  25534. }
  25535. currentPool.push(otherMesh);
  25536. globalLength--;
  25537. globalPool.splice(subIndex, 1);
  25538. subIndex--;
  25539. }
  25540. if (currentPool.length < 2) {
  25541. continue;
  25542. }
  25543. // Merge meshes
  25544. BABYLON.Mesh.MergeMeshes(currentPool);
  25545. }
  25546. return true;
  25547. };
  25548. }
  25549. return MergeMeshesOptimization;
  25550. })(SceneOptimization);
  25551. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25552. // Options
  25553. var SceneOptimizerOptions = (function () {
  25554. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25555. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25556. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25557. this.targetFrameRate = targetFrameRate;
  25558. this.trackerDuration = trackerDuration;
  25559. this.optimizations = new Array();
  25560. }
  25561. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25562. var result = new SceneOptimizerOptions(targetFrameRate);
  25563. var priority = 0;
  25564. result.optimizations.push(new MergeMeshesOptimization(priority));
  25565. result.optimizations.push(new ShadowsOptimization(priority));
  25566. result.optimizations.push(new LensFlaresOptimization(priority));
  25567. // Next priority
  25568. priority++;
  25569. result.optimizations.push(new PostProcessesOptimization(priority));
  25570. result.optimizations.push(new ParticlesOptimization(priority));
  25571. // Next priority
  25572. priority++;
  25573. result.optimizations.push(new TextureOptimization(priority, 1024));
  25574. return result;
  25575. };
  25576. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25577. var result = new SceneOptimizerOptions(targetFrameRate);
  25578. var priority = 0;
  25579. result.optimizations.push(new MergeMeshesOptimization(priority));
  25580. result.optimizations.push(new ShadowsOptimization(priority));
  25581. result.optimizations.push(new LensFlaresOptimization(priority));
  25582. // Next priority
  25583. priority++;
  25584. result.optimizations.push(new PostProcessesOptimization(priority));
  25585. result.optimizations.push(new ParticlesOptimization(priority));
  25586. // Next priority
  25587. priority++;
  25588. result.optimizations.push(new TextureOptimization(priority, 512));
  25589. // Next priority
  25590. priority++;
  25591. result.optimizations.push(new RenderTargetsOptimization(priority));
  25592. // Next priority
  25593. priority++;
  25594. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25595. return result;
  25596. };
  25597. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25598. var result = new SceneOptimizerOptions(targetFrameRate);
  25599. var priority = 0;
  25600. result.optimizations.push(new MergeMeshesOptimization(priority));
  25601. result.optimizations.push(new ShadowsOptimization(priority));
  25602. result.optimizations.push(new LensFlaresOptimization(priority));
  25603. // Next priority
  25604. priority++;
  25605. result.optimizations.push(new PostProcessesOptimization(priority));
  25606. result.optimizations.push(new ParticlesOptimization(priority));
  25607. // Next priority
  25608. priority++;
  25609. result.optimizations.push(new TextureOptimization(priority, 256));
  25610. // Next priority
  25611. priority++;
  25612. result.optimizations.push(new RenderTargetsOptimization(priority));
  25613. // Next priority
  25614. priority++;
  25615. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25616. return result;
  25617. };
  25618. return SceneOptimizerOptions;
  25619. })();
  25620. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25621. // Scene optimizer tool
  25622. var SceneOptimizer = (function () {
  25623. function SceneOptimizer() {
  25624. }
  25625. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25626. // TODO: add an epsilon
  25627. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25628. if (onSuccess) {
  25629. onSuccess();
  25630. }
  25631. return;
  25632. }
  25633. // Apply current level of optimizations
  25634. var allDone = true;
  25635. var noOptimizationApplied = true;
  25636. for (var index = 0; index < options.optimizations.length; index++) {
  25637. var optimization = options.optimizations[index];
  25638. if (optimization.priority === currentPriorityLevel) {
  25639. noOptimizationApplied = false;
  25640. allDone = allDone && optimization.apply(scene);
  25641. }
  25642. }
  25643. // If no optimization was applied, this is a failure :(
  25644. if (noOptimizationApplied) {
  25645. if (onFailure) {
  25646. onFailure();
  25647. }
  25648. return;
  25649. }
  25650. // If all optimizations were done, move to next level
  25651. if (allDone) {
  25652. currentPriorityLevel++;
  25653. }
  25654. // Let's the system running for a specific amount of time before checking FPS
  25655. scene.executeWhenReady(function () {
  25656. setTimeout(function () {
  25657. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25658. }, options.trackerDuration);
  25659. });
  25660. };
  25661. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25662. if (!options) {
  25663. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25664. }
  25665. // Let's the system running for a specific amount of time before checking FPS
  25666. scene.executeWhenReady(function () {
  25667. setTimeout(function () {
  25668. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25669. }, options.trackerDuration);
  25670. });
  25671. };
  25672. return SceneOptimizer;
  25673. })();
  25674. BABYLON.SceneOptimizer = SceneOptimizer;
  25675. })(BABYLON || (BABYLON = {}));
  25676. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25677. (function (BABYLON) {
  25678. var Internals;
  25679. (function (Internals) {
  25680. var MeshLODLevel = (function () {
  25681. function MeshLODLevel(distance, mesh) {
  25682. this.distance = distance;
  25683. this.mesh = mesh;
  25684. }
  25685. return MeshLODLevel;
  25686. })();
  25687. Internals.MeshLODLevel = MeshLODLevel;
  25688. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25689. })(BABYLON || (BABYLON = {}));
  25690. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25691. (function (BABYLON) {
  25692. var AudioEngine = (function () {
  25693. function AudioEngine() {
  25694. this.audioContext = null;
  25695. this.canUseWebAudio = false;
  25696. this.WarnedWebAudioUnsupported = false;
  25697. try {
  25698. if (typeof AudioContext !== 'undefined') {
  25699. this.audioContext = new AudioContext();
  25700. this.canUseWebAudio = true;
  25701. }
  25702. else if (typeof webkitAudioContext !== 'undefined') {
  25703. this.audioContext = new webkitAudioContext();
  25704. this.canUseWebAudio = true;
  25705. }
  25706. }
  25707. catch (e) {
  25708. this.canUseWebAudio = false;
  25709. BABYLON.Tools.Error("Web Audio: " + e.message);
  25710. }
  25711. // create a global volume gain node
  25712. if (this.canUseWebAudio) {
  25713. this.masterGain = this.audioContext.createGain();
  25714. this.masterGain.gain.value = 1;
  25715. this.masterGain.connect(this.audioContext.destination);
  25716. }
  25717. }
  25718. AudioEngine.prototype.dispose = function () {
  25719. if (this.canUseWebAudio) {
  25720. if (this._connectedAnalyser) {
  25721. this._connectedAnalyser.stopDebugCanvas();
  25722. this._connectedAnalyser.dispose();
  25723. this.masterGain.disconnect();
  25724. this.masterGain.connect(this.audioContext.destination);
  25725. this._connectedAnalyser = null;
  25726. }
  25727. this.masterGain.gain.value = 1;
  25728. }
  25729. this.WarnedWebAudioUnsupported = false;
  25730. };
  25731. AudioEngine.prototype.getGlobalVolume = function () {
  25732. if (this.canUseWebAudio) {
  25733. return this.masterGain.gain.value;
  25734. }
  25735. else {
  25736. return -1;
  25737. }
  25738. };
  25739. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25740. if (this.canUseWebAudio) {
  25741. this.masterGain.gain.value = newVolume;
  25742. }
  25743. };
  25744. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25745. if (this._connectedAnalyser) {
  25746. this._connectedAnalyser.stopDebugCanvas();
  25747. }
  25748. this._connectedAnalyser = analyser;
  25749. if (this.canUseWebAudio) {
  25750. this.masterGain.disconnect();
  25751. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25752. }
  25753. };
  25754. return AudioEngine;
  25755. })();
  25756. BABYLON.AudioEngine = AudioEngine;
  25757. })(BABYLON || (BABYLON = {}));
  25758. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25759. (function (BABYLON) {
  25760. var Sound = (function () {
  25761. /**
  25762. * Create a sound and attach it to a scene
  25763. * @param name Name of your sound
  25764. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25765. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25766. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25767. */
  25768. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25769. var _this = this;
  25770. this.autoplay = false;
  25771. this.loop = false;
  25772. this.useCustomAttenuation = false;
  25773. this.spatialSound = false;
  25774. this.refDistance = 1;
  25775. this.rolloffFactor = 1;
  25776. this.maxDistance = 100;
  25777. this.distanceModel = "linear";
  25778. this.panningModel = "HRTF";
  25779. this._playbackRate = 1;
  25780. this._startTime = 0;
  25781. this._startOffset = 0;
  25782. this._position = BABYLON.Vector3.Zero();
  25783. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25784. this._volume = 1;
  25785. this._isLoaded = false;
  25786. this._isReadyToPlay = false;
  25787. this._isPlaying = false;
  25788. this._isDirectional = false;
  25789. // Used if you'd like to create a directional sound.
  25790. // If not set, the sound will be omnidirectional
  25791. this._coneInnerAngle = 360;
  25792. this._coneOuterAngle = 360;
  25793. this._coneOuterGain = 0;
  25794. this.name = name;
  25795. this._scene = scene;
  25796. this._readyToPlayCallback = readyToPlayCallback;
  25797. // Default custom attenuation function is a linear attenuation
  25798. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25799. if (currentDistance < maxDistance) {
  25800. return currentVolume * (1 - currentDistance / maxDistance);
  25801. }
  25802. else {
  25803. return 0;
  25804. }
  25805. };
  25806. if (options) {
  25807. this.autoplay = options.autoplay || false;
  25808. this.loop = options.loop || false;
  25809. // if volume === 0, we need another way to check this option
  25810. if (options.volume !== undefined) {
  25811. this._volume = options.volume;
  25812. }
  25813. this.spatialSound = options.spatialSound || false;
  25814. this.maxDistance = options.maxDistance || 100;
  25815. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25816. this.rolloffFactor = options.rolloffFactor || 1;
  25817. this.refDistance = options.refDistance || 1;
  25818. this.distanceModel = options.distanceModel || "linear";
  25819. this.panningModel = options.panningModel || "HRTF";
  25820. this._playbackRate = options.playbackRate || 1;
  25821. }
  25822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25823. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25824. this._soundGain.gain.value = this._volume;
  25825. this._inputAudioNode = this._soundGain;
  25826. this._ouputAudioNode = this._soundGain;
  25827. if (this.spatialSound) {
  25828. this._createSpatialParameters();
  25829. }
  25830. this._scene.mainSoundTrack.AddSound(this);
  25831. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25832. if (urlOrArrayBuffer) {
  25833. // If it's an URL
  25834. if (typeof (urlOrArrayBuffer) === "string") {
  25835. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25836. _this._soundLoaded(data);
  25837. }, null, null, true);
  25838. }
  25839. else {
  25840. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25841. this._soundLoaded(urlOrArrayBuffer);
  25842. }
  25843. else {
  25844. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25845. }
  25846. }
  25847. }
  25848. }
  25849. else {
  25850. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  25851. this._scene.mainSoundTrack.AddSound(this);
  25852. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25853. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25854. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25855. }
  25856. }
  25857. }
  25858. Sound.prototype.dispose = function () {
  25859. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25860. if (this._isPlaying) {
  25861. this.stop();
  25862. }
  25863. this._isReadyToPlay = false;
  25864. if (this.soundTrackId === -1) {
  25865. this._scene.mainSoundTrack.RemoveSound(this);
  25866. }
  25867. else {
  25868. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25869. }
  25870. this._soundGain.disconnect();
  25871. this._soundSource.disconnect();
  25872. if (this._soundPanner) {
  25873. this._soundPanner.disconnect();
  25874. this._soundPanner = null;
  25875. }
  25876. this._audioBuffer = null;
  25877. this._soundGain = null;
  25878. this._soundSource = null;
  25879. if (this._connectedMesh) {
  25880. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25881. this._connectedMesh = null;
  25882. }
  25883. }
  25884. };
  25885. Sound.prototype._soundLoaded = function (audioData) {
  25886. var _this = this;
  25887. this._isLoaded = true;
  25888. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25889. _this._audioBuffer = buffer;
  25890. _this._isReadyToPlay = true;
  25891. if (_this.autoplay) {
  25892. _this.play();
  25893. }
  25894. if (_this._readyToPlayCallback) {
  25895. _this._readyToPlayCallback();
  25896. }
  25897. }, function (error) {
  25898. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25899. });
  25900. };
  25901. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25902. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25903. this._audioBuffer = audioBuffer;
  25904. this._isReadyToPlay = true;
  25905. }
  25906. };
  25907. Sound.prototype.updateOptions = function (options) {
  25908. if (options) {
  25909. this.loop = options.loop || this.loop;
  25910. this.maxDistance = options.maxDistance || this.maxDistance;
  25911. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25912. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25913. this.refDistance = options.refDistance || this.refDistance;
  25914. this.distanceModel = options.distanceModel || this.distanceModel;
  25915. this.panningModel = options.panningModel || this.panningModel;
  25916. this._playbackRate = options.playbackRate || this._playbackRate;
  25917. }
  25918. };
  25919. Sound.prototype._createSpatialParameters = function () {
  25920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25921. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25922. if (this.useCustomAttenuation) {
  25923. // Tricks to disable in a way embedded Web Audio attenuation
  25924. this._soundPanner.distanceModel = "linear";
  25925. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25926. this._soundPanner.refDistance = 1;
  25927. this._soundPanner.rolloffFactor = 1;
  25928. this._soundPanner.panningModel = "HRTF";
  25929. }
  25930. else {
  25931. this._soundPanner.distanceModel = this.distanceModel;
  25932. this._soundPanner.maxDistance = this.maxDistance;
  25933. this._soundPanner.refDistance = this.refDistance;
  25934. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25935. this._soundPanner.panningModel = this.panningModel;
  25936. }
  25937. this._soundPanner.connect(this._ouputAudioNode);
  25938. this._inputAudioNode = this._soundPanner;
  25939. }
  25940. };
  25941. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25942. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25943. this._ouputAudioNode.disconnect();
  25944. this._ouputAudioNode.connect(soundTrackAudioNode);
  25945. }
  25946. };
  25947. /**
  25948. * Transform this sound into a directional source
  25949. * @param coneInnerAngle Size of the inner cone in degree
  25950. * @param coneOuterAngle Size of the outer cone in degree
  25951. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25952. */
  25953. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25954. if (coneOuterAngle < coneInnerAngle) {
  25955. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25956. return;
  25957. }
  25958. this._coneInnerAngle = coneInnerAngle;
  25959. this._coneOuterAngle = coneOuterAngle;
  25960. this._coneOuterGain = coneOuterGain;
  25961. this._isDirectional = true;
  25962. if (this._isPlaying && this.loop) {
  25963. this.stop();
  25964. this.play();
  25965. }
  25966. };
  25967. Sound.prototype.setPosition = function (newPosition) {
  25968. this._position = newPosition;
  25969. if (this._isPlaying && this.spatialSound) {
  25970. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25971. }
  25972. };
  25973. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25974. this._localDirection = newLocalDirection;
  25975. if (this._connectedMesh && this._isPlaying) {
  25976. this._updateDirection();
  25977. }
  25978. };
  25979. Sound.prototype._updateDirection = function () {
  25980. var mat = this._connectedMesh.getWorldMatrix();
  25981. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25982. direction.normalize();
  25983. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25984. };
  25985. Sound.prototype.updateDistanceFromListener = function () {
  25986. if (this._connectedMesh && this.useCustomAttenuation) {
  25987. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25988. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25989. }
  25990. };
  25991. Sound.prototype.setAttenuationFunction = function (callback) {
  25992. this._customAttenuationFunction = callback;
  25993. };
  25994. /**
  25995. * Play the sound
  25996. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25997. */
  25998. Sound.prototype.play = function (time) {
  25999. if (this._isReadyToPlay) {
  26000. try {
  26001. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26002. if (!this._soundSource) {
  26003. if (this.spatialSound) {
  26004. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26005. if (this._isDirectional) {
  26006. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26007. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26008. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26009. if (this._connectedMesh) {
  26010. this._updateDirection();
  26011. }
  26012. else {
  26013. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26014. }
  26015. }
  26016. }
  26017. }
  26018. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26019. this._soundSource.buffer = this._audioBuffer;
  26020. this._soundSource.connect(this._inputAudioNode);
  26021. this._soundSource.loop = this.loop;
  26022. this._soundSource.playbackRate.value = this._playbackRate;
  26023. this._startTime = startTime;
  26024. if (this.onended) {
  26025. this._soundSource.onended = this.onended;
  26026. }
  26027. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  26028. this._isPlaying = true;
  26029. }
  26030. catch (ex) {
  26031. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26032. }
  26033. }
  26034. };
  26035. /**
  26036. * Stop the sound
  26037. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26038. */
  26039. Sound.prototype.stop = function (time) {
  26040. if (this._isPlaying) {
  26041. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26042. this._soundSource.stop(stopTime);
  26043. this._isPlaying = false;
  26044. }
  26045. };
  26046. Sound.prototype.pause = function () {
  26047. if (this._isPlaying) {
  26048. this._soundSource.stop(0);
  26049. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26050. }
  26051. };
  26052. Sound.prototype.setVolume = function (newVolume, time) {
  26053. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26054. if (time) {
  26055. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26056. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26057. }
  26058. else {
  26059. this._soundGain.gain.value = newVolume;
  26060. }
  26061. }
  26062. this._volume = newVolume;
  26063. };
  26064. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26065. this._playbackRate = newPlaybackRate;
  26066. if (this._isPlaying) {
  26067. this._soundSource.playbackRate.value = this._playbackRate;
  26068. }
  26069. };
  26070. Sound.prototype.getVolume = function () {
  26071. return this._volume;
  26072. };
  26073. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26074. var _this = this;
  26075. this._connectedMesh = meshToConnectTo;
  26076. if (!this.spatialSound) {
  26077. this._createSpatialParameters();
  26078. this.spatialSound = true;
  26079. if (this._isPlaying && this.loop) {
  26080. this.stop();
  26081. this.play();
  26082. }
  26083. }
  26084. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26085. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26086. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26087. };
  26088. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26089. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26090. if (this._isDirectional && this._isPlaying) {
  26091. this._updateDirection();
  26092. }
  26093. };
  26094. return Sound;
  26095. })();
  26096. BABYLON.Sound = Sound;
  26097. })(BABYLON || (BABYLON = {}));
  26098. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26099. (function (BABYLON) {
  26100. var SoundTrack = (function () {
  26101. function SoundTrack(scene, options) {
  26102. this.id = -1;
  26103. this._isMainTrack = false;
  26104. this._scene = scene;
  26105. this._audioEngine = BABYLON.Engine.audioEngine;
  26106. this.soundCollection = new Array();
  26107. if (this._audioEngine.canUseWebAudio) {
  26108. this._trackGain = this._audioEngine.audioContext.createGain();
  26109. this._trackGain.connect(this._audioEngine.masterGain);
  26110. if (options) {
  26111. if (options.volume) {
  26112. this._trackGain.gain.value = options.volume;
  26113. }
  26114. if (options.mainTrack) {
  26115. this._isMainTrack = options.mainTrack;
  26116. }
  26117. }
  26118. }
  26119. if (!this._isMainTrack) {
  26120. this._scene.soundTracks.push(this);
  26121. this.id = this._scene.soundTracks.length - 1;
  26122. }
  26123. }
  26124. SoundTrack.prototype.dispose = function () {
  26125. if (this._audioEngine.canUseWebAudio) {
  26126. if (this._connectedAnalyser) {
  26127. this._connectedAnalyser.stopDebugCanvas();
  26128. }
  26129. while (this.soundCollection.length) {
  26130. this.soundCollection[0].dispose();
  26131. }
  26132. this._trackGain.disconnect();
  26133. this._trackGain = null;
  26134. }
  26135. };
  26136. SoundTrack.prototype.AddSound = function (sound) {
  26137. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26138. sound.connectToSoundTrackAudioNode(this._trackGain);
  26139. }
  26140. if (sound.soundTrackId) {
  26141. if (sound.soundTrackId === -1) {
  26142. this._scene.mainSoundTrack.RemoveSound(sound);
  26143. }
  26144. else {
  26145. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26146. }
  26147. }
  26148. this.soundCollection.push(sound);
  26149. sound.soundTrackId = this.id;
  26150. };
  26151. SoundTrack.prototype.RemoveSound = function (sound) {
  26152. var index = this.soundCollection.indexOf(sound);
  26153. if (index !== -1) {
  26154. this.soundCollection.splice(index, 1);
  26155. }
  26156. };
  26157. SoundTrack.prototype.setVolume = function (newVolume) {
  26158. if (this._audioEngine.canUseWebAudio) {
  26159. this._trackGain.gain.value = newVolume;
  26160. }
  26161. };
  26162. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26163. if (this._connectedAnalyser) {
  26164. this._connectedAnalyser.stopDebugCanvas();
  26165. }
  26166. this._connectedAnalyser = analyser;
  26167. if (this._audioEngine.canUseWebAudio) {
  26168. this._trackGain.disconnect();
  26169. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26170. }
  26171. };
  26172. return SoundTrack;
  26173. })();
  26174. BABYLON.SoundTrack = SoundTrack;
  26175. })(BABYLON || (BABYLON = {}));
  26176. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26177. (function (BABYLON) {
  26178. var DebugLayer = (function () {
  26179. function DebugLayer(scene) {
  26180. var _this = this;
  26181. this._transformationMatrix = BABYLON.Matrix.Identity();
  26182. this._enabled = false;
  26183. this._labelsEnabled = false;
  26184. this._displayStatistics = true;
  26185. this._displayTree = false;
  26186. this._displayLogs = false;
  26187. this._identityMatrix = BABYLON.Matrix.Identity();
  26188. this.axisRatio = 0.02;
  26189. this.accentColor = "orange";
  26190. this._scene = scene;
  26191. this._syncPositions = function () {
  26192. var engine = _this._scene.getEngine();
  26193. var canvasRect = engine.getRenderingCanvasClientRect();
  26194. if (_this._showUI) {
  26195. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26196. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26197. _this._statsDiv.style.width = "400px";
  26198. _this._statsDiv.style.height = "auto";
  26199. _this._statsSubsetDiv.style.maxHeight = "240px";
  26200. _this._optionsDiv.style.left = "0px";
  26201. _this._optionsDiv.style.top = "10px";
  26202. _this._optionsDiv.style.width = "200px";
  26203. _this._optionsDiv.style.height = "auto";
  26204. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26205. _this._logDiv.style.left = "0px";
  26206. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26207. _this._logDiv.style.width = "600px";
  26208. _this._logDiv.style.height = "160px";
  26209. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26210. _this._treeDiv.style.top = "10px";
  26211. _this._treeDiv.style.width = "300px";
  26212. _this._treeDiv.style.height = "auto";
  26213. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26214. }
  26215. _this._globalDiv.style.left = canvasRect.left + "px";
  26216. _this._globalDiv.style.top = canvasRect.top + "px";
  26217. _this._drawingCanvas.style.left = "0px";
  26218. _this._drawingCanvas.style.top = "0px";
  26219. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26220. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26221. var devicePixelRatio = window.devicePixelRatio || 1;
  26222. var context = _this._drawingContext;
  26223. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26224. _this._ratio = devicePixelRatio / backingStoreRatio;
  26225. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26226. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26227. };
  26228. this._onCanvasClick = function (evt) {
  26229. _this._clickPosition = {
  26230. x: evt.clientX * _this._ratio,
  26231. y: evt.clientY * _this._ratio
  26232. };
  26233. };
  26234. this._syncData = function () {
  26235. if (_this._showUI) {
  26236. if (_this._displayStatistics) {
  26237. _this._displayStats();
  26238. _this._statsDiv.style.display = "";
  26239. }
  26240. else {
  26241. _this._statsDiv.style.display = "none";
  26242. }
  26243. if (_this._displayLogs) {
  26244. _this._logDiv.style.display = "";
  26245. }
  26246. else {
  26247. _this._logDiv.style.display = "none";
  26248. }
  26249. if (_this._displayTree) {
  26250. _this._treeDiv.style.display = "";
  26251. if (_this._needToRefreshMeshesTree) {
  26252. _this._needToRefreshMeshesTree = false;
  26253. _this._refreshMeshesTreeContent();
  26254. }
  26255. }
  26256. else {
  26257. _this._treeDiv.style.display = "none";
  26258. }
  26259. }
  26260. if (_this._labelsEnabled || !_this._showUI) {
  26261. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26262. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26263. var engine = _this._scene.getEngine();
  26264. var viewport = _this._camera.viewport;
  26265. var globalViewport = viewport.toGlobal(engine);
  26266. // Meshes
  26267. var meshes = _this._scene.getActiveMeshes();
  26268. for (var index = 0; index < meshes.length; index++) {
  26269. var mesh = meshes.data[index];
  26270. var position = mesh.getBoundingInfo().boundingSphere.center;
  26271. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26272. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26273. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26274. }
  26275. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26276. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26277. mesh.renderOverlay = !mesh.renderOverlay;
  26278. }, function () {
  26279. return mesh.renderOverlay ? 'red' : 'black';
  26280. });
  26281. }
  26282. }
  26283. // Cameras
  26284. var cameras = _this._scene.cameras;
  26285. for (index = 0; index < cameras.length; index++) {
  26286. var camera = cameras[index];
  26287. if (camera === _this._camera) {
  26288. continue;
  26289. }
  26290. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26291. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26292. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26293. _this._camera.detachControl(engine.getRenderingCanvas());
  26294. _this._camera = camera;
  26295. _this._camera.attachControl(engine.getRenderingCanvas());
  26296. }, function () {
  26297. return "purple";
  26298. });
  26299. }
  26300. }
  26301. // Lights
  26302. var lights = _this._scene.lights;
  26303. for (index = 0; index < lights.length; index++) {
  26304. var light = lights[index];
  26305. if (light.position) {
  26306. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26307. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26308. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26309. light.setEnabled(!light.isEnabled());
  26310. }, function () {
  26311. return light.isEnabled() ? "orange" : "gray";
  26312. });
  26313. }
  26314. }
  26315. }
  26316. }
  26317. _this._clickPosition = undefined;
  26318. };
  26319. }
  26320. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26321. while (this._treeSubsetDiv.hasChildNodes()) {
  26322. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26323. }
  26324. // Add meshes
  26325. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26326. sortedArray.sort(function (a, b) {
  26327. if (a.name === b.name) {
  26328. return 0;
  26329. }
  26330. return (a.name > b.name) ? 1 : -1;
  26331. });
  26332. for (var index = 0; index < sortedArray.length; index++) {
  26333. var mesh = sortedArray[index];
  26334. if (!mesh.isEnabled()) {
  26335. continue;
  26336. }
  26337. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26338. m.isVisible = element.checked;
  26339. }, mesh);
  26340. }
  26341. };
  26342. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26343. this._drawingContext.beginPath();
  26344. this._drawingContext.moveTo(zero.x, zero.y);
  26345. this._drawingContext.lineTo(unit.x, unit.y);
  26346. this._drawingContext.strokeStyle = color;
  26347. this._drawingContext.lineWidth = 4;
  26348. this._drawingContext.stroke();
  26349. this._drawingContext.font = "normal 14px Segoe UI";
  26350. this._drawingContext.fillStyle = color;
  26351. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26352. };
  26353. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26354. var position = mesh.getBoundingInfo().boundingSphere.center;
  26355. var worldMatrix = mesh.getWorldMatrix();
  26356. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26357. var unit = (unprojectedVector.subtract(position)).length();
  26358. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26359. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26360. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26361. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26362. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26363. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26364. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26365. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26366. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26367. };
  26368. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26369. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26370. this._drawingContext.font = "normal 12px Segoe UI";
  26371. var textMetrics = this._drawingContext.measureText(text);
  26372. var centerX = projectedPosition.x - textMetrics.width / 2;
  26373. var centerY = projectedPosition.y;
  26374. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26375. if (this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26376. onClick();
  26377. }
  26378. this._drawingContext.beginPath();
  26379. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26380. this._drawingContext.fillStyle = getFillStyle();
  26381. this._drawingContext.globalAlpha = 0.5;
  26382. this._drawingContext.fill();
  26383. this._drawingContext.globalAlpha = 1.0;
  26384. this._drawingContext.strokeStyle = '#FFFFFF';
  26385. this._drawingContext.lineWidth = 1;
  26386. this._drawingContext.stroke();
  26387. this._drawingContext.fillStyle = "#FFFFFF";
  26388. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26389. this._drawingContext.beginPath();
  26390. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26391. this._drawingContext.fill();
  26392. }
  26393. };
  26394. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26395. if (!this._clickPosition) {
  26396. return false;
  26397. }
  26398. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26399. return false;
  26400. }
  26401. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26402. return false;
  26403. }
  26404. return true;
  26405. };
  26406. DebugLayer.prototype.isVisible = function () {
  26407. return this._enabled;
  26408. };
  26409. DebugLayer.prototype.hide = function () {
  26410. if (!this._enabled) {
  26411. return;
  26412. }
  26413. this._enabled = false;
  26414. var engine = this._scene.getEngine();
  26415. this._scene.unregisterAfterRender(this._syncData);
  26416. document.body.removeChild(this._globalDiv);
  26417. window.removeEventListener("resize", this._syncPositions);
  26418. this._scene.forceShowBoundingBoxes = false;
  26419. this._scene.forceWireframe = false;
  26420. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26421. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26422. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26423. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26424. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26425. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26426. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26427. this._scene.shadowsEnabled = true;
  26428. this._scene.particlesEnabled = true;
  26429. this._scene.postProcessesEnabled = true;
  26430. this._scene.collisionsEnabled = true;
  26431. this._scene.lightsEnabled = true;
  26432. this._scene.texturesEnabled = true;
  26433. this._scene.lensFlaresEnabled = true;
  26434. this._scene.proceduralTexturesEnabled = true;
  26435. this._scene.renderTargetsEnabled = true;
  26436. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26437. };
  26438. DebugLayer.prototype.show = function (showUI, camera) {
  26439. if (showUI === void 0) { showUI = true; }
  26440. if (camera === void 0) { camera = null; }
  26441. if (this._enabled) {
  26442. return;
  26443. }
  26444. if (camera) {
  26445. this._camera = camera;
  26446. }
  26447. else {
  26448. this._camera = this._scene.activeCamera;
  26449. }
  26450. this._enabled = true;
  26451. this._showUI = showUI;
  26452. var engine = this._scene.getEngine();
  26453. this._globalDiv = document.createElement("div");
  26454. document.body.appendChild(this._globalDiv);
  26455. this._generateDOMelements();
  26456. window.addEventListener("resize", this._syncPositions);
  26457. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26458. this._syncPositions();
  26459. this._scene.registerAfterRender(this._syncData);
  26460. };
  26461. DebugLayer.prototype._clearLabels = function () {
  26462. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26463. for (var index = 0; index < this._scene.meshes.length; index++) {
  26464. var mesh = this._scene.meshes[index];
  26465. mesh.renderOverlay = false;
  26466. }
  26467. };
  26468. DebugLayer.prototype._generateheader = function (root, text) {
  26469. var header = document.createElement("div");
  26470. header.innerHTML = text + "&nbsp;";
  26471. header.style.textAlign = "right";
  26472. header.style.width = "100%";
  26473. header.style.color = "white";
  26474. header.style.backgroundColor = "Black";
  26475. header.style.padding = "5px 5px 4px 0px";
  26476. header.style.marginLeft = "-5px";
  26477. header.style.fontWeight = "bold";
  26478. root.appendChild(header);
  26479. };
  26480. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26481. var label = document.createElement("label");
  26482. label.innerHTML = title;
  26483. label.style.color = color;
  26484. root.appendChild(label);
  26485. root.appendChild(document.createElement("br"));
  26486. };
  26487. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26488. if (tag === void 0) { tag = null; }
  26489. var label = document.createElement("label");
  26490. var boundingBoxesCheckbox = document.createElement("input");
  26491. boundingBoxesCheckbox.type = "checkbox";
  26492. boundingBoxesCheckbox.checked = initialState;
  26493. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26494. task(evt.target, tag);
  26495. });
  26496. label.appendChild(boundingBoxesCheckbox);
  26497. var container = document.createElement("span");
  26498. var leftPart = document.createElement("span");
  26499. var rightPart = document.createElement("span");
  26500. rightPart.style.cssFloat = "right";
  26501. leftPart.innerHTML = leftTitle;
  26502. rightPart.innerHTML = rightTitle;
  26503. rightPart.style.fontSize = "12px";
  26504. rightPart.style.maxWidth = "200px";
  26505. container.appendChild(leftPart);
  26506. container.appendChild(rightPart);
  26507. label.appendChild(container);
  26508. root.appendChild(label);
  26509. root.appendChild(document.createElement("br"));
  26510. };
  26511. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26512. if (tag === void 0) { tag = null; }
  26513. var label = document.createElement("label");
  26514. var boundingBoxesCheckbox = document.createElement("input");
  26515. boundingBoxesCheckbox.type = "checkbox";
  26516. boundingBoxesCheckbox.checked = initialState;
  26517. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26518. task(evt.target, tag);
  26519. });
  26520. label.appendChild(boundingBoxesCheckbox);
  26521. label.appendChild(document.createTextNode(title));
  26522. root.appendChild(label);
  26523. root.appendChild(document.createElement("br"));
  26524. };
  26525. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26526. if (tag === void 0) { tag = null; }
  26527. var label = document.createElement("label");
  26528. var boundingBoxesRadio = document.createElement("input");
  26529. boundingBoxesRadio.type = "radio";
  26530. boundingBoxesRadio.name = name;
  26531. boundingBoxesRadio.checked = initialState;
  26532. boundingBoxesRadio.addEventListener("change", function (evt) {
  26533. task(evt.target, tag);
  26534. });
  26535. label.appendChild(boundingBoxesRadio);
  26536. label.appendChild(document.createTextNode(title));
  26537. root.appendChild(label);
  26538. root.appendChild(document.createElement("br"));
  26539. };
  26540. DebugLayer.prototype._generateDOMelements = function () {
  26541. var _this = this;
  26542. this._globalDiv.id = "DebugLayer";
  26543. this._globalDiv.style.position = "absolute";
  26544. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26545. this._globalDiv.style.fontSize = "14px";
  26546. this._globalDiv.style.color = "white";
  26547. // Drawing canvas
  26548. this._drawingCanvas = document.createElement("canvas");
  26549. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26550. this._drawingCanvas.style.position = "absolute";
  26551. this._drawingCanvas.style.pointerEvents = "none";
  26552. this._drawingContext = this._drawingCanvas.getContext("2d");
  26553. this._globalDiv.appendChild(this._drawingCanvas);
  26554. if (this._showUI) {
  26555. var background = "rgba(128, 128, 128, 0.4)";
  26556. var border = "rgb(180, 180, 180) solid 1px";
  26557. // Stats
  26558. this._statsDiv = document.createElement("div");
  26559. this._statsDiv.id = "DebugLayerStats";
  26560. this._statsDiv.style.border = border;
  26561. this._statsDiv.style.position = "absolute";
  26562. this._statsDiv.style.background = background;
  26563. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26564. this._generateheader(this._statsDiv, "STATISTICS");
  26565. this._statsSubsetDiv = document.createElement("div");
  26566. this._statsSubsetDiv.style.paddingTop = "5px";
  26567. this._statsSubsetDiv.style.paddingBottom = "5px";
  26568. this._statsSubsetDiv.style.overflowY = "auto";
  26569. this._statsDiv.appendChild(this._statsSubsetDiv);
  26570. // Tree
  26571. this._treeDiv = document.createElement("div");
  26572. this._treeDiv.id = "DebugLayerTree";
  26573. this._treeDiv.style.border = border;
  26574. this._treeDiv.style.position = "absolute";
  26575. this._treeDiv.style.background = background;
  26576. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26577. this._treeDiv.style.display = "none";
  26578. this._generateheader(this._treeDiv, "MESHES TREE");
  26579. this._treeSubsetDiv = document.createElement("div");
  26580. this._treeSubsetDiv.style.paddingTop = "5px";
  26581. this._treeSubsetDiv.style.paddingRight = "5px";
  26582. this._treeSubsetDiv.style.overflowY = "auto";
  26583. this._treeSubsetDiv.style.maxHeight = "300px";
  26584. this._treeDiv.appendChild(this._treeSubsetDiv);
  26585. this._needToRefreshMeshesTree = true;
  26586. // Logs
  26587. this._logDiv = document.createElement("div");
  26588. this._logDiv.style.border = border;
  26589. this._logDiv.id = "DebugLayerLogs";
  26590. this._logDiv.style.position = "absolute";
  26591. this._logDiv.style.background = background;
  26592. this._logDiv.style.padding = "0px 0px 0px 5px";
  26593. this._logDiv.style.display = "none";
  26594. this._generateheader(this._logDiv, "LOGS");
  26595. this._logSubsetDiv = document.createElement("div");
  26596. this._logSubsetDiv.style.height = "127px";
  26597. this._logSubsetDiv.style.paddingTop = "5px";
  26598. this._logSubsetDiv.style.overflowY = "auto";
  26599. this._logSubsetDiv.style.fontSize = "12px";
  26600. this._logSubsetDiv.style.fontFamily = "consolas";
  26601. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26602. this._logDiv.appendChild(this._logSubsetDiv);
  26603. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26604. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26605. };
  26606. // Options
  26607. this._optionsDiv = document.createElement("div");
  26608. this._optionsDiv.id = "DebugLayerOptions";
  26609. this._optionsDiv.style.border = border;
  26610. this._optionsDiv.style.position = "absolute";
  26611. this._optionsDiv.style.background = background;
  26612. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26613. this._optionsDiv.style.overflowY = "auto";
  26614. this._generateheader(this._optionsDiv, "OPTIONS");
  26615. this._optionsSubsetDiv = document.createElement("div");
  26616. this._optionsSubsetDiv.style.paddingTop = "5px";
  26617. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26618. this._optionsSubsetDiv.style.overflowY = "auto";
  26619. this._optionsSubsetDiv.style.maxHeight = "200px";
  26620. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26621. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26622. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26623. _this._displayStatistics = element.checked;
  26624. });
  26625. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26626. _this._displayLogs = element.checked;
  26627. });
  26628. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26629. _this._displayTree = element.checked;
  26630. _this._needToRefreshMeshesTree = true;
  26631. });
  26632. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26633. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26634. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26635. _this._scene.forceShowBoundingBoxes = element.checked;
  26636. });
  26637. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26638. _this._labelsEnabled = element.checked;
  26639. if (!_this._labelsEnabled) {
  26640. _this._clearLabels();
  26641. }
  26642. });
  26643. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26644. if (element.checked) {
  26645. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26646. }
  26647. else {
  26648. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26649. }
  26650. });
  26651. ;
  26652. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26653. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26654. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26655. if (element.checked) {
  26656. _this._scene.forceWireframe = false;
  26657. _this._scene.forcePointsCloud = false;
  26658. }
  26659. });
  26660. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26661. if (element.checked) {
  26662. _this._scene.forceWireframe = true;
  26663. _this._scene.forcePointsCloud = false;
  26664. }
  26665. });
  26666. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26667. if (element.checked) {
  26668. _this._scene.forceWireframe = false;
  26669. _this._scene.forcePointsCloud = true;
  26670. }
  26671. });
  26672. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26673. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26674. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26675. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26676. });
  26677. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26678. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26679. });
  26680. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26681. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26682. });
  26683. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26684. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26685. });
  26686. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26687. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26688. });
  26689. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26690. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26691. });
  26692. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26693. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26694. });
  26695. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26696. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26697. });
  26698. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26699. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26700. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26701. _this._scene.animationsEnabled = element.checked;
  26702. });
  26703. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26704. _this._scene.collisionsEnabled = element.checked;
  26705. });
  26706. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26707. _this._scene.fogEnabled = element.checked;
  26708. });
  26709. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26710. _this._scene.lensFlaresEnabled = element.checked;
  26711. });
  26712. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26713. _this._scene.lightsEnabled = element.checked;
  26714. });
  26715. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26716. _this._scene.particlesEnabled = element.checked;
  26717. });
  26718. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26719. _this._scene.postProcessesEnabled = element.checked;
  26720. });
  26721. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26722. _this._scene.proceduralTexturesEnabled = element.checked;
  26723. });
  26724. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26725. _this._scene.renderTargetsEnabled = element.checked;
  26726. });
  26727. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26728. _this._scene.shadowsEnabled = element.checked;
  26729. });
  26730. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26731. _this._scene.skeletonsEnabled = element.checked;
  26732. });
  26733. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26734. _this._scene.texturesEnabled = element.checked;
  26735. });
  26736. this._globalDiv.appendChild(this._statsDiv);
  26737. this._globalDiv.appendChild(this._logDiv);
  26738. this._globalDiv.appendChild(this._optionsDiv);
  26739. this._globalDiv.appendChild(this._treeDiv);
  26740. }
  26741. };
  26742. DebugLayer.prototype._displayStats = function () {
  26743. var scene = this._scene;
  26744. var engine = scene.getEngine();
  26745. var glInfo = engine.getGlInfo();
  26746. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  26747. if (this.customStatsFunction) {
  26748. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26749. }
  26750. };
  26751. return DebugLayer;
  26752. })();
  26753. BABYLON.DebugLayer = DebugLayer;
  26754. })(BABYLON || (BABYLON = {}));
  26755. //# sourceMappingURL=babylon.debugLayer.js.map
  26756. var BABYLON;
  26757. (function (BABYLON) {
  26758. var RawTexture = (function (_super) {
  26759. __extends(RawTexture, _super);
  26760. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26761. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26762. if (invertY === void 0) { invertY = false; }
  26763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26764. _super.call(this, null, scene, !generateMipMaps, invertY);
  26765. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26766. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26767. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26768. }
  26769. // Statics
  26770. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26771. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26772. if (invertY === void 0) { invertY = false; }
  26773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26774. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26775. };
  26776. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26777. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26778. if (invertY === void 0) { invertY = false; }
  26779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26780. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26781. };
  26782. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26783. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26784. if (invertY === void 0) { invertY = false; }
  26785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26786. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26787. };
  26788. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26789. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26790. if (invertY === void 0) { invertY = false; }
  26791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26792. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26793. };
  26794. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26796. if (invertY === void 0) { invertY = false; }
  26797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26798. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26799. };
  26800. return RawTexture;
  26801. })(BABYLON.Texture);
  26802. BABYLON.RawTexture = RawTexture;
  26803. })(BABYLON || (BABYLON = {}));
  26804. //# sourceMappingURL=babylon.rawTexture.js.map
  26805. var BABYLON;
  26806. (function (BABYLON) {
  26807. var IndexedVector2 = (function (_super) {
  26808. __extends(IndexedVector2, _super);
  26809. function IndexedVector2(original, index) {
  26810. _super.call(this, original.x, original.y);
  26811. this.index = index;
  26812. }
  26813. return IndexedVector2;
  26814. })(BABYLON.Vector2);
  26815. var PolygonPoints = (function () {
  26816. function PolygonPoints() {
  26817. this.elements = new Array();
  26818. }
  26819. PolygonPoints.prototype.add = function (originalPoints) {
  26820. var _this = this;
  26821. var result = new Array();
  26822. originalPoints.forEach(function (point) {
  26823. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26824. var newPoint = new IndexedVector2(point, _this.elements.length);
  26825. result.push(newPoint);
  26826. _this.elements.push(newPoint);
  26827. }
  26828. });
  26829. return result;
  26830. };
  26831. PolygonPoints.prototype.computeBounds = function () {
  26832. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26833. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26834. this.elements.forEach(function (point) {
  26835. // x
  26836. if (point.x < lmin.x) {
  26837. lmin.x = point.x;
  26838. }
  26839. else if (point.x > lmax.x) {
  26840. lmax.x = point.x;
  26841. }
  26842. // y
  26843. if (point.y < lmin.y) {
  26844. lmin.y = point.y;
  26845. }
  26846. else if (point.y > lmax.y) {
  26847. lmax.y = point.y;
  26848. }
  26849. });
  26850. return {
  26851. min: lmin,
  26852. max: lmax,
  26853. width: lmax.x - lmin.x,
  26854. height: lmax.y - lmin.y
  26855. };
  26856. };
  26857. return PolygonPoints;
  26858. })();
  26859. var Polygon = (function () {
  26860. function Polygon() {
  26861. }
  26862. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26863. return [
  26864. new BABYLON.Vector2(xmin, ymin),
  26865. new BABYLON.Vector2(xmax, ymin),
  26866. new BABYLON.Vector2(xmax, ymax),
  26867. new BABYLON.Vector2(xmin, ymax)
  26868. ];
  26869. };
  26870. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26871. if (cx === void 0) { cx = 0; }
  26872. if (cy === void 0) { cy = 0; }
  26873. if (numberOfSides === void 0) { numberOfSides = 32; }
  26874. var result = new Array();
  26875. var angle = 0;
  26876. var increment = (Math.PI * 2) / numberOfSides;
  26877. for (var i = 0; i < numberOfSides; i++) {
  26878. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26879. angle -= increment;
  26880. }
  26881. return result;
  26882. };
  26883. Polygon.Parse = function (input) {
  26884. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26885. var i, result = [];
  26886. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26887. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26888. }
  26889. return result;
  26890. };
  26891. Polygon.StartingAt = function (x, y) {
  26892. return BABYLON.Path2.StartingAt(x, y);
  26893. };
  26894. return Polygon;
  26895. })();
  26896. BABYLON.Polygon = Polygon;
  26897. var PolygonMeshBuilder = (function () {
  26898. function PolygonMeshBuilder(name, contours, scene) {
  26899. this._points = new PolygonPoints();
  26900. if (!("poly2tri" in window)) {
  26901. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26902. }
  26903. this._name = name;
  26904. this._scene = scene;
  26905. var points;
  26906. if (contours instanceof BABYLON.Path2) {
  26907. points = contours.getPoints();
  26908. }
  26909. else {
  26910. points = contours;
  26911. }
  26912. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26913. }
  26914. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26915. this._swctx.addHole(this._points.add(hole));
  26916. return this;
  26917. };
  26918. PolygonMeshBuilder.prototype.build = function (updatable) {
  26919. if (updatable === void 0) { updatable = false; }
  26920. var result = new BABYLON.Mesh(this._name, this._scene);
  26921. var normals = [];
  26922. var positions = [];
  26923. var uvs = [];
  26924. var bounds = this._points.computeBounds();
  26925. this._points.elements.forEach(function (p) {
  26926. normals.push(0, 1.0, 0);
  26927. positions.push(p.x, 0, p.y);
  26928. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26929. });
  26930. var indices = [];
  26931. this._swctx.triangulate();
  26932. this._swctx.getTriangles().forEach(function (triangle) {
  26933. triangle.getPoints().forEach(function (point) {
  26934. indices.push(point.index);
  26935. });
  26936. });
  26937. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26938. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26939. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26940. result.setIndices(indices);
  26941. return result;
  26942. };
  26943. return PolygonMeshBuilder;
  26944. })();
  26945. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26946. })(BABYLON || (BABYLON = {}));
  26947. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26948. (function (BABYLON) {
  26949. var SimplificationSettings = (function () {
  26950. function SimplificationSettings(quality, distance) {
  26951. this.quality = quality;
  26952. this.distance = distance;
  26953. }
  26954. return SimplificationSettings;
  26955. })();
  26956. BABYLON.SimplificationSettings = SimplificationSettings;
  26957. /**
  26958. * The implemented types of simplification.
  26959. * At the moment only Quadratic Error Decimation is implemented.
  26960. */
  26961. (function (SimplificationType) {
  26962. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26963. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26964. var SimplificationType = BABYLON.SimplificationType;
  26965. var DecimationTriangle = (function () {
  26966. function DecimationTriangle(vertices) {
  26967. this.vertices = vertices;
  26968. this.error = new Array(4);
  26969. this.deleted = false;
  26970. this.isDirty = false;
  26971. this.borderFactor = 0;
  26972. }
  26973. return DecimationTriangle;
  26974. })();
  26975. BABYLON.DecimationTriangle = DecimationTriangle;
  26976. var DecimationVertex = (function () {
  26977. function DecimationVertex(position, normal, uv, id) {
  26978. this.position = position;
  26979. this.normal = normal;
  26980. this.uv = uv;
  26981. this.id = id;
  26982. this.isBorder = true;
  26983. this.q = new QuadraticMatrix();
  26984. this.triangleCount = 0;
  26985. this.triangleStart = 0;
  26986. }
  26987. return DecimationVertex;
  26988. })();
  26989. BABYLON.DecimationVertex = DecimationVertex;
  26990. var QuadraticMatrix = (function () {
  26991. function QuadraticMatrix(data) {
  26992. this.data = new Array(10);
  26993. for (var i = 0; i < 10; ++i) {
  26994. if (data && data[i]) {
  26995. this.data[i] = data[i];
  26996. }
  26997. else {
  26998. this.data[i] = 0;
  26999. }
  27000. }
  27001. }
  27002. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27003. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  27004. return det;
  27005. };
  27006. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27007. for (var i = 0; i < 10; ++i) {
  27008. this.data[i] += matrix.data[i];
  27009. }
  27010. };
  27011. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27012. for (var i = 0; i < 10; ++i) {
  27013. this.data[i] += data[i];
  27014. }
  27015. };
  27016. QuadraticMatrix.prototype.add = function (matrix) {
  27017. var m = new QuadraticMatrix();
  27018. for (var i = 0; i < 10; ++i) {
  27019. m.data[i] = this.data[i] + matrix.data[i];
  27020. }
  27021. return m;
  27022. };
  27023. QuadraticMatrix.FromData = function (a, b, c, d) {
  27024. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27025. };
  27026. //returning an array to avoid garbage collection
  27027. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27028. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27029. };
  27030. return QuadraticMatrix;
  27031. })();
  27032. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27033. var Reference = (function () {
  27034. function Reference(vertexId, triangleId) {
  27035. this.vertexId = vertexId;
  27036. this.triangleId = triangleId;
  27037. }
  27038. return Reference;
  27039. })();
  27040. BABYLON.Reference = Reference;
  27041. /**
  27042. * An implementation of the Quadratic Error simplification algorithm.
  27043. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27044. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27045. * @author RaananW
  27046. */
  27047. var QuadraticErrorSimplification = (function () {
  27048. function QuadraticErrorSimplification(_mesh) {
  27049. this._mesh = _mesh;
  27050. this.initialised = false;
  27051. this.syncIterations = 5000;
  27052. this.aggressiveness = 7;
  27053. this.decimationIterations = 100;
  27054. }
  27055. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27056. var _this = this;
  27057. this.initWithMesh(this._mesh, function () {
  27058. _this.runDecimation(settings, successCallback);
  27059. });
  27060. };
  27061. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  27062. var _this = this;
  27063. var targetCount = ~~(this.triangles.length * settings.quality);
  27064. var deletedTriangles = 0;
  27065. var triangleCount = this.triangles.length;
  27066. var iterationFunction = function (iteration, callback) {
  27067. setTimeout(function () {
  27068. if (iteration % 5 === 0) {
  27069. _this.updateMesh(iteration === 0);
  27070. }
  27071. for (var i = 0; i < _this.triangles.length; ++i) {
  27072. _this.triangles[i].isDirty = false;
  27073. }
  27074. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27075. var trianglesIterator = function (i) {
  27076. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27077. var t = _this.triangles[tIdx];
  27078. if (!t)
  27079. return;
  27080. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27081. return;
  27082. }
  27083. for (var j = 0; j < 3; ++j) {
  27084. if (t.error[j] < threshold) {
  27085. var deleted0 = [];
  27086. var deleted1 = [];
  27087. var i0 = t.vertices[j];
  27088. var i1 = t.vertices[(j + 1) % 3];
  27089. var v0 = _this.vertices[i0];
  27090. var v1 = _this.vertices[i1];
  27091. if (v0.isBorder !== v1.isBorder)
  27092. continue;
  27093. var p = BABYLON.Vector3.Zero();
  27094. var n = BABYLON.Vector3.Zero();
  27095. var uv = BABYLON.Vector2.Zero();
  27096. var color = new BABYLON.Color4(0, 0, 0, 1);
  27097. _this.calculateError(v0, v1, p, n, uv, color);
  27098. var delTr = [];
  27099. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27100. continue;
  27101. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27102. continue;
  27103. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27104. continue;
  27105. }
  27106. v0.normal = n;
  27107. if (v0.uv)
  27108. v0.uv = uv;
  27109. else if (v0.color)
  27110. v0.color = color;
  27111. v0.q = v1.q.add(v0.q);
  27112. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27113. continue;
  27114. if (p.equals(v0.position))
  27115. continue;
  27116. v0.position = p;
  27117. var tStart = _this.references.length;
  27118. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27119. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27120. var tCount = _this.references.length - tStart;
  27121. if (tCount <= v0.triangleCount) {
  27122. if (tCount) {
  27123. for (var c = 0; c < tCount; c++) {
  27124. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27125. }
  27126. }
  27127. }
  27128. else {
  27129. v0.triangleStart = tStart;
  27130. }
  27131. v0.triangleCount = tCount;
  27132. break;
  27133. }
  27134. }
  27135. };
  27136. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27137. return (triangleCount - deletedTriangles <= targetCount);
  27138. });
  27139. }, 0);
  27140. };
  27141. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27142. if (triangleCount - deletedTriangles <= targetCount)
  27143. loop.breakLoop();
  27144. else {
  27145. iterationFunction(loop.index, function () {
  27146. loop.executeNext();
  27147. });
  27148. }
  27149. }, function () {
  27150. setTimeout(function () {
  27151. successCallback(_this.reconstructMesh());
  27152. }, 0);
  27153. });
  27154. };
  27155. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27156. var _this = this;
  27157. if (!mesh)
  27158. return;
  27159. this.vertices = [];
  27160. this.triangles = [];
  27161. this._mesh = mesh;
  27162. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27163. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27164. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27165. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27166. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27167. var indices = mesh.getIndices();
  27168. var vertexInit = function (i) {
  27169. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27170. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27171. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27172. }
  27173. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27174. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27175. }
  27176. _this.vertices.push(vertex);
  27177. };
  27178. var totalVertices = mesh.getTotalVertices();
  27179. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27180. var indicesInit = function (i) {
  27181. var pos = i * 3;
  27182. var i0 = indices[pos + 0];
  27183. var i1 = indices[pos + 1];
  27184. var i2 = indices[pos + 2];
  27185. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27186. _this.triangles.push(triangle);
  27187. };
  27188. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27189. _this.init(callback);
  27190. });
  27191. });
  27192. };
  27193. QuadraticErrorSimplification.prototype.init = function (callback) {
  27194. var _this = this;
  27195. var triangleInit1 = function (i) {
  27196. var t = _this.triangles[i];
  27197. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  27198. for (var j = 0; j < 3; j++) {
  27199. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  27200. }
  27201. };
  27202. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27203. var triangleInit2 = function (i) {
  27204. var t = _this.triangles[i];
  27205. for (var j = 0; j < 3; ++j) {
  27206. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27207. }
  27208. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27209. };
  27210. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27211. _this.initialised = true;
  27212. callback();
  27213. });
  27214. });
  27215. };
  27216. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27217. var newTriangles = [];
  27218. var i;
  27219. for (i = 0; i < this.vertices.length; ++i) {
  27220. this.vertices[i].triangleCount = 0;
  27221. }
  27222. var t;
  27223. var j;
  27224. for (i = 0; i < this.triangles.length; ++i) {
  27225. if (!this.triangles[i].deleted) {
  27226. t = this.triangles[i];
  27227. for (j = 0; j < 3; ++j) {
  27228. this.vertices[t.vertices[j]].triangleCount = 1;
  27229. }
  27230. newTriangles.push(t);
  27231. }
  27232. }
  27233. var newVerticesOrder = [];
  27234. //compact vertices, get the IDs of the vertices used.
  27235. var dst = 0;
  27236. for (i = 0; i < this.vertices.length; ++i) {
  27237. if (this.vertices[i].triangleCount) {
  27238. this.vertices[i].triangleStart = dst;
  27239. this.vertices[dst].position = this.vertices[i].position;
  27240. this.vertices[dst].normal = this.vertices[i].normal;
  27241. this.vertices[dst].uv = this.vertices[i].uv;
  27242. this.vertices[dst].color = this.vertices[i].color;
  27243. newVerticesOrder.push(i);
  27244. dst++;
  27245. }
  27246. }
  27247. for (i = 0; i < newTriangles.length; ++i) {
  27248. t = newTriangles[i];
  27249. for (j = 0; j < 3; ++j) {
  27250. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27251. }
  27252. }
  27253. this.vertices = this.vertices.slice(0, dst);
  27254. var newPositionData = [];
  27255. var newNormalData = [];
  27256. var newUVsData = [];
  27257. var newColorsData = [];
  27258. for (i = 0; i < newVerticesOrder.length; ++i) {
  27259. newPositionData.push(this.vertices[i].position.x);
  27260. newPositionData.push(this.vertices[i].position.y);
  27261. newPositionData.push(this.vertices[i].position.z);
  27262. newNormalData.push(this.vertices[i].normal.x);
  27263. newNormalData.push(this.vertices[i].normal.y);
  27264. newNormalData.push(this.vertices[i].normal.z);
  27265. if (this.vertices[i].uv) {
  27266. newUVsData.push(this.vertices[i].uv.x);
  27267. newUVsData.push(this.vertices[i].uv.y);
  27268. }
  27269. else if (this.vertices[i].color) {
  27270. newColorsData.push(this.vertices[i].color.r);
  27271. newColorsData.push(this.vertices[i].color.g);
  27272. newColorsData.push(this.vertices[i].color.b);
  27273. newColorsData.push(this.vertices[i].color.a);
  27274. }
  27275. }
  27276. var newIndicesArray = [];
  27277. for (i = 0; i < newTriangles.length; ++i) {
  27278. newIndicesArray.push(newTriangles[i].vertices[0]);
  27279. newIndicesArray.push(newTriangles[i].vertices[1]);
  27280. newIndicesArray.push(newTriangles[i].vertices[2]);
  27281. }
  27282. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27283. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27284. newMesh.material = this._mesh.material;
  27285. newMesh.parent = this._mesh.parent;
  27286. newMesh.setIndices(newIndicesArray);
  27287. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27288. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27289. if (newUVsData.length > 0)
  27290. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27291. if (newColorsData.length > 0)
  27292. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27293. //preparing the skeleton support
  27294. if (this._mesh.skeleton) {
  27295. }
  27296. return newMesh;
  27297. };
  27298. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27299. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27300. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27301. if (t.deleted)
  27302. continue;
  27303. var s = this.references[vertex1.triangleStart + i].vertexId;
  27304. var id1 = t.vertices[(s + 1) % 3];
  27305. var id2 = t.vertices[(s + 2) % 3];
  27306. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27307. deletedArray[i] = true;
  27308. delTr.push(t);
  27309. continue;
  27310. }
  27311. var d1 = this.vertices[id1].position.subtract(point);
  27312. d1 = d1.normalize();
  27313. var d2 = this.vertices[id2].position.subtract(point);
  27314. d2 = d2.normalize();
  27315. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27316. return true;
  27317. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27318. deletedArray[i] = false;
  27319. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27320. return true;
  27321. }
  27322. return false;
  27323. };
  27324. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27325. var newDeleted = deletedTriangles;
  27326. for (var i = 0; i < vertex.triangleCount; ++i) {
  27327. var ref = this.references[vertex.triangleStart + i];
  27328. var t = this.triangles[ref.triangleId];
  27329. if (t.deleted)
  27330. continue;
  27331. if (deletedArray[i]) {
  27332. t.deleted = true;
  27333. newDeleted++;
  27334. continue;
  27335. }
  27336. t.vertices[ref.vertexId] = vertexId;
  27337. t.isDirty = true;
  27338. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27339. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27340. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27341. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27342. this.references.push(ref);
  27343. }
  27344. return newDeleted;
  27345. };
  27346. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27347. for (var i = 0; i < this.vertices.length; ++i) {
  27348. var vCount = [];
  27349. var vId = [];
  27350. var v = this.vertices[i];
  27351. var j;
  27352. for (j = 0; j < v.triangleCount; ++j) {
  27353. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27354. for (var ii = 0; ii < 3; ii++) {
  27355. var ofs = 0;
  27356. var id = triangle.vertices[ii];
  27357. while (ofs < vCount.length) {
  27358. if (vId[ofs] === id)
  27359. break;
  27360. ++ofs;
  27361. }
  27362. if (ofs === vCount.length) {
  27363. vCount.push(1);
  27364. vId.push(id);
  27365. }
  27366. else {
  27367. vCount[ofs]++;
  27368. }
  27369. }
  27370. }
  27371. for (j = 0; j < vCount.length; ++j) {
  27372. if (vCount[j] === 1) {
  27373. this.vertices[vId[j]].isBorder = true;
  27374. }
  27375. else {
  27376. this.vertices[vId[j]].isBorder = false;
  27377. }
  27378. }
  27379. }
  27380. };
  27381. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27382. if (identifyBorders === void 0) { identifyBorders = false; }
  27383. var i;
  27384. if (!identifyBorders) {
  27385. var newTrianglesVector = [];
  27386. for (i = 0; i < this.triangles.length; ++i) {
  27387. if (!this.triangles[i].deleted) {
  27388. newTrianglesVector.push(this.triangles[i]);
  27389. }
  27390. }
  27391. this.triangles = newTrianglesVector;
  27392. }
  27393. for (i = 0; i < this.vertices.length; ++i) {
  27394. this.vertices[i].triangleCount = 0;
  27395. this.vertices[i].triangleStart = 0;
  27396. }
  27397. var t;
  27398. var j;
  27399. var v;
  27400. for (i = 0; i < this.triangles.length; ++i) {
  27401. t = this.triangles[i];
  27402. for (j = 0; j < 3; ++j) {
  27403. v = this.vertices[t.vertices[j]];
  27404. v.triangleCount++;
  27405. }
  27406. }
  27407. var tStart = 0;
  27408. for (i = 0; i < this.vertices.length; ++i) {
  27409. this.vertices[i].triangleStart = tStart;
  27410. tStart += this.vertices[i].triangleCount;
  27411. this.vertices[i].triangleCount = 0;
  27412. }
  27413. var newReferences = new Array(this.triangles.length * 3);
  27414. for (i = 0; i < this.triangles.length; ++i) {
  27415. t = this.triangles[i];
  27416. for (j = 0; j < 3; ++j) {
  27417. v = this.vertices[t.vertices[j]];
  27418. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27419. v.triangleCount++;
  27420. }
  27421. }
  27422. this.references = newReferences;
  27423. if (identifyBorders) {
  27424. this.identifyBorder();
  27425. }
  27426. };
  27427. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27428. var x = point.x;
  27429. var y = point.y;
  27430. var z = point.z;
  27431. 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 + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  27432. };
  27433. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27434. var q = vertex1.q.add(vertex2.q);
  27435. var border = vertex1.isBorder && vertex2.isBorder;
  27436. var error = 0;
  27437. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27438. if (qDet !== 0 && !border) {
  27439. if (!pointResult) {
  27440. pointResult = BABYLON.Vector3.Zero();
  27441. }
  27442. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27443. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27444. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27445. error = this.vertexError(q, pointResult);
  27446. //TODO this should be correctly calculated
  27447. if (normalResult) {
  27448. normalResult.copyFrom(vertex1.normal);
  27449. if (vertex1.uv)
  27450. uvResult.copyFrom(vertex1.uv);
  27451. else if (vertex1.color)
  27452. colorResult.copyFrom(vertex1.color);
  27453. }
  27454. }
  27455. else {
  27456. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27457. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27458. var error1 = this.vertexError(q, vertex1.position);
  27459. var error2 = this.vertexError(q, vertex2.position);
  27460. var error3 = this.vertexError(q, p3);
  27461. error = Math.min(error1, error2, error3);
  27462. if (error === error1) {
  27463. if (pointResult) {
  27464. pointResult.copyFrom(vertex1.position);
  27465. normalResult.copyFrom(vertex1.normal);
  27466. if (vertex1.uv)
  27467. uvResult.copyFrom(vertex1.uv);
  27468. else if (vertex1.color)
  27469. colorResult.copyFrom(vertex1.color);
  27470. }
  27471. }
  27472. else if (error === error2) {
  27473. if (pointResult) {
  27474. pointResult.copyFrom(vertex2.position);
  27475. normalResult.copyFrom(vertex2.normal);
  27476. if (vertex2.uv)
  27477. uvResult.copyFrom(vertex2.uv);
  27478. else if (vertex2.color)
  27479. colorResult.copyFrom(vertex2.color);
  27480. }
  27481. }
  27482. else {
  27483. if (pointResult) {
  27484. pointResult.copyFrom(p3);
  27485. normalResult.copyFrom(vertex1.normal);
  27486. if (vertex1.uv)
  27487. uvResult.copyFrom(vertex1.uv);
  27488. else if (vertex1.color)
  27489. colorResult.copyFrom(vertex1.color);
  27490. }
  27491. }
  27492. }
  27493. return error;
  27494. };
  27495. return QuadraticErrorSimplification;
  27496. })();
  27497. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27498. })(BABYLON || (BABYLON = {}));
  27499. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27500. (function (BABYLON) {
  27501. var Analyser = (function () {
  27502. function Analyser(scene) {
  27503. this.SMOOTHING = 0.75;
  27504. this.FFT_SIZE = 512;
  27505. this.BARGRAPHAMPLITUDE = 256;
  27506. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27507. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27508. this._scene = scene;
  27509. this._audioEngine = BABYLON.Engine.audioEngine;
  27510. if (this._audioEngine.canUseWebAudio) {
  27511. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27512. this._webAudioAnalyser.minDecibels = -140;
  27513. this._webAudioAnalyser.maxDecibels = 0;
  27514. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27515. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27516. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27517. }
  27518. }
  27519. Analyser.prototype.getFrequencyBinCount = function () {
  27520. if (this._audioEngine.canUseWebAudio) {
  27521. return this._webAudioAnalyser.frequencyBinCount;
  27522. }
  27523. else {
  27524. return 0;
  27525. }
  27526. };
  27527. Analyser.prototype.getByteFrequencyData = function () {
  27528. if (this._audioEngine.canUseWebAudio) {
  27529. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27530. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27531. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27532. }
  27533. return this._byteFreqs;
  27534. };
  27535. Analyser.prototype.getByteTimeDomainData = function () {
  27536. if (this._audioEngine.canUseWebAudio) {
  27537. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27538. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27539. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27540. }
  27541. return this._byteTime;
  27542. };
  27543. Analyser.prototype.getFloatFrequencyData = function () {
  27544. if (this._audioEngine.canUseWebAudio) {
  27545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27547. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27548. }
  27549. return this._floatFreqs;
  27550. };
  27551. Analyser.prototype.drawDebugCanvas = function () {
  27552. var _this = this;
  27553. if (this._audioEngine.canUseWebAudio) {
  27554. if (!this._debugCanvas) {
  27555. this._debugCanvas = document.createElement("canvas");
  27556. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27557. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27558. this._debugCanvas.style.position = "absolute";
  27559. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27560. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27561. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27562. document.body.appendChild(this._debugCanvas);
  27563. this._registerFunc = function () {
  27564. _this.drawDebugCanvas();
  27565. };
  27566. this._scene.registerBeforeRender(this._registerFunc);
  27567. }
  27568. if (this._registerFunc) {
  27569. var workingArray = this.getByteFrequencyData();
  27570. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27571. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27572. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27573. var value = workingArray[i];
  27574. var percent = value / this.BARGRAPHAMPLITUDE;
  27575. var height = this.DEBUGCANVASSIZE.height * percent;
  27576. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27577. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27578. var hue = i / this.getFrequencyBinCount() * 360;
  27579. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27580. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27581. }
  27582. }
  27583. }
  27584. };
  27585. Analyser.prototype.stopDebugCanvas = function () {
  27586. if (this._debugCanvas) {
  27587. this._scene.unregisterBeforeRender(this._registerFunc);
  27588. this._registerFunc = null;
  27589. document.body.removeChild(this._debugCanvas);
  27590. this._debugCanvas = null;
  27591. this._debugCanvasContext = null;
  27592. }
  27593. };
  27594. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27595. if (this._audioEngine.canUseWebAudio) {
  27596. inputAudioNode.connect(this._webAudioAnalyser);
  27597. this._webAudioAnalyser.connect(outputAudioNode);
  27598. }
  27599. };
  27600. Analyser.prototype.dispose = function () {
  27601. if (this._audioEngine.canUseWebAudio) {
  27602. this._webAudioAnalyser.disconnect();
  27603. }
  27604. };
  27605. return Analyser;
  27606. })();
  27607. BABYLON.Analyser = Analyser;
  27608. })(BABYLON || (BABYLON = {}));
  27609. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27610. (function (BABYLON) {
  27611. var DepthRenderer = (function () {
  27612. function DepthRenderer(scene, type) {
  27613. var _this = this;
  27614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27615. this._viewMatrix = BABYLON.Matrix.Zero();
  27616. this._projectionMatrix = BABYLON.Matrix.Zero();
  27617. this._transformMatrix = BABYLON.Matrix.Zero();
  27618. this._worldViewProjection = BABYLON.Matrix.Zero();
  27619. this._scene = scene;
  27620. var engine = scene.getEngine();
  27621. // Render target
  27622. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27623. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27624. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27625. this._depthMap.refreshRate = 1;
  27626. this._depthMap.renderParticles = false;
  27627. this._depthMap.renderList = null;
  27628. // Custom render function
  27629. var renderSubMesh = function (subMesh) {
  27630. var mesh = subMesh.getRenderingMesh();
  27631. var scene = _this._scene;
  27632. var engine = scene.getEngine();
  27633. // Culling
  27634. engine.setState(subMesh.getMaterial().backFaceCulling);
  27635. // Managing instances
  27636. var batch = mesh._getInstancesRenderList(subMesh._id);
  27637. if (batch.mustReturn) {
  27638. return;
  27639. }
  27640. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27641. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27642. engine.enableEffect(_this._effect);
  27643. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27644. var material = subMesh.getMaterial();
  27645. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27646. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27647. // Alpha test
  27648. if (material && material.needAlphaTesting()) {
  27649. var alphaTexture = material.getAlphaTestTexture();
  27650. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27651. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27652. }
  27653. // Bones
  27654. if (mesh.useBones) {
  27655. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27656. }
  27657. // Draw
  27658. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27659. }
  27660. };
  27661. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27662. var index;
  27663. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27664. renderSubMesh(opaqueSubMeshes.data[index]);
  27665. }
  27666. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27667. renderSubMesh(alphaTestSubMeshes.data[index]);
  27668. }
  27669. };
  27670. }
  27671. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27672. var defines = [];
  27673. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27674. var mesh = subMesh.getMesh();
  27675. var scene = mesh.getScene();
  27676. var material = subMesh.getMaterial();
  27677. // Alpha test
  27678. if (material && material.needAlphaTesting()) {
  27679. defines.push("#define ALPHATEST");
  27680. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27681. attribs.push(BABYLON.VertexBuffer.UVKind);
  27682. defines.push("#define UV1");
  27683. }
  27684. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27685. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27686. defines.push("#define UV2");
  27687. }
  27688. }
  27689. // Bones
  27690. if (mesh.useBones) {
  27691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27693. defines.push("#define BONES");
  27694. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27695. }
  27696. // Instances
  27697. if (useInstances) {
  27698. defines.push("#define INSTANCES");
  27699. attribs.push("world0");
  27700. attribs.push("world1");
  27701. attribs.push("world2");
  27702. attribs.push("world3");
  27703. }
  27704. // Get correct effect
  27705. var join = defines.join("\n");
  27706. if (this._cachedDefines !== join) {
  27707. this._cachedDefines = join;
  27708. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27709. }
  27710. return this._effect.isReady();
  27711. };
  27712. DepthRenderer.prototype.getDepthMap = function () {
  27713. return this._depthMap;
  27714. };
  27715. // Methods
  27716. DepthRenderer.prototype.dispose = function () {
  27717. this._depthMap.dispose();
  27718. };
  27719. return DepthRenderer;
  27720. })();
  27721. BABYLON.DepthRenderer = DepthRenderer;
  27722. })(BABYLON || (BABYLON = {}));
  27723. //# sourceMappingURL=babylon.depthRenderer.js.map
  27724. var BABYLON;
  27725. (function (BABYLON) {
  27726. var SSAORenderingPipeline = (function (_super) {
  27727. __extends(SSAORenderingPipeline, _super);
  27728. /**
  27729. * @constructor
  27730. * @param {string} name - The rendering pipeline name
  27731. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  27732. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  27733. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  27734. */
  27735. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27736. var _this = this;
  27737. _super.call(this, scene.getEngine(), name);
  27738. // Members
  27739. /**
  27740. * The PassPostProcess id in the pipeline that contains the original scene color
  27741. * @type {string}
  27742. */
  27743. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27744. /**
  27745. * The SSAO PostProcess id in the pipeline
  27746. * @type {string}
  27747. */
  27748. this.SSAORenderEffect = "SSAORenderEffect";
  27749. /**
  27750. * The horizontal blur PostProcess id in the pipeline
  27751. * @type {string}
  27752. */
  27753. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27754. /**
  27755. * The vertical blur PostProcess id in the pipeline
  27756. * @type {string}
  27757. */
  27758. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27759. /**
  27760. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  27761. * @type {string}
  27762. */
  27763. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27764. this._firstUpdate = true;
  27765. this._scene = scene;
  27766. // Set up assets
  27767. this._createRandomTexture();
  27768. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27769. var ssaoRatio = ratio.ssaoRatio || ratio;
  27770. var combineRatio = ratio.combineRatio || ratio;
  27771. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27772. this._createSSAOPostProcess(ssaoRatio);
  27773. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27774. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27775. this._createSSAOCombinePostProcess(combineRatio);
  27776. // Set up pipeline
  27777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27778. return _this._originalColorPostProcess;
  27779. }, true));
  27780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27781. return _this._ssaoPostProcess;
  27782. }, true));
  27783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27784. return _this._blurHPostProcess;
  27785. }, true));
  27786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27787. return _this._blurVPostProcess;
  27788. }, true));
  27789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27790. return _this._ssaoCombinePostProcess;
  27791. }, true));
  27792. // Finish
  27793. scene.postProcessRenderPipelineManager.addPipeline(this);
  27794. if (cameras)
  27795. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27796. }
  27797. // Public Methods
  27798. /**
  27799. * Returns the horizontal blur PostProcess
  27800. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  27801. */
  27802. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27803. return this._blurHPostProcess;
  27804. };
  27805. /**
  27806. * Returns the vertical blur PostProcess
  27807. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  27808. */
  27809. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27810. return this._blurVPostProcess;
  27811. };
  27812. /**
  27813. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  27814. */
  27815. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  27816. if (disableDepthRender === void 0) { disableDepthRender = false; }
  27817. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  27818. this._originalColorPostProcess = undefined;
  27819. this._ssaoPostProcess = undefined;
  27820. this._blurHPostProcess = undefined;
  27821. this._blurVPostProcess = undefined;
  27822. this._ssaoCombinePostProcess = undefined;
  27823. this._randomTexture.dispose();
  27824. if (disableDepthRender)
  27825. this._scene.disableDepthRenderer();
  27826. };
  27827. // Private Methods
  27828. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27829. var _this = this;
  27830. var sampleSphere = [
  27831. 0.5381,
  27832. 0.1856,
  27833. -0.4319,
  27834. 0.1379,
  27835. 0.2486,
  27836. 0.4430,
  27837. 0.3371,
  27838. 0.5679,
  27839. -0.0057,
  27840. -0.6999,
  27841. -0.0451,
  27842. -0.0019,
  27843. 0.0689,
  27844. -0.1598,
  27845. -0.8547,
  27846. 0.0560,
  27847. 0.0069,
  27848. -0.1843,
  27849. -0.0146,
  27850. 0.1402,
  27851. 0.0762,
  27852. 0.0100,
  27853. -0.1924,
  27854. -0.0344,
  27855. -0.3577,
  27856. -0.5301,
  27857. -0.4358,
  27858. -0.3169,
  27859. 0.1063,
  27860. 0.0158,
  27861. 0.0103,
  27862. -0.5869,
  27863. 0.0046,
  27864. -0.0897,
  27865. -0.4940,
  27866. 0.3287,
  27867. 0.7119,
  27868. -0.0154,
  27869. -0.0918,
  27870. -0.0533,
  27871. 0.0596,
  27872. -0.5411,
  27873. 0.0352,
  27874. -0.0631,
  27875. 0.5460,
  27876. -0.4776,
  27877. 0.2847,
  27878. -0.0271
  27879. ];
  27880. var samplesFactor = 1.0 / 16.0;
  27881. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27882. this._ssaoPostProcess.onApply = function (effect) {
  27883. if (_this._firstUpdate) {
  27884. effect.setArray3("sampleSphere", sampleSphere);
  27885. effect.setFloat("samplesFactor", samplesFactor);
  27886. effect.setFloat("randTextureTiles", 4.0 / ratio);
  27887. _this._firstUpdate = false;
  27888. }
  27889. effect.setTexture("textureSampler", _this._depthTexture);
  27890. effect.setTexture("randomSampler", _this._randomTexture);
  27891. };
  27892. };
  27893. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  27894. var _this = this;
  27895. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27896. this._ssaoCombinePostProcess.onApply = function (effect) {
  27897. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27898. };
  27899. };
  27900. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27901. var size = 512;
  27902. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27903. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27904. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27905. var context = this._randomTexture.getContext();
  27906. var rand = function (min, max) {
  27907. return Math.random() * (max - min) + min;
  27908. };
  27909. for (var x = 0; x < size; x++) {
  27910. for (var y = 0; y < size; y++) {
  27911. var randVector = BABYLON.Vector3.Zero();
  27912. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27913. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27914. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27915. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27916. context.fillRect(x, y, 1, 1);
  27917. }
  27918. }
  27919. this._randomTexture.update(false);
  27920. };
  27921. return SSAORenderingPipeline;
  27922. })(BABYLON.PostProcessRenderPipeline);
  27923. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27924. })(BABYLON || (BABYLON = {}));
  27925. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27926. var BABYLON;
  27927. (function (BABYLON) {
  27928. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  27929. var VolumetricLightScatteringPostProcess = (function (_super) {
  27930. __extends(VolumetricLightScatteringPostProcess, _super);
  27931. /**
  27932. * @constructor
  27933. * @param {string} name - The post-process name
  27934. * @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)
  27935. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  27936. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  27937. * @param {number} samples - The post-process quality, default 100
  27938. * @param {number} samplingMode - The post-process filtering mode
  27939. * @param {BABYLON.Engine} engine - The babylon engine
  27940. * @param {boolean} reusable - If the post-process is reusable
  27941. */
  27942. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  27943. var _this = this;
  27944. if (samples === void 0) { samples = 100; }
  27945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27946. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  27947. this._screenCoordinates = BABYLON.Vector2.Zero();
  27948. /**
  27949. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  27950. * @type {boolean}
  27951. */
  27952. this.useCustomMeshPosition = false;
  27953. /**
  27954. * If the post-process should inverse the light scattering direction
  27955. * @type {boolean}
  27956. */
  27957. this.invert = true;
  27958. /**
  27959. * Array containing the excluded meshes not rendered in the internal pass
  27960. */
  27961. this.excludedMeshes = new Array();
  27962. this.exposure = 0.3;
  27963. this.decay = 0.96815;
  27964. this.weight = 0.58767;
  27965. this.density = 0.926;
  27966. var scene = camera.getScene();
  27967. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27968. // Configure mesh
  27969. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  27970. // Configure
  27971. this._createPass(scene, ratio.passRatio || ratio);
  27972. this.onApply = function (effect) {
  27973. _this._updateMeshScreenCoordinates(scene);
  27974. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  27975. effect.setFloat("exposure", _this.exposure);
  27976. effect.setFloat("decay", _this.decay);
  27977. effect.setFloat("weight", _this.weight);
  27978. effect.setFloat("density", _this.density);
  27979. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  27980. };
  27981. }
  27982. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27983. var mesh = subMesh.getMesh();
  27984. var defines = [];
  27985. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27986. var material = subMesh.getMaterial();
  27987. // Render this.mesh as default
  27988. if (mesh === this.mesh) {
  27989. defines.push("#define BASIC_RENDER");
  27990. }
  27991. // Alpha test
  27992. if (material) {
  27993. if (material.needAlphaTesting() || mesh === this.mesh)
  27994. defines.push("#define ALPHATEST");
  27995. if (material.opacityTexture !== undefined)
  27996. defines.push("#define OPACITY");
  27997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27998. attribs.push(BABYLON.VertexBuffer.UVKind);
  27999. defines.push("#define UV1");
  28000. }
  28001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28003. defines.push("#define UV2");
  28004. }
  28005. }
  28006. // Bones
  28007. if (mesh.useBones) {
  28008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28010. defines.push("#define BONES");
  28011. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28012. }
  28013. // Instances
  28014. if (useInstances) {
  28015. defines.push("#define INSTANCES");
  28016. attribs.push("world0");
  28017. attribs.push("world1");
  28018. attribs.push("world2");
  28019. attribs.push("world3");
  28020. }
  28021. // Get correct effect
  28022. var join = defines.join("\n");
  28023. if (this._cachedDefines !== join) {
  28024. this._cachedDefines = join;
  28025. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28026. }
  28027. return this._volumetricLightScatteringPass.isReady();
  28028. };
  28029. /**
  28030. * Sets the new light position for light scattering effect
  28031. * @param {BABYLON.Vector3} The new custom light position
  28032. */
  28033. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28034. this._customMeshPosition = position;
  28035. };
  28036. /**
  28037. * Returns the light position for light scattering effect
  28038. * @return {BABYLON.Vector3} The custom light position
  28039. */
  28040. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28041. return this._customMeshPosition;
  28042. };
  28043. /**
  28044. * Disposes the internal assets and detaches the post-process from the camera
  28045. */
  28046. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28047. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28048. if (rttIndex !== -1) {
  28049. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28050. }
  28051. this._volumetricLightScatteringRTT.dispose();
  28052. _super.prototype.dispose.call(this, camera);
  28053. };
  28054. /**
  28055. * Returns the render target texture used by the post-process
  28056. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28057. */
  28058. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28059. return this._volumetricLightScatteringRTT;
  28060. };
  28061. // Private methods
  28062. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28063. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28064. return true;
  28065. }
  28066. return false;
  28067. };
  28068. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28069. var _this = this;
  28070. var engine = scene.getEngine();
  28071. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28072. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28073. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28074. this._volumetricLightScatteringRTT.renderList = null;
  28075. this._volumetricLightScatteringRTT.renderParticles = false;
  28076. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28077. // Custom render function for submeshes
  28078. var renderSubMesh = function (subMesh) {
  28079. var mesh = subMesh.getRenderingMesh();
  28080. if (_this._meshExcluded(mesh)) {
  28081. return;
  28082. }
  28083. var scene = mesh.getScene();
  28084. var engine = scene.getEngine();
  28085. // Culling
  28086. engine.setState(subMesh.getMaterial().backFaceCulling);
  28087. // Managing instances
  28088. var batch = mesh._getInstancesRenderList(subMesh._id);
  28089. if (batch.mustReturn) {
  28090. return;
  28091. }
  28092. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28093. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28094. engine.enableEffect(_this._volumetricLightScatteringPass);
  28095. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28096. var material = subMesh.getMaterial();
  28097. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28098. // Alpha test
  28099. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28100. var alphaTexture = material.getAlphaTestTexture();
  28101. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28102. if (_this.mesh.material && alphaTexture)
  28103. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28104. if (material.opacityTexture !== undefined)
  28105. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28106. }
  28107. // Bones
  28108. if (mesh.useBones) {
  28109. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28110. }
  28111. // Draw
  28112. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28113. }
  28114. };
  28115. // Render target texture callbacks
  28116. var savedSceneClearColor;
  28117. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28118. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28119. savedSceneClearColor = scene.clearColor;
  28120. scene.clearColor = sceneClearColor;
  28121. };
  28122. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28123. scene.clearColor = savedSceneClearColor;
  28124. };
  28125. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28126. var index;
  28127. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28128. renderSubMesh(opaqueSubMeshes.data[index]);
  28129. }
  28130. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28131. renderSubMesh(alphaTestSubMeshes.data[index]);
  28132. }
  28133. for (index = 0; index < transparentSubMeshes.length; index++) {
  28134. renderSubMesh(transparentSubMeshes.data[index]);
  28135. }
  28136. };
  28137. };
  28138. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28139. var transform = scene.getTransformMatrix();
  28140. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28141. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28142. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28143. if (this.invert)
  28144. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28145. };
  28146. // Static methods
  28147. /**
  28148. * Creates a default mesh for the Volumeric Light Scattering post-process
  28149. * @param {string} The mesh name
  28150. * @param {BABYLON.Scene} The scene where to create the mesh
  28151. * @return {BABYLON.Mesh} the default mesh
  28152. */
  28153. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28154. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28155. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28156. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28157. return mesh;
  28158. };
  28159. return VolumetricLightScatteringPostProcess;
  28160. })(BABYLON.PostProcess);
  28161. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28162. })(BABYLON || (BABYLON = {}));
  28163. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map