babylon.2.1-alpha.debug.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346
  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.multiplyToArraySIMD = function (other, result, offset) {
  1459. if (offset === void 0) { offset = 0; }
  1460. var tm = this.m;
  1461. var om = other.m;
  1462. var om0 = SIMD.float32x4.load(om, 0);
  1463. var om1 = SIMD.float32x4.load(om, 4);
  1464. var om2 = SIMD.float32x4.load(om, 8);
  1465. var om3 = SIMD.float32x4.load(om, 12);
  1466. var tm0 = SIMD.float32x4.load(tm, 0);
  1467. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1468. var tm1 = SIMD.float32x4.load(tm, 4);
  1469. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1470. var tm2 = SIMD.float32x4.load(tm, 8);
  1471. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1472. var tm3 = SIMD.float32x4.load(tm, 12);
  1473. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1474. };
  1475. Matrix.prototype.equals = function (value) {
  1476. 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]);
  1477. };
  1478. Matrix.prototype.clone = function () {
  1479. 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]);
  1480. };
  1481. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1482. translation.x = this.m[12];
  1483. translation.y = this.m[13];
  1484. translation.z = this.m[14];
  1485. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1486. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1487. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1488. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1489. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1490. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1491. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1492. rotation.x = 0;
  1493. rotation.y = 0;
  1494. rotation.z = 0;
  1495. rotation.w = 1;
  1496. return false;
  1497. }
  1498. 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);
  1499. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1500. return true;
  1501. };
  1502. // Statics
  1503. Matrix.FromArray = function (array, offset) {
  1504. var result = new Matrix();
  1505. if (!offset) {
  1506. offset = 0;
  1507. }
  1508. Matrix.FromArrayToRef(array, offset, result);
  1509. return result;
  1510. };
  1511. Matrix.FromArrayToRef = function (array, offset, result) {
  1512. for (var index = 0; index < 16; index++) {
  1513. result.m[index] = array[index + offset];
  1514. }
  1515. };
  1516. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1517. result.m[0] = initialM11;
  1518. result.m[1] = initialM12;
  1519. result.m[2] = initialM13;
  1520. result.m[3] = initialM14;
  1521. result.m[4] = initialM21;
  1522. result.m[5] = initialM22;
  1523. result.m[6] = initialM23;
  1524. result.m[7] = initialM24;
  1525. result.m[8] = initialM31;
  1526. result.m[9] = initialM32;
  1527. result.m[10] = initialM33;
  1528. result.m[11] = initialM34;
  1529. result.m[12] = initialM41;
  1530. result.m[13] = initialM42;
  1531. result.m[14] = initialM43;
  1532. result.m[15] = initialM44;
  1533. };
  1534. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1535. var result = new Matrix();
  1536. result.m[0] = initialM11;
  1537. result.m[1] = initialM12;
  1538. result.m[2] = initialM13;
  1539. result.m[3] = initialM14;
  1540. result.m[4] = initialM21;
  1541. result.m[5] = initialM22;
  1542. result.m[6] = initialM23;
  1543. result.m[7] = initialM24;
  1544. result.m[8] = initialM31;
  1545. result.m[9] = initialM32;
  1546. result.m[10] = initialM33;
  1547. result.m[11] = initialM34;
  1548. result.m[12] = initialM41;
  1549. result.m[13] = initialM42;
  1550. result.m[14] = initialM43;
  1551. result.m[15] = initialM44;
  1552. return result;
  1553. };
  1554. Matrix.Compose = function (scale, rotation, translation) {
  1555. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1556. var rotationMatrix = Matrix.Identity();
  1557. rotation.toRotationMatrix(rotationMatrix);
  1558. result = result.multiply(rotationMatrix);
  1559. result.setTranslation(translation);
  1560. return result;
  1561. };
  1562. Matrix.Identity = function () {
  1563. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1564. };
  1565. Matrix.IdentityToRef = function (result) {
  1566. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1567. };
  1568. Matrix.Zero = function () {
  1569. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1570. };
  1571. Matrix.RotationX = function (angle) {
  1572. var result = new Matrix();
  1573. Matrix.RotationXToRef(angle, result);
  1574. return result;
  1575. };
  1576. Matrix.Invert = function (source) {
  1577. var result = new Matrix();
  1578. source.invertToRef(result);
  1579. return result;
  1580. };
  1581. Matrix.RotationXToRef = function (angle, result) {
  1582. var s = Math.sin(angle);
  1583. var c = Math.cos(angle);
  1584. result.m[0] = 1.0;
  1585. result.m[15] = 1.0;
  1586. result.m[5] = c;
  1587. result.m[10] = c;
  1588. result.m[9] = -s;
  1589. result.m[6] = s;
  1590. result.m[1] = 0;
  1591. result.m[2] = 0;
  1592. result.m[3] = 0;
  1593. result.m[4] = 0;
  1594. result.m[7] = 0;
  1595. result.m[8] = 0;
  1596. result.m[11] = 0;
  1597. result.m[12] = 0;
  1598. result.m[13] = 0;
  1599. result.m[14] = 0;
  1600. };
  1601. Matrix.RotationY = function (angle) {
  1602. var result = new Matrix();
  1603. Matrix.RotationYToRef(angle, result);
  1604. return result;
  1605. };
  1606. Matrix.RotationYToRef = function (angle, result) {
  1607. var s = Math.sin(angle);
  1608. var c = Math.cos(angle);
  1609. result.m[5] = 1.0;
  1610. result.m[15] = 1.0;
  1611. result.m[0] = c;
  1612. result.m[2] = -s;
  1613. result.m[8] = s;
  1614. result.m[10] = c;
  1615. result.m[1] = 0;
  1616. result.m[3] = 0;
  1617. result.m[4] = 0;
  1618. result.m[6] = 0;
  1619. result.m[7] = 0;
  1620. result.m[9] = 0;
  1621. result.m[11] = 0;
  1622. result.m[12] = 0;
  1623. result.m[13] = 0;
  1624. result.m[14] = 0;
  1625. };
  1626. Matrix.RotationZ = function (angle) {
  1627. var result = new Matrix();
  1628. Matrix.RotationZToRef(angle, result);
  1629. return result;
  1630. };
  1631. Matrix.RotationZToRef = function (angle, result) {
  1632. var s = Math.sin(angle);
  1633. var c = Math.cos(angle);
  1634. result.m[10] = 1.0;
  1635. result.m[15] = 1.0;
  1636. result.m[0] = c;
  1637. result.m[1] = s;
  1638. result.m[4] = -s;
  1639. result.m[5] = c;
  1640. result.m[2] = 0;
  1641. result.m[3] = 0;
  1642. result.m[6] = 0;
  1643. result.m[7] = 0;
  1644. result.m[8] = 0;
  1645. result.m[9] = 0;
  1646. result.m[11] = 0;
  1647. result.m[12] = 0;
  1648. result.m[13] = 0;
  1649. result.m[14] = 0;
  1650. };
  1651. Matrix.RotationAxis = function (axis, angle) {
  1652. var s = Math.sin(-angle);
  1653. var c = Math.cos(-angle);
  1654. var c1 = 1 - c;
  1655. axis.normalize();
  1656. var result = Matrix.Zero();
  1657. result.m[0] = (axis.x * axis.x) * c1 + c;
  1658. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1659. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1660. result.m[3] = 0.0;
  1661. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1662. result.m[5] = (axis.y * axis.y) * c1 + c;
  1663. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1664. result.m[7] = 0.0;
  1665. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1666. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1667. result.m[10] = (axis.z * axis.z) * c1 + c;
  1668. result.m[11] = 0.0;
  1669. result.m[15] = 1.0;
  1670. return result;
  1671. };
  1672. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1673. var result = new Matrix();
  1674. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1675. return result;
  1676. };
  1677. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1678. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1679. this._tempQuaternion.toRotationMatrix(result);
  1680. };
  1681. Matrix.Scaling = function (x, y, z) {
  1682. var result = Matrix.Zero();
  1683. Matrix.ScalingToRef(x, y, z, result);
  1684. return result;
  1685. };
  1686. Matrix.ScalingToRef = function (x, y, z, result) {
  1687. result.m[0] = x;
  1688. result.m[1] = 0;
  1689. result.m[2] = 0;
  1690. result.m[3] = 0;
  1691. result.m[4] = 0;
  1692. result.m[5] = y;
  1693. result.m[6] = 0;
  1694. result.m[7] = 0;
  1695. result.m[8] = 0;
  1696. result.m[9] = 0;
  1697. result.m[10] = z;
  1698. result.m[11] = 0;
  1699. result.m[12] = 0;
  1700. result.m[13] = 0;
  1701. result.m[14] = 0;
  1702. result.m[15] = 1.0;
  1703. };
  1704. Matrix.Translation = function (x, y, z) {
  1705. var result = Matrix.Identity();
  1706. Matrix.TranslationToRef(x, y, z, result);
  1707. return result;
  1708. };
  1709. Matrix.TranslationToRef = function (x, y, z, result) {
  1710. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1711. };
  1712. Matrix.LookAtLH = function (eye, target, up) {
  1713. var result = Matrix.Zero();
  1714. Matrix.LookAtLHToRef(eye, target, up, result);
  1715. return result;
  1716. };
  1717. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1718. // Z axis
  1719. target.subtractToRef(eye, this._zAxis);
  1720. this._zAxis.normalize();
  1721. // X axis
  1722. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1723. this._xAxis.normalize();
  1724. // Y axis
  1725. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1726. this._yAxis.normalize();
  1727. // Eye angles
  1728. var ex = -Vector3.Dot(this._xAxis, eye);
  1729. var ey = -Vector3.Dot(this._yAxis, eye);
  1730. var ez = -Vector3.Dot(this._zAxis, eye);
  1731. 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);
  1732. };
  1733. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1734. var matrix = Matrix.Zero();
  1735. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1736. return matrix;
  1737. };
  1738. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1739. var hw = 2.0 / width;
  1740. var hh = 2.0 / height;
  1741. var id = 1.0 / (zfar - znear);
  1742. var nid = znear / (znear - zfar);
  1743. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1744. };
  1745. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1748. return matrix;
  1749. };
  1750. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1751. result.m[0] = 2.0 / (right - left);
  1752. result.m[1] = result.m[2] = result.m[3] = 0;
  1753. result.m[5] = 2.0 / (top - bottom);
  1754. result.m[4] = result.m[6] = result.m[7] = 0;
  1755. result.m[10] = -1.0 / (znear - zfar);
  1756. result.m[8] = result.m[9] = result.m[11] = 0;
  1757. result.m[12] = (left + right) / (left - right);
  1758. result.m[13] = (top + bottom) / (bottom - top);
  1759. result.m[14] = znear / (znear - zfar);
  1760. result.m[15] = 1.0;
  1761. };
  1762. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1763. var matrix = Matrix.Zero();
  1764. matrix.m[0] = (2.0 * znear) / width;
  1765. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1766. matrix.m[5] = (2.0 * znear) / height;
  1767. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1768. matrix.m[10] = -zfar / (znear - zfar);
  1769. matrix.m[8] = matrix.m[9] = 0.0;
  1770. matrix.m[11] = 1.0;
  1771. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1772. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1773. return matrix;
  1774. };
  1775. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1776. var matrix = Matrix.Zero();
  1777. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1778. return matrix;
  1779. };
  1780. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1781. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1782. var tan = 1.0 / (Math.tan(fov * 0.5));
  1783. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1784. if (v_fixed) {
  1785. result.m[0] = tan / aspect;
  1786. }
  1787. else {
  1788. result.m[0] = tan;
  1789. }
  1790. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1791. if (v_fixed) {
  1792. result.m[5] = tan;
  1793. }
  1794. else {
  1795. result.m[5] = tan * aspect;
  1796. }
  1797. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1798. result.m[8] = result.m[9] = 0.0;
  1799. result.m[10] = -zfar / (znear - zfar);
  1800. result.m[11] = 1.0;
  1801. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1802. result.m[14] = (znear * zfar) / (znear - zfar);
  1803. };
  1804. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1805. var cw = viewport.width;
  1806. var ch = viewport.height;
  1807. var cx = viewport.x;
  1808. var cy = viewport.y;
  1809. 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);
  1810. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1811. };
  1812. Matrix.Transpose = function (matrix) {
  1813. var result = new Matrix();
  1814. result.m[0] = matrix.m[0];
  1815. result.m[1] = matrix.m[4];
  1816. result.m[2] = matrix.m[8];
  1817. result.m[3] = matrix.m[12];
  1818. result.m[4] = matrix.m[1];
  1819. result.m[5] = matrix.m[5];
  1820. result.m[6] = matrix.m[9];
  1821. result.m[7] = matrix.m[13];
  1822. result.m[8] = matrix.m[2];
  1823. result.m[9] = matrix.m[6];
  1824. result.m[10] = matrix.m[10];
  1825. result.m[11] = matrix.m[14];
  1826. result.m[12] = matrix.m[3];
  1827. result.m[13] = matrix.m[7];
  1828. result.m[14] = matrix.m[11];
  1829. result.m[15] = matrix.m[15];
  1830. return result;
  1831. };
  1832. Matrix.Reflection = function (plane) {
  1833. var matrix = new Matrix();
  1834. Matrix.ReflectionToRef(plane, matrix);
  1835. return matrix;
  1836. };
  1837. Matrix.ReflectionToRef = function (plane, result) {
  1838. plane.normalize();
  1839. var x = plane.normal.x;
  1840. var y = plane.normal.y;
  1841. var z = plane.normal.z;
  1842. var temp = -2 * x;
  1843. var temp2 = -2 * y;
  1844. var temp3 = -2 * z;
  1845. result.m[0] = (temp * x) + 1;
  1846. result.m[1] = temp2 * x;
  1847. result.m[2] = temp3 * x;
  1848. result.m[3] = 0.0;
  1849. result.m[4] = temp * y;
  1850. result.m[5] = (temp2 * y) + 1;
  1851. result.m[6] = temp3 * y;
  1852. result.m[7] = 0.0;
  1853. result.m[8] = temp * z;
  1854. result.m[9] = temp2 * z;
  1855. result.m[10] = (temp3 * z) + 1;
  1856. result.m[11] = 0.0;
  1857. result.m[12] = temp * plane.d;
  1858. result.m[13] = temp2 * plane.d;
  1859. result.m[14] = temp3 * plane.d;
  1860. result.m[15] = 1.0;
  1861. };
  1862. Matrix._tempQuaternion = new Quaternion();
  1863. Matrix._xAxis = Vector3.Zero();
  1864. Matrix._yAxis = Vector3.Zero();
  1865. Matrix._zAxis = Vector3.Zero();
  1866. return Matrix;
  1867. })();
  1868. BABYLON.Matrix = Matrix;
  1869. var Plane = (function () {
  1870. function Plane(a, b, c, d) {
  1871. this.normal = new Vector3(a, b, c);
  1872. this.d = d;
  1873. }
  1874. Plane.prototype.asArray = function () {
  1875. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1876. };
  1877. // Methods
  1878. Plane.prototype.clone = function () {
  1879. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1880. };
  1881. Plane.prototype.normalize = function () {
  1882. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1883. var magnitude = 0;
  1884. if (norm !== 0) {
  1885. magnitude = 1.0 / norm;
  1886. }
  1887. this.normal.x *= magnitude;
  1888. this.normal.y *= magnitude;
  1889. this.normal.z *= magnitude;
  1890. this.d *= magnitude;
  1891. return this;
  1892. };
  1893. Plane.prototype.transform = function (transformation) {
  1894. var transposedMatrix = Matrix.Transpose(transformation);
  1895. var x = this.normal.x;
  1896. var y = this.normal.y;
  1897. var z = this.normal.z;
  1898. var d = this.d;
  1899. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1900. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1901. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1902. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1903. return new Plane(normalX, normalY, normalZ, finalD);
  1904. };
  1905. Plane.prototype.dotCoordinate = function (point) {
  1906. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1907. };
  1908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1909. var x1 = point2.x - point1.x;
  1910. var y1 = point2.y - point1.y;
  1911. var z1 = point2.z - point1.z;
  1912. var x2 = point3.x - point1.x;
  1913. var y2 = point3.y - point1.y;
  1914. var z2 = point3.z - point1.z;
  1915. var yz = (y1 * z2) - (z1 * y2);
  1916. var xz = (z1 * x2) - (x1 * z2);
  1917. var xy = (x1 * y2) - (y1 * x2);
  1918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1919. var invPyth;
  1920. if (pyth !== 0) {
  1921. invPyth = 1.0 / pyth;
  1922. }
  1923. else {
  1924. invPyth = 0;
  1925. }
  1926. this.normal.x = yz * invPyth;
  1927. this.normal.y = xz * invPyth;
  1928. this.normal.z = xy * invPyth;
  1929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1930. return this;
  1931. };
  1932. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1933. var dot = Vector3.Dot(this.normal, direction);
  1934. return (dot <= epsilon);
  1935. };
  1936. Plane.prototype.signedDistanceTo = function (point) {
  1937. return Vector3.Dot(point, this.normal) + this.d;
  1938. };
  1939. // Statics
  1940. Plane.FromArray = function (array) {
  1941. return new Plane(array[0], array[1], array[2], array[3]);
  1942. };
  1943. Plane.FromPoints = function (point1, point2, point3) {
  1944. var result = new Plane(0, 0, 0, 0);
  1945. result.copyFromPoints(point1, point2, point3);
  1946. return result;
  1947. };
  1948. Plane.FromPositionAndNormal = function (origin, normal) {
  1949. var result = new Plane(0, 0, 0, 0);
  1950. normal.normalize();
  1951. result.normal = normal;
  1952. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1953. return result;
  1954. };
  1955. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1956. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1957. return Vector3.Dot(point, normal) + d;
  1958. };
  1959. return Plane;
  1960. })();
  1961. BABYLON.Plane = Plane;
  1962. var Viewport = (function () {
  1963. function Viewport(x, y, width, height) {
  1964. this.x = x;
  1965. this.y = y;
  1966. this.width = width;
  1967. this.height = height;
  1968. }
  1969. Viewport.prototype.toGlobal = function (engine) {
  1970. var width = engine.getRenderWidth();
  1971. var height = engine.getRenderHeight();
  1972. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1973. };
  1974. return Viewport;
  1975. })();
  1976. BABYLON.Viewport = Viewport;
  1977. var Frustum = (function () {
  1978. function Frustum() {
  1979. }
  1980. Frustum.GetPlanes = function (transform) {
  1981. var frustumPlanes = [];
  1982. for (var index = 0; index < 6; index++) {
  1983. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1984. }
  1985. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1986. return frustumPlanes;
  1987. };
  1988. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1989. // Near
  1990. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1991. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1992. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1993. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1994. frustumPlanes[0].normalize();
  1995. // Far
  1996. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1997. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1998. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1999. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2000. frustumPlanes[1].normalize();
  2001. // Left
  2002. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2003. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2004. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2005. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2006. frustumPlanes[2].normalize();
  2007. // Right
  2008. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2009. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2010. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2011. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2012. frustumPlanes[3].normalize();
  2013. // Top
  2014. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2015. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2016. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2017. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2018. frustumPlanes[4].normalize();
  2019. // Bottom
  2020. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2021. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2022. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2023. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2024. frustumPlanes[5].normalize();
  2025. };
  2026. return Frustum;
  2027. })();
  2028. BABYLON.Frustum = Frustum;
  2029. var Ray = (function () {
  2030. function Ray(origin, direction, length) {
  2031. if (length === void 0) { length = Number.MAX_VALUE; }
  2032. this.origin = origin;
  2033. this.direction = direction;
  2034. this.length = length;
  2035. }
  2036. // Methods
  2037. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2038. var d = 0.0;
  2039. var maxValue = Number.MAX_VALUE;
  2040. if (Math.abs(this.direction.x) < 0.0000001) {
  2041. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2042. return false;
  2043. }
  2044. }
  2045. else {
  2046. var inv = 1.0 / this.direction.x;
  2047. var min = (minimum.x - this.origin.x) * inv;
  2048. var max = (maximum.x - this.origin.x) * inv;
  2049. if (max === -Infinity) {
  2050. max = Infinity;
  2051. }
  2052. if (min > max) {
  2053. var temp = min;
  2054. min = max;
  2055. max = temp;
  2056. }
  2057. d = Math.max(min, d);
  2058. maxValue = Math.min(max, maxValue);
  2059. if (d > maxValue) {
  2060. return false;
  2061. }
  2062. }
  2063. if (Math.abs(this.direction.y) < 0.0000001) {
  2064. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2065. return false;
  2066. }
  2067. }
  2068. else {
  2069. inv = 1.0 / this.direction.y;
  2070. min = (minimum.y - this.origin.y) * inv;
  2071. max = (maximum.y - this.origin.y) * inv;
  2072. if (max === -Infinity) {
  2073. max = Infinity;
  2074. }
  2075. if (min > max) {
  2076. temp = min;
  2077. min = max;
  2078. max = temp;
  2079. }
  2080. d = Math.max(min, d);
  2081. maxValue = Math.min(max, maxValue);
  2082. if (d > maxValue) {
  2083. return false;
  2084. }
  2085. }
  2086. if (Math.abs(this.direction.z) < 0.0000001) {
  2087. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2088. return false;
  2089. }
  2090. }
  2091. else {
  2092. inv = 1.0 / this.direction.z;
  2093. min = (minimum.z - this.origin.z) * inv;
  2094. max = (maximum.z - this.origin.z) * inv;
  2095. if (max === -Infinity) {
  2096. max = Infinity;
  2097. }
  2098. if (min > max) {
  2099. temp = min;
  2100. min = max;
  2101. max = temp;
  2102. }
  2103. d = Math.max(min, d);
  2104. maxValue = Math.min(max, maxValue);
  2105. if (d > maxValue) {
  2106. return false;
  2107. }
  2108. }
  2109. return true;
  2110. };
  2111. Ray.prototype.intersectsBox = function (box) {
  2112. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2113. };
  2114. Ray.prototype.intersectsSphere = function (sphere) {
  2115. var x = sphere.center.x - this.origin.x;
  2116. var y = sphere.center.y - this.origin.y;
  2117. var z = sphere.center.z - this.origin.z;
  2118. var pyth = (x * x) + (y * y) + (z * z);
  2119. var rr = sphere.radius * sphere.radius;
  2120. if (pyth <= rr) {
  2121. return true;
  2122. }
  2123. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2124. if (dot < 0.0) {
  2125. return false;
  2126. }
  2127. var temp = pyth - (dot * dot);
  2128. return temp <= rr;
  2129. };
  2130. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2131. if (!this._edge1) {
  2132. this._edge1 = Vector3.Zero();
  2133. this._edge2 = Vector3.Zero();
  2134. this._pvec = Vector3.Zero();
  2135. this._tvec = Vector3.Zero();
  2136. this._qvec = Vector3.Zero();
  2137. }
  2138. vertex1.subtractToRef(vertex0, this._edge1);
  2139. vertex2.subtractToRef(vertex0, this._edge2);
  2140. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2141. var det = Vector3.Dot(this._edge1, this._pvec);
  2142. if (det === 0) {
  2143. return null;
  2144. }
  2145. var invdet = 1 / det;
  2146. this.origin.subtractToRef(vertex0, this._tvec);
  2147. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2148. if (bu < 0 || bu > 1.0) {
  2149. return null;
  2150. }
  2151. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2152. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2153. if (bv < 0 || bu + bv > 1.0) {
  2154. return null;
  2155. }
  2156. //check if the distance is longer than the predefined length.
  2157. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2158. if (distance > this.length) {
  2159. return null;
  2160. }
  2161. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2162. };
  2163. // Statics
  2164. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2165. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2166. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2167. var direction = end.subtract(start);
  2168. direction.normalize();
  2169. return new Ray(start, direction);
  2170. };
  2171. /**
  2172. * 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
  2173. * transformed to the given world matrix.
  2174. * @param origin The origin point
  2175. * @param end The end point
  2176. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2177. */
  2178. Ray.CreateNewFromTo = function (origin, end, world) {
  2179. if (world === void 0) { world = Matrix.Identity(); }
  2180. var direction = end.subtract(origin);
  2181. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2182. direction.normalize();
  2183. return Ray.Transform(new Ray(origin, direction, length), world);
  2184. };
  2185. Ray.Transform = function (ray, matrix) {
  2186. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2187. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2188. return new Ray(newOrigin, newDirection, ray.length);
  2189. };
  2190. return Ray;
  2191. })();
  2192. BABYLON.Ray = Ray;
  2193. (function (Space) {
  2194. Space[Space["LOCAL"] = 0] = "LOCAL";
  2195. Space[Space["WORLD"] = 1] = "WORLD";
  2196. })(BABYLON.Space || (BABYLON.Space = {}));
  2197. var Space = BABYLON.Space;
  2198. var Axis = (function () {
  2199. function Axis() {
  2200. }
  2201. Axis.X = new Vector3(1, 0, 0);
  2202. Axis.Y = new Vector3(0, 1, 0);
  2203. Axis.Z = new Vector3(0, 0, 1);
  2204. return Axis;
  2205. })();
  2206. BABYLON.Axis = Axis;
  2207. ;
  2208. var BezierCurve = (function () {
  2209. function BezierCurve() {
  2210. }
  2211. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2212. // Extract X (which is equal to time here)
  2213. var f0 = 1 - 3 * x2 + 3 * x1;
  2214. var f1 = 3 * x2 - 6 * x1;
  2215. var f2 = 3 * x1;
  2216. var refinedT = t;
  2217. for (var i = 0; i < 5; i++) {
  2218. var refinedT2 = refinedT * refinedT;
  2219. var refinedT3 = refinedT2 * refinedT;
  2220. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2221. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2222. refinedT -= (x - t) * slope;
  2223. refinedT = Math.min(1, Math.max(0, refinedT));
  2224. }
  2225. // Resolve cubic bezier for the given x
  2226. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2227. };
  2228. return BezierCurve;
  2229. })();
  2230. BABYLON.BezierCurve = BezierCurve;
  2231. (function (Orientation) {
  2232. Orientation[Orientation["CW"] = 0] = "CW";
  2233. Orientation[Orientation["CCW"] = 1] = "CCW";
  2234. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2235. var Orientation = BABYLON.Orientation;
  2236. var Angle = (function () {
  2237. function Angle(radians) {
  2238. var _this = this;
  2239. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2240. this.radians = function () { return _this._radians; };
  2241. this._radians = radians;
  2242. if (this._radians < 0)
  2243. this._radians += (2 * Math.PI);
  2244. }
  2245. Angle.BetweenTwoPoints = function (a, b) {
  2246. var delta = b.subtract(a);
  2247. var theta = Math.atan2(delta.y, delta.x);
  2248. return new Angle(theta);
  2249. };
  2250. Angle.FromRadians = function (radians) {
  2251. return new Angle(radians);
  2252. };
  2253. Angle.FromDegrees = function (degrees) {
  2254. return new Angle(degrees * Math.PI / 180);
  2255. };
  2256. return Angle;
  2257. })();
  2258. BABYLON.Angle = Angle;
  2259. var Arc2 = (function () {
  2260. function Arc2(startPoint, midPoint, endPoint) {
  2261. this.startPoint = startPoint;
  2262. this.midPoint = midPoint;
  2263. this.endPoint = endPoint;
  2264. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2265. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2266. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2267. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2268. 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);
  2269. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2270. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2271. var a1 = this.startAngle.degrees();
  2272. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2273. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2274. // angles correction
  2275. if (a2 - a1 > +180.0)
  2276. a2 -= 360.0;
  2277. if (a2 - a1 < -180.0)
  2278. a2 += 360.0;
  2279. if (a3 - a2 > +180.0)
  2280. a3 -= 360.0;
  2281. if (a3 - a2 < -180.0)
  2282. a3 += 360.0;
  2283. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2284. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2285. }
  2286. return Arc2;
  2287. })();
  2288. BABYLON.Arc2 = Arc2;
  2289. var PathCursor = (function () {
  2290. function PathCursor(path) {
  2291. this.path = path;
  2292. this._onchange = new Array();
  2293. this.value = 0;
  2294. this.animations = new Array();
  2295. }
  2296. PathCursor.prototype.getPoint = function () {
  2297. var point = this.path.getPointAtLengthPosition(this.value);
  2298. return new Vector3(point.x, 0, point.y);
  2299. };
  2300. PathCursor.prototype.moveAhead = function (step) {
  2301. if (step === void 0) { step = 0.002; }
  2302. this.move(step);
  2303. return this;
  2304. };
  2305. PathCursor.prototype.moveBack = function (step) {
  2306. if (step === void 0) { step = 0.002; }
  2307. this.move(-step);
  2308. return this;
  2309. };
  2310. PathCursor.prototype.move = function (step) {
  2311. if (Math.abs(step) > 1) {
  2312. throw "step size should be less than 1.";
  2313. }
  2314. this.value += step;
  2315. this.ensureLimits();
  2316. this.raiseOnChange();
  2317. return this;
  2318. };
  2319. PathCursor.prototype.ensureLimits = function () {
  2320. while (this.value > 1) {
  2321. this.value -= 1;
  2322. }
  2323. while (this.value < 0) {
  2324. this.value += 1;
  2325. }
  2326. return this;
  2327. };
  2328. // used by animation engine
  2329. PathCursor.prototype.markAsDirty = function (propertyName) {
  2330. this.ensureLimits();
  2331. this.raiseOnChange();
  2332. return this;
  2333. };
  2334. PathCursor.prototype.raiseOnChange = function () {
  2335. var _this = this;
  2336. this._onchange.forEach(function (f) { return f(_this); });
  2337. return this;
  2338. };
  2339. PathCursor.prototype.onchange = function (f) {
  2340. this._onchange.push(f);
  2341. return this;
  2342. };
  2343. return PathCursor;
  2344. })();
  2345. BABYLON.PathCursor = PathCursor;
  2346. var Path2 = (function () {
  2347. function Path2(x, y) {
  2348. this._points = new Array();
  2349. this._length = 0;
  2350. this.closed = false;
  2351. this._points.push(new Vector2(x, y));
  2352. }
  2353. Path2.prototype.addLineTo = function (x, y) {
  2354. if (closed) {
  2355. BABYLON.Tools.Error("cannot add lines to closed paths");
  2356. return this;
  2357. }
  2358. var newPoint = new Vector2(x, y);
  2359. var previousPoint = this._points[this._points.length - 1];
  2360. this._points.push(newPoint);
  2361. this._length += newPoint.subtract(previousPoint).length();
  2362. return this;
  2363. };
  2364. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2365. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2366. if (closed) {
  2367. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2368. return this;
  2369. }
  2370. var startPoint = this._points[this._points.length - 1];
  2371. var midPoint = new Vector2(midX, midY);
  2372. var endPoint = new Vector2(endX, endY);
  2373. var arc = new Arc2(startPoint, midPoint, endPoint);
  2374. var increment = arc.angle.radians() / numberOfSegments;
  2375. if (arc.orientation === 0 /* CW */)
  2376. increment *= -1;
  2377. var currentAngle = arc.startAngle.radians() + increment;
  2378. for (var i = 0; i < numberOfSegments; i++) {
  2379. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2380. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2381. this.addLineTo(x, y);
  2382. currentAngle += increment;
  2383. }
  2384. return this;
  2385. };
  2386. Path2.prototype.close = function () {
  2387. this.closed = true;
  2388. return this;
  2389. };
  2390. Path2.prototype.length = function () {
  2391. var result = this._length;
  2392. if (!this.closed) {
  2393. var lastPoint = this._points[this._points.length - 1];
  2394. var firstPoint = this._points[0];
  2395. result += (firstPoint.subtract(lastPoint).length());
  2396. }
  2397. return result;
  2398. };
  2399. Path2.prototype.getPoints = function () {
  2400. return this._points;
  2401. };
  2402. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2403. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2404. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2405. return Vector2.Zero();
  2406. }
  2407. var lengthPosition = normalizedLengthPosition * this.length();
  2408. var previousOffset = 0;
  2409. for (var i = 0; i < this._points.length; i++) {
  2410. var j = (i + 1) % this._points.length;
  2411. var a = this._points[i];
  2412. var b = this._points[j];
  2413. var bToA = b.subtract(a);
  2414. var nextOffset = (bToA.length() + previousOffset);
  2415. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2416. var dir = bToA.normalize();
  2417. var localOffset = lengthPosition - previousOffset;
  2418. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2419. }
  2420. previousOffset = nextOffset;
  2421. }
  2422. BABYLON.Tools.Error("internal error");
  2423. return Vector2.Zero();
  2424. };
  2425. Path2.StartingAt = function (x, y) {
  2426. return new Path2(x, y);
  2427. };
  2428. return Path2;
  2429. })();
  2430. BABYLON.Path2 = Path2;
  2431. var Path3D = (function () {
  2432. function Path3D(path) {
  2433. this.path = path;
  2434. this._curve = new Array();
  2435. this._distances = new Array();
  2436. this._tangents = new Array();
  2437. this._normals = new Array();
  2438. this._binormals = new Array();
  2439. this._curve = path.slice(); // copy array
  2440. var l = this._curve.length;
  2441. // first and last tangents
  2442. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2443. this._tangents[0].normalize();
  2444. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2445. this._tangents[l - 1].normalize();
  2446. // normals and binormals at first point : arbitrary vector with _normalVector()
  2447. var tg0 = this._tangents[0];
  2448. var pp0 = this._normalVector(this._curve[0], tg0);
  2449. this._normals[0] = pp0;
  2450. this._normals[0].normalize();
  2451. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2452. this._normals[0].normalize();
  2453. this._distances[0] = 0;
  2454. // normals and binormals : next points
  2455. var prev; // previous vector (segment)
  2456. var cur; // current vector (segment)
  2457. var curTang; // current tangent
  2458. var prevNorm; // previous normal
  2459. var prevBinor; // previous binormal
  2460. for (var i = 1; i < l; i++) {
  2461. // tangents
  2462. prev = this._curve[i].subtract(this._curve[i - 1]);
  2463. if (i < l - 1) {
  2464. cur = this._curve[i + 1].subtract(this._curve[i]);
  2465. this._tangents[i] = prev.add(cur);
  2466. this._tangents[i].normalize();
  2467. }
  2468. this._distances[i] = this._distances[i - 1] + prev.length();
  2469. // normals and binormals
  2470. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2471. curTang = this._tangents[i];
  2472. prevNorm = this._normals[i - 1];
  2473. prevBinor = this._binormals[i - 1];
  2474. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2475. this._normals[i].normalize();
  2476. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2477. this._binormals[i].normalize();
  2478. }
  2479. }
  2480. Path3D.prototype.getCurve = function () {
  2481. return this._curve;
  2482. };
  2483. Path3D.prototype.getTangents = function () {
  2484. return this._tangents;
  2485. };
  2486. Path3D.prototype.getNormals = function () {
  2487. return this._normals;
  2488. };
  2489. Path3D.prototype.getBinormals = function () {
  2490. return this._binormals;
  2491. };
  2492. Path3D.prototype.getDistances = function () {
  2493. return this._distances;
  2494. };
  2495. // private function normalVector(v0, vt) :
  2496. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2497. Path3D.prototype._normalVector = function (v0, vt) {
  2498. var point;
  2499. if (vt.x !== 1) {
  2500. point = new Vector3(1, 0, 0);
  2501. }
  2502. else if (vt.y !== 1) {
  2503. point = new Vector3(0, 1, 0);
  2504. }
  2505. else if (vt.z !== 1) {
  2506. point = new Vector3(0, 0, 1);
  2507. }
  2508. var normal0 = Vector3.Cross(vt, point);
  2509. normal0.normalize();
  2510. return normal0;
  2511. };
  2512. return Path3D;
  2513. })();
  2514. BABYLON.Path3D = Path3D;
  2515. var Curve3 = (function () {
  2516. function Curve3(points) {
  2517. this._points = points;
  2518. }
  2519. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2520. Curve3.QuadraticBezier = function (v0, v1, v2, nbPoints) {
  2521. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2522. var bez = new Array();
  2523. var step = 1 / nbPoints;
  2524. var equation = function (t, val0, val1, val2) {
  2525. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2526. return res;
  2527. };
  2528. for (var i = 0; i <= 1; i += step) {
  2529. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2530. }
  2531. return new Curve3(bez);
  2532. };
  2533. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2534. Curve3.CubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2535. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2536. var bez = new Array();
  2537. var step = 1 / nbPoints;
  2538. var equation = function (t, val0, val1, val2, val3) {
  2539. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2540. return res;
  2541. };
  2542. for (var i = 0; i <= 1; i += step) {
  2543. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2544. }
  2545. return new Curve3(bez);
  2546. };
  2547. Curve3.prototype.getPoints = function () {
  2548. return this._points;
  2549. };
  2550. return Curve3;
  2551. })();
  2552. BABYLON.Curve3 = Curve3;
  2553. // SIMD
  2554. if (window.SIMD !== undefined) {
  2555. // Replace functions
  2556. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2557. }
  2558. })(BABYLON || (BABYLON = {}));
  2559. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2560. (function (BABYLON) {
  2561. // Screenshots
  2562. var screenshotCanvas;
  2563. var cloneValue = function (source, destinationObject) {
  2564. if (!source)
  2565. return null;
  2566. if (source instanceof BABYLON.Mesh) {
  2567. return null;
  2568. }
  2569. if (source instanceof BABYLON.SubMesh) {
  2570. return source.clone(destinationObject);
  2571. }
  2572. else if (source.clone) {
  2573. return source.clone();
  2574. }
  2575. return null;
  2576. };
  2577. var Tools = (function () {
  2578. function Tools() {
  2579. }
  2580. Tools.GetFilename = function (path) {
  2581. var index = path.lastIndexOf("/");
  2582. if (index < 0)
  2583. return path;
  2584. return path.substring(index + 1);
  2585. };
  2586. Tools.GetDOMTextContent = function (element) {
  2587. var result = "";
  2588. var child = element.firstChild;
  2589. while (child) {
  2590. if (child.nodeType === 3) {
  2591. result += child.textContent;
  2592. }
  2593. child = child.nextSibling;
  2594. }
  2595. return result;
  2596. };
  2597. Tools.ToDegrees = function (angle) {
  2598. return angle * 180 / Math.PI;
  2599. };
  2600. Tools.ToRadians = function (angle) {
  2601. return angle * Math.PI / 180;
  2602. };
  2603. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2604. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2605. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2606. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2607. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2608. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2609. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2610. }
  2611. return {
  2612. minimum: minimum,
  2613. maximum: maximum
  2614. };
  2615. };
  2616. Tools.ExtractMinAndMax = function (positions, start, count) {
  2617. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2618. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2619. for (var index = start; index < start + count; index++) {
  2620. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2621. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2622. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2623. }
  2624. return {
  2625. minimum: minimum,
  2626. maximum: maximum
  2627. };
  2628. };
  2629. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2630. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2631. return undefined;
  2632. return Array.isArray(obj) ? obj : [obj];
  2633. };
  2634. // Misc.
  2635. Tools.GetPointerPrefix = function () {
  2636. var eventPrefix = "pointer";
  2637. // Check if hand.js is referenced or if the browser natively supports pointer events
  2638. if (!navigator.pointerEnabled) {
  2639. eventPrefix = "mouse";
  2640. }
  2641. return eventPrefix;
  2642. };
  2643. Tools.QueueNewFrame = function (func) {
  2644. if (window.requestAnimationFrame)
  2645. window.requestAnimationFrame(func);
  2646. else if (window.msRequestAnimationFrame)
  2647. window.msRequestAnimationFrame(func);
  2648. else if (window.webkitRequestAnimationFrame)
  2649. window.webkitRequestAnimationFrame(func);
  2650. else if (window.mozRequestAnimationFrame)
  2651. window.mozRequestAnimationFrame(func);
  2652. else if (window.oRequestAnimationFrame)
  2653. window.oRequestAnimationFrame(func);
  2654. else {
  2655. window.setTimeout(func, 16);
  2656. }
  2657. };
  2658. Tools.RequestFullscreen = function (element) {
  2659. if (element.requestFullscreen)
  2660. element.requestFullscreen();
  2661. else if (element.msRequestFullscreen)
  2662. element.msRequestFullscreen();
  2663. else if (element.webkitRequestFullscreen)
  2664. element.webkitRequestFullscreen();
  2665. else if (element.mozRequestFullScreen)
  2666. element.mozRequestFullScreen();
  2667. };
  2668. Tools.ExitFullscreen = function () {
  2669. if (document.exitFullscreen) {
  2670. document.exitFullscreen();
  2671. }
  2672. else if (document.mozCancelFullScreen) {
  2673. document.mozCancelFullScreen();
  2674. }
  2675. else if (document.webkitCancelFullScreen) {
  2676. document.webkitCancelFullScreen();
  2677. }
  2678. else if (document.msCancelFullScreen) {
  2679. document.msCancelFullScreen();
  2680. }
  2681. };
  2682. // External files
  2683. Tools.CleanUrl = function (url) {
  2684. url = url.replace(/#/mg, "%23");
  2685. return url;
  2686. };
  2687. Tools.LoadImage = function (url, onload, onerror, database) {
  2688. url = Tools.CleanUrl(url);
  2689. var img = new Image();
  2690. if (url.substr(0, 5) !== "data:")
  2691. img.crossOrigin = 'anonymous';
  2692. img.onload = function () {
  2693. onload(img);
  2694. };
  2695. img.onerror = function (err) {
  2696. onerror(img, err);
  2697. };
  2698. var noIndexedDB = function () {
  2699. img.src = url;
  2700. };
  2701. var loadFromIndexedDB = function () {
  2702. database.loadImageFromDB(url, img);
  2703. };
  2704. //ANY database to do!
  2705. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2706. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2707. }
  2708. else {
  2709. if (url.indexOf("file:") === -1) {
  2710. noIndexedDB();
  2711. }
  2712. else {
  2713. try {
  2714. var textureName = url.substring(5);
  2715. var blobURL;
  2716. try {
  2717. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2718. }
  2719. catch (ex) {
  2720. // Chrome doesn't support oneTimeOnly parameter
  2721. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2722. }
  2723. img.src = blobURL;
  2724. }
  2725. catch (e) {
  2726. Tools.Log("Error while trying to load texture: " + textureName);
  2727. img.src = null;
  2728. }
  2729. }
  2730. }
  2731. return img;
  2732. };
  2733. //ANY
  2734. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2735. url = Tools.CleanUrl(url);
  2736. var noIndexedDB = function () {
  2737. var request = new XMLHttpRequest();
  2738. var loadUrl = Tools.BaseUrl + url;
  2739. request.open('GET', loadUrl, true);
  2740. if (useArrayBuffer) {
  2741. request.responseType = "arraybuffer";
  2742. }
  2743. request.onprogress = progressCallBack;
  2744. request.onreadystatechange = function () {
  2745. if (request.readyState === 4) {
  2746. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2747. callback(!useArrayBuffer ? request.responseText : request.response);
  2748. }
  2749. else {
  2750. if (onError) {
  2751. onError();
  2752. }
  2753. else {
  2754. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2755. }
  2756. }
  2757. }
  2758. };
  2759. request.send(null);
  2760. };
  2761. var loadFromIndexedDB = function () {
  2762. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2763. };
  2764. if (url.indexOf("file:") !== -1) {
  2765. var fileName = url.substring(5);
  2766. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2767. }
  2768. else {
  2769. // Caching all files
  2770. if (database && database.enableSceneOffline) {
  2771. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2772. }
  2773. else {
  2774. noIndexedDB();
  2775. }
  2776. }
  2777. };
  2778. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2779. var reader = new FileReader();
  2780. reader.onload = function (e) {
  2781. //target doesn't have result from ts 1.3
  2782. callback(e.target['result']);
  2783. };
  2784. reader.onprogress = progressCallback;
  2785. reader.readAsDataURL(fileToLoad);
  2786. };
  2787. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2788. var reader = new FileReader();
  2789. reader.onerror = function (e) {
  2790. Tools.Log("Error while reading file: " + fileToLoad.name);
  2791. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2792. };
  2793. reader.onload = function (e) {
  2794. //target doesn't have result from ts 1.3
  2795. callback(e.target['result']);
  2796. };
  2797. reader.onprogress = progressCallBack;
  2798. if (!useArrayBuffer) {
  2799. // Asynchronous read
  2800. reader.readAsText(fileToLoad);
  2801. }
  2802. else {
  2803. reader.readAsArrayBuffer(fileToLoad);
  2804. }
  2805. };
  2806. // Misc.
  2807. Tools.Clamp = function (value, min, max) {
  2808. if (min === void 0) { min = 0; }
  2809. if (max === void 0) { max = 1; }
  2810. return Math.min(max, Math.max(min, value));
  2811. };
  2812. // Returns -1 when value is a negative number and
  2813. // +1 when value is a positive number.
  2814. Tools.Sign = function (value) {
  2815. value = +value; // convert to a number
  2816. if (value === 0 || isNaN(value))
  2817. return value;
  2818. return value > 0 ? 1 : -1;
  2819. };
  2820. Tools.Format = function (value, decimals) {
  2821. if (decimals === void 0) { decimals = 2; }
  2822. return value.toFixed(decimals);
  2823. };
  2824. Tools.CheckExtends = function (v, min, max) {
  2825. if (v.x < min.x)
  2826. min.x = v.x;
  2827. if (v.y < min.y)
  2828. min.y = v.y;
  2829. if (v.z < min.z)
  2830. min.z = v.z;
  2831. if (v.x > max.x)
  2832. max.x = v.x;
  2833. if (v.y > max.y)
  2834. max.y = v.y;
  2835. if (v.z > max.z)
  2836. max.z = v.z;
  2837. };
  2838. Tools.WithinEpsilon = function (a, b, epsilon) {
  2839. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2840. var num = a - b;
  2841. return -epsilon <= num && num <= epsilon;
  2842. };
  2843. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2844. for (var prop in source) {
  2845. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2846. continue;
  2847. }
  2848. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2849. continue;
  2850. }
  2851. var sourceValue = source[prop];
  2852. var typeOfSourceValue = typeof sourceValue;
  2853. if (typeOfSourceValue === "function") {
  2854. continue;
  2855. }
  2856. if (typeOfSourceValue === "object") {
  2857. if (sourceValue instanceof Array) {
  2858. destination[prop] = [];
  2859. if (sourceValue.length > 0) {
  2860. if (typeof sourceValue[0] == "object") {
  2861. for (var index = 0; index < sourceValue.length; index++) {
  2862. var clonedValue = cloneValue(sourceValue[index], destination);
  2863. if (destination[prop].indexOf(clonedValue) === -1) {
  2864. destination[prop].push(clonedValue);
  2865. }
  2866. }
  2867. }
  2868. else {
  2869. destination[prop] = sourceValue.slice(0);
  2870. }
  2871. }
  2872. }
  2873. else {
  2874. destination[prop] = cloneValue(sourceValue, destination);
  2875. }
  2876. }
  2877. else {
  2878. destination[prop] = sourceValue;
  2879. }
  2880. }
  2881. };
  2882. Tools.IsEmpty = function (obj) {
  2883. for (var i in obj) {
  2884. return false;
  2885. }
  2886. return true;
  2887. };
  2888. Tools.RegisterTopRootEvents = function (events) {
  2889. for (var index = 0; index < events.length; index++) {
  2890. var event = events[index];
  2891. window.addEventListener(event.name, event.handler, false);
  2892. try {
  2893. if (window.parent) {
  2894. window.parent.addEventListener(event.name, event.handler, false);
  2895. }
  2896. }
  2897. catch (e) {
  2898. }
  2899. }
  2900. };
  2901. Tools.UnregisterTopRootEvents = function (events) {
  2902. for (var index = 0; index < events.length; index++) {
  2903. var event = events[index];
  2904. window.removeEventListener(event.name, event.handler);
  2905. try {
  2906. if (window.parent) {
  2907. window.parent.removeEventListener(event.name, event.handler);
  2908. }
  2909. }
  2910. catch (e) {
  2911. }
  2912. }
  2913. };
  2914. Tools.DumpFramebuffer = function (width, height, engine) {
  2915. // Read the contents of the framebuffer
  2916. var numberOfChannelsByLine = width * 4;
  2917. var halfHeight = height / 2;
  2918. //Reading datas from WebGL
  2919. var data = engine.readPixels(0, 0, width, height);
  2920. for (var i = 0; i < halfHeight; i++) {
  2921. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2922. var currentCell = j + i * numberOfChannelsByLine;
  2923. var targetLine = height - i - 1;
  2924. var targetCell = j + targetLine * numberOfChannelsByLine;
  2925. var temp = data[currentCell];
  2926. data[currentCell] = data[targetCell];
  2927. data[targetCell] = temp;
  2928. }
  2929. }
  2930. // Create a 2D canvas to store the result
  2931. if (!screenshotCanvas) {
  2932. screenshotCanvas = document.createElement('canvas');
  2933. }
  2934. screenshotCanvas.width = width;
  2935. screenshotCanvas.height = height;
  2936. var context = screenshotCanvas.getContext('2d');
  2937. // Copy the pixels to a 2D canvas
  2938. var imageData = context.createImageData(width, height);
  2939. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2940. var castData = imageData.data;
  2941. castData.set(data);
  2942. context.putImageData(imageData, 0, 0);
  2943. var base64Image = screenshotCanvas.toDataURL();
  2944. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2945. if (("download" in document.createElement("a"))) {
  2946. var a = window.document.createElement("a");
  2947. a.href = base64Image;
  2948. var date = new Date();
  2949. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2950. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2951. window.document.body.appendChild(a);
  2952. a.addEventListener("click", function () {
  2953. a.parentElement.removeChild(a);
  2954. });
  2955. a.click();
  2956. }
  2957. else {
  2958. var newWindow = window.open("");
  2959. var img = newWindow.document.createElement("img");
  2960. img.src = base64Image;
  2961. newWindow.document.body.appendChild(img);
  2962. }
  2963. };
  2964. Tools.CreateScreenshot = function (engine, camera, size) {
  2965. var width;
  2966. var height;
  2967. var scene = camera.getScene();
  2968. var previousCamera = null;
  2969. if (scene.activeCamera !== camera) {
  2970. previousCamera = scene.activeCamera;
  2971. scene.activeCamera = camera;
  2972. }
  2973. //If a precision value is specified
  2974. if (size.precision) {
  2975. width = Math.round(engine.getRenderWidth() * size.precision);
  2976. height = Math.round(width / engine.getAspectRatio(camera));
  2977. size = { width: width, height: height };
  2978. }
  2979. else if (size.width && size.height) {
  2980. width = size.width;
  2981. height = size.height;
  2982. }
  2983. else if (size.width && !size.height) {
  2984. width = size.width;
  2985. height = Math.round(width / engine.getAspectRatio(camera));
  2986. size = { width: width, height: height };
  2987. }
  2988. else if (size.height && !size.width) {
  2989. height = size.height;
  2990. width = Math.round(height * engine.getAspectRatio(camera));
  2991. size = { width: width, height: height };
  2992. }
  2993. else if (!isNaN(size)) {
  2994. height = size;
  2995. width = size;
  2996. }
  2997. else {
  2998. Tools.Error("Invalid 'size' parameter !");
  2999. return;
  3000. }
  3001. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3002. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3003. texture.renderList = scene.meshes;
  3004. texture.onAfterRender = function () {
  3005. Tools.DumpFramebuffer(width, height, engine);
  3006. };
  3007. scene.incrementRenderId();
  3008. texture.render(true);
  3009. texture.dispose();
  3010. if (previousCamera) {
  3011. scene.activeCamera = previousCamera;
  3012. }
  3013. };
  3014. // XHR response validator for local file scenario
  3015. Tools.ValidateXHRData = function (xhr, dataType) {
  3016. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3017. if (dataType === void 0) { dataType = 7; }
  3018. try {
  3019. if (dataType & 1) {
  3020. if (xhr.responseText && xhr.responseText.length > 0) {
  3021. return true;
  3022. }
  3023. else if (dataType === 1) {
  3024. return false;
  3025. }
  3026. }
  3027. if (dataType & 2) {
  3028. // Check header width and height since there is no "TGA" magic number
  3029. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3030. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3031. return true;
  3032. }
  3033. else if (dataType === 2) {
  3034. return false;
  3035. }
  3036. }
  3037. if (dataType & 4) {
  3038. // Check for the "DDS" magic number
  3039. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3040. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3041. return true;
  3042. }
  3043. else {
  3044. return false;
  3045. }
  3046. }
  3047. }
  3048. catch (e) {
  3049. }
  3050. return false;
  3051. };
  3052. Object.defineProperty(Tools, "NoneLogLevel", {
  3053. get: function () {
  3054. return Tools._NoneLogLevel;
  3055. },
  3056. enumerable: true,
  3057. configurable: true
  3058. });
  3059. Object.defineProperty(Tools, "MessageLogLevel", {
  3060. get: function () {
  3061. return Tools._MessageLogLevel;
  3062. },
  3063. enumerable: true,
  3064. configurable: true
  3065. });
  3066. Object.defineProperty(Tools, "WarningLogLevel", {
  3067. get: function () {
  3068. return Tools._WarningLogLevel;
  3069. },
  3070. enumerable: true,
  3071. configurable: true
  3072. });
  3073. Object.defineProperty(Tools, "ErrorLogLevel", {
  3074. get: function () {
  3075. return Tools._ErrorLogLevel;
  3076. },
  3077. enumerable: true,
  3078. configurable: true
  3079. });
  3080. Object.defineProperty(Tools, "AllLogLevel", {
  3081. get: function () {
  3082. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3083. },
  3084. enumerable: true,
  3085. configurable: true
  3086. });
  3087. Tools._AddLogEntry = function (entry) {
  3088. Tools._LogCache = entry + Tools._LogCache;
  3089. if (Tools.OnNewCacheEntry) {
  3090. Tools.OnNewCacheEntry(entry);
  3091. }
  3092. };
  3093. Tools._FormatMessage = function (message) {
  3094. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3095. var date = new Date();
  3096. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3097. };
  3098. Tools._LogDisabled = function (message) {
  3099. // nothing to do
  3100. };
  3101. Tools._LogEnabled = function (message) {
  3102. var formattedMessage = Tools._FormatMessage(message);
  3103. console.log("BJS - " + formattedMessage);
  3104. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3105. Tools._AddLogEntry(entry);
  3106. };
  3107. Tools._WarnDisabled = function (message) {
  3108. // nothing to do
  3109. };
  3110. Tools._WarnEnabled = function (message) {
  3111. var formattedMessage = Tools._FormatMessage(message);
  3112. console.warn("BJS - " + formattedMessage);
  3113. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3114. Tools._AddLogEntry(entry);
  3115. };
  3116. Tools._ErrorDisabled = function (message) {
  3117. // nothing to do
  3118. };
  3119. Tools._ErrorEnabled = function (message) {
  3120. var formattedMessage = Tools._FormatMessage(message);
  3121. console.error("BJS - " + formattedMessage);
  3122. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3123. Tools._AddLogEntry(entry);
  3124. };
  3125. Object.defineProperty(Tools, "LogCache", {
  3126. get: function () {
  3127. return Tools._LogCache;
  3128. },
  3129. enumerable: true,
  3130. configurable: true
  3131. });
  3132. Object.defineProperty(Tools, "LogLevels", {
  3133. set: function (level) {
  3134. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3135. Tools.Log = Tools._LogEnabled;
  3136. }
  3137. else {
  3138. Tools.Log = Tools._LogDisabled;
  3139. }
  3140. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3141. Tools.Warn = Tools._WarnEnabled;
  3142. }
  3143. else {
  3144. Tools.Warn = Tools._WarnDisabled;
  3145. }
  3146. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3147. Tools.Error = Tools._ErrorEnabled;
  3148. }
  3149. else {
  3150. Tools.Error = Tools._ErrorDisabled;
  3151. }
  3152. },
  3153. enumerable: true,
  3154. configurable: true
  3155. });
  3156. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3157. get: function () {
  3158. return Tools._PerformanceNoneLogLevel;
  3159. },
  3160. enumerable: true,
  3161. configurable: true
  3162. });
  3163. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3164. get: function () {
  3165. return Tools._PerformanceUserMarkLogLevel;
  3166. },
  3167. enumerable: true,
  3168. configurable: true
  3169. });
  3170. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3171. get: function () {
  3172. return Tools._PerformanceConsoleLogLevel;
  3173. },
  3174. enumerable: true,
  3175. configurable: true
  3176. });
  3177. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3178. set: function (level) {
  3179. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3180. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3181. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3182. return;
  3183. }
  3184. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3185. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3186. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3187. return;
  3188. }
  3189. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3190. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3191. },
  3192. enumerable: true,
  3193. configurable: true
  3194. });
  3195. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3196. };
  3197. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3198. };
  3199. Tools._StartUserMark = function (counterName, condition) {
  3200. if (condition === void 0) { condition = true; }
  3201. if (!condition || !Tools._performance.mark) {
  3202. return;
  3203. }
  3204. Tools._performance.mark(counterName + "-Begin");
  3205. };
  3206. Tools._EndUserMark = function (counterName, condition) {
  3207. if (condition === void 0) { condition = true; }
  3208. if (!condition || !Tools._performance.mark) {
  3209. return;
  3210. }
  3211. Tools._performance.mark(counterName + "-End");
  3212. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3213. };
  3214. Tools._StartPerformanceConsole = function (counterName, condition) {
  3215. if (condition === void 0) { condition = true; }
  3216. if (!condition) {
  3217. return;
  3218. }
  3219. Tools._StartUserMark(counterName, condition);
  3220. if (console.time) {
  3221. console.time(counterName);
  3222. }
  3223. };
  3224. Tools._EndPerformanceConsole = function (counterName, condition) {
  3225. if (condition === void 0) { condition = true; }
  3226. if (!condition) {
  3227. return;
  3228. }
  3229. Tools._EndUserMark(counterName, condition);
  3230. if (console.time) {
  3231. console.timeEnd(counterName);
  3232. }
  3233. };
  3234. Object.defineProperty(Tools, "Now", {
  3235. get: function () {
  3236. if (window.performance && window.performance.now) {
  3237. return window.performance.now();
  3238. }
  3239. return new Date().getTime();
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. // Deprecated
  3245. Tools.GetFps = function () {
  3246. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3247. return 0;
  3248. };
  3249. Tools.BaseUrl = "";
  3250. Tools.GetExponantOfTwo = function (value, max) {
  3251. var count = 1;
  3252. do {
  3253. count *= 2;
  3254. } while (count < value);
  3255. if (count > max)
  3256. count = max;
  3257. return count;
  3258. };
  3259. // Logs
  3260. Tools._NoneLogLevel = 0;
  3261. Tools._MessageLogLevel = 1;
  3262. Tools._WarningLogLevel = 2;
  3263. Tools._ErrorLogLevel = 4;
  3264. Tools._LogCache = "";
  3265. Tools.Log = Tools._LogEnabled;
  3266. Tools.Warn = Tools._WarnEnabled;
  3267. Tools.Error = Tools._ErrorEnabled;
  3268. // Performances
  3269. Tools._PerformanceNoneLogLevel = 0;
  3270. Tools._PerformanceUserMarkLogLevel = 1;
  3271. Tools._PerformanceConsoleLogLevel = 2;
  3272. Tools._performance = window.performance;
  3273. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3274. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3275. return Tools;
  3276. })();
  3277. BABYLON.Tools = Tools;
  3278. /**
  3279. * An implementation of a loop for asynchronous functions.
  3280. */
  3281. var AsyncLoop = (function () {
  3282. /**
  3283. * Constroctor.
  3284. * @param iterations the number of iterations.
  3285. * @param _fn the function to run each iteration
  3286. * @param _successCallback the callback that will be called upon succesful execution
  3287. * @param offset starting offset.
  3288. */
  3289. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3290. if (offset === void 0) { offset = 0; }
  3291. this.iterations = iterations;
  3292. this._fn = _fn;
  3293. this._successCallback = _successCallback;
  3294. this.index = offset - 1;
  3295. this._done = false;
  3296. }
  3297. /**
  3298. * Execute the next iteration. Must be called after the last iteration was finished.
  3299. */
  3300. AsyncLoop.prototype.executeNext = function () {
  3301. if (!this._done) {
  3302. if (this.index + 1 < this.iterations) {
  3303. ++this.index;
  3304. this._fn(this);
  3305. }
  3306. else {
  3307. this.breakLoop();
  3308. }
  3309. }
  3310. };
  3311. /**
  3312. * Break the loop and run the success callback.
  3313. */
  3314. AsyncLoop.prototype.breakLoop = function () {
  3315. this._done = true;
  3316. this._successCallback();
  3317. };
  3318. /**
  3319. * Helper function
  3320. */
  3321. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3322. if (offset === void 0) { offset = 0; }
  3323. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3324. loop.executeNext();
  3325. return loop;
  3326. };
  3327. /**
  3328. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3329. * @param iterations total number of iterations
  3330. * @param syncedIterations number of synchronous iterations in each async iteration.
  3331. * @param fn the function to call each iteration.
  3332. * @param callback a success call back that will be called when iterating stops.
  3333. * @param breakFunction a break condition (optional)
  3334. * @param timeout timeout settings for the setTimeout function. default - 0.
  3335. * @constructor
  3336. */
  3337. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3338. if (timeout === void 0) { timeout = 0; }
  3339. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3340. if (breakFunction && breakFunction())
  3341. loop.breakLoop();
  3342. else {
  3343. setTimeout(function () {
  3344. for (var i = 0; i < syncedIterations; ++i) {
  3345. var iteration = (loop.index * syncedIterations) + i;
  3346. if (iteration >= iterations)
  3347. break;
  3348. fn(iteration);
  3349. if (breakFunction && breakFunction()) {
  3350. loop.breakLoop();
  3351. break;
  3352. }
  3353. }
  3354. loop.executeNext();
  3355. }, timeout);
  3356. }
  3357. }, callback);
  3358. };
  3359. return AsyncLoop;
  3360. })();
  3361. BABYLON.AsyncLoop = AsyncLoop;
  3362. })(BABYLON || (BABYLON = {}));
  3363. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3364. (function (BABYLON) {
  3365. var _DepthCullingState = (function () {
  3366. function _DepthCullingState() {
  3367. this._isDepthTestDirty = false;
  3368. this._isDepthMaskDirty = false;
  3369. this._isDepthFuncDirty = false;
  3370. this._isCullFaceDirty = false;
  3371. this._isCullDirty = false;
  3372. }
  3373. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3374. get: function () {
  3375. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3376. },
  3377. enumerable: true,
  3378. configurable: true
  3379. });
  3380. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3381. get: function () {
  3382. return this._cullFace;
  3383. },
  3384. set: function (value) {
  3385. if (this._cullFace === value) {
  3386. return;
  3387. }
  3388. this._cullFace = value;
  3389. this._isCullFaceDirty = true;
  3390. },
  3391. enumerable: true,
  3392. configurable: true
  3393. });
  3394. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3395. get: function () {
  3396. return this._cull;
  3397. },
  3398. set: function (value) {
  3399. if (this._cull === value) {
  3400. return;
  3401. }
  3402. this._cull = value;
  3403. this._isCullDirty = true;
  3404. },
  3405. enumerable: true,
  3406. configurable: true
  3407. });
  3408. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3409. get: function () {
  3410. return this._depthFunc;
  3411. },
  3412. set: function (value) {
  3413. if (this._depthFunc === value) {
  3414. return;
  3415. }
  3416. this._depthFunc = value;
  3417. this._isDepthFuncDirty = true;
  3418. },
  3419. enumerable: true,
  3420. configurable: true
  3421. });
  3422. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3423. get: function () {
  3424. return this._depthMask;
  3425. },
  3426. set: function (value) {
  3427. if (this._depthMask === value) {
  3428. return;
  3429. }
  3430. this._depthMask = value;
  3431. this._isDepthMaskDirty = true;
  3432. },
  3433. enumerable: true,
  3434. configurable: true
  3435. });
  3436. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3437. get: function () {
  3438. return this._depthTest;
  3439. },
  3440. set: function (value) {
  3441. if (this._depthTest === value) {
  3442. return;
  3443. }
  3444. this._depthTest = value;
  3445. this._isDepthTestDirty = true;
  3446. },
  3447. enumerable: true,
  3448. configurable: true
  3449. });
  3450. _DepthCullingState.prototype.reset = function () {
  3451. this._depthMask = true;
  3452. this._depthTest = true;
  3453. this._depthFunc = null;
  3454. this._cull = null;
  3455. this._cullFace = null;
  3456. this._isDepthTestDirty = true;
  3457. this._isDepthMaskDirty = true;
  3458. this._isDepthFuncDirty = false;
  3459. this._isCullFaceDirty = false;
  3460. this._isCullDirty = false;
  3461. };
  3462. _DepthCullingState.prototype.apply = function (gl) {
  3463. if (!this.isDirty) {
  3464. return;
  3465. }
  3466. // Cull
  3467. if (this._isCullDirty) {
  3468. if (this.cull) {
  3469. gl.enable(gl.CULL_FACE);
  3470. }
  3471. else {
  3472. gl.disable(gl.CULL_FACE);
  3473. }
  3474. this._isCullDirty = false;
  3475. }
  3476. // Cull face
  3477. if (this._isCullFaceDirty) {
  3478. gl.cullFace(this.cullFace);
  3479. this._isCullFaceDirty = false;
  3480. }
  3481. // Depth mask
  3482. if (this._isDepthMaskDirty) {
  3483. gl.depthMask(this.depthMask);
  3484. this._isDepthMaskDirty = false;
  3485. }
  3486. // Depth test
  3487. if (this._isDepthTestDirty) {
  3488. if (this.depthTest) {
  3489. gl.enable(gl.DEPTH_TEST);
  3490. }
  3491. else {
  3492. gl.disable(gl.DEPTH_TEST);
  3493. }
  3494. this._isDepthTestDirty = false;
  3495. }
  3496. // Depth func
  3497. if (this._isDepthFuncDirty) {
  3498. gl.depthFunc(this.depthFunc);
  3499. this._isDepthFuncDirty = false;
  3500. }
  3501. };
  3502. return _DepthCullingState;
  3503. })();
  3504. BABYLON._DepthCullingState = _DepthCullingState;
  3505. var _AlphaState = (function () {
  3506. function _AlphaState() {
  3507. this._isAlphaBlendDirty = false;
  3508. this._isBlendFunctionParametersDirty = false;
  3509. this._alphaBlend = false;
  3510. this._blendFunctionParameters = new Array(4);
  3511. }
  3512. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3513. get: function () {
  3514. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3515. },
  3516. enumerable: true,
  3517. configurable: true
  3518. });
  3519. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3520. get: function () {
  3521. return this._alphaBlend;
  3522. },
  3523. set: function (value) {
  3524. if (this._alphaBlend === value) {
  3525. return;
  3526. }
  3527. this._alphaBlend = value;
  3528. this._isAlphaBlendDirty = true;
  3529. },
  3530. enumerable: true,
  3531. configurable: true
  3532. });
  3533. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3534. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3535. return;
  3536. }
  3537. this._blendFunctionParameters[0] = value0;
  3538. this._blendFunctionParameters[1] = value1;
  3539. this._blendFunctionParameters[2] = value2;
  3540. this._blendFunctionParameters[3] = value3;
  3541. this._isBlendFunctionParametersDirty = true;
  3542. };
  3543. _AlphaState.prototype.reset = function () {
  3544. this._alphaBlend = false;
  3545. this._blendFunctionParameters[0] = null;
  3546. this._blendFunctionParameters[1] = null;
  3547. this._blendFunctionParameters[2] = null;
  3548. this._blendFunctionParameters[3] = null;
  3549. this._isAlphaBlendDirty = true;
  3550. this._isBlendFunctionParametersDirty = false;
  3551. };
  3552. _AlphaState.prototype.apply = function (gl) {
  3553. if (!this.isDirty) {
  3554. return;
  3555. }
  3556. // Alpha blend
  3557. if (this._isAlphaBlendDirty) {
  3558. if (this._alphaBlend) {
  3559. gl.enable(gl.BLEND);
  3560. }
  3561. else {
  3562. gl.disable(gl.BLEND);
  3563. }
  3564. this._isAlphaBlendDirty = false;
  3565. }
  3566. // Alpha function
  3567. if (this._isBlendFunctionParametersDirty) {
  3568. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3569. this._isBlendFunctionParametersDirty = false;
  3570. }
  3571. };
  3572. return _AlphaState;
  3573. })();
  3574. BABYLON._AlphaState = _AlphaState;
  3575. var compileShader = function (gl, source, type, defines) {
  3576. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3577. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3578. gl.compileShader(shader);
  3579. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3580. throw new Error(gl.getShaderInfoLog(shader));
  3581. }
  3582. return shader;
  3583. };
  3584. var getWebGLTextureType = function (gl, type) {
  3585. var textureType = gl.UNSIGNED_BYTE;
  3586. if (type === Engine.TEXTURETYPE_FLOAT)
  3587. textureType = gl.FLOAT;
  3588. return textureType;
  3589. };
  3590. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3591. var magFilter = gl.NEAREST;
  3592. var minFilter = gl.NEAREST;
  3593. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3594. magFilter = gl.LINEAR;
  3595. if (generateMipMaps) {
  3596. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3597. }
  3598. else {
  3599. minFilter = gl.LINEAR;
  3600. }
  3601. }
  3602. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3603. magFilter = gl.LINEAR;
  3604. if (generateMipMaps) {
  3605. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3606. }
  3607. else {
  3608. minFilter = gl.LINEAR;
  3609. }
  3610. }
  3611. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3612. magFilter = gl.NEAREST;
  3613. if (generateMipMaps) {
  3614. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3615. }
  3616. else {
  3617. minFilter = gl.NEAREST;
  3618. }
  3619. }
  3620. return {
  3621. min: minFilter,
  3622. mag: magFilter
  3623. };
  3624. };
  3625. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3627. var engine = scene.getEngine();
  3628. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3629. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3630. gl.bindTexture(gl.TEXTURE_2D, texture);
  3631. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3632. processFunction(potWidth, potHeight);
  3633. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3636. if (!noMipmap && !isCompressed) {
  3637. gl.generateMipmap(gl.TEXTURE_2D);
  3638. }
  3639. gl.bindTexture(gl.TEXTURE_2D, null);
  3640. engine._activeTexturesCache = [];
  3641. texture._baseWidth = width;
  3642. texture._baseHeight = height;
  3643. texture._width = potWidth;
  3644. texture._height = potHeight;
  3645. texture.isReady = true;
  3646. texture.samplingMode = samplingMode;
  3647. scene._removePendingData(texture);
  3648. };
  3649. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3650. var onload = function () {
  3651. loadedImages[index] = img;
  3652. loadedImages._internalCount++;
  3653. scene._removePendingData(img);
  3654. if (loadedImages._internalCount === 6) {
  3655. onfinish(loadedImages);
  3656. }
  3657. };
  3658. var onerror = function () {
  3659. scene._removePendingData(img);
  3660. };
  3661. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3662. scene._addPendingData(img);
  3663. };
  3664. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3665. var loadedImages = [];
  3666. loadedImages._internalCount = 0;
  3667. for (var index = 0; index < 6; index++) {
  3668. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3669. }
  3670. };
  3671. var EngineCapabilities = (function () {
  3672. function EngineCapabilities() {
  3673. }
  3674. return EngineCapabilities;
  3675. })();
  3676. BABYLON.EngineCapabilities = EngineCapabilities;
  3677. /**
  3678. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3679. */
  3680. var Engine = (function () {
  3681. /**
  3682. * @constructor
  3683. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3684. * @param {boolean} [antialias] - enable antialias
  3685. * @param options - further options to be sent to the getContext function
  3686. */
  3687. function Engine(canvas, antialias, options) {
  3688. var _this = this;
  3689. // Public members
  3690. this.isFullscreen = false;
  3691. this.isPointerLock = false;
  3692. this.cullBackFaces = true;
  3693. this.renderEvenInBackground = true;
  3694. this.scenes = new Array();
  3695. this._windowIsBackground = false;
  3696. this._loadingDivBackgroundColor = "black";
  3697. this._drawCalls = 0;
  3698. this._renderingQueueLaunched = false;
  3699. this._activeRenderLoops = [];
  3700. // FPS
  3701. this.fpsRange = 60;
  3702. this.previousFramesDuration = [];
  3703. this.fps = 60;
  3704. this.deltaTime = 0;
  3705. // States
  3706. this._depthCullingState = new _DepthCullingState();
  3707. this._alphaState = new _AlphaState();
  3708. this._alphaMode = Engine.ALPHA_DISABLE;
  3709. // Cache
  3710. this._loadedTexturesCache = new Array();
  3711. this._activeTexturesCache = new Array();
  3712. this._compiledEffects = {};
  3713. this._uintIndicesCurrentlySet = false;
  3714. this._renderingCanvas = canvas;
  3715. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3716. options = options || {};
  3717. options.antialias = antialias;
  3718. try {
  3719. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3720. }
  3721. catch (e) {
  3722. throw new Error("WebGL not supported");
  3723. }
  3724. if (!this._gl) {
  3725. throw new Error("WebGL not supported");
  3726. }
  3727. this._onBlur = function () {
  3728. _this._windowIsBackground = true;
  3729. };
  3730. this._onFocus = function () {
  3731. _this._windowIsBackground = false;
  3732. };
  3733. window.addEventListener("blur", this._onBlur);
  3734. window.addEventListener("focus", this._onFocus);
  3735. // Textures
  3736. this._workingCanvas = document.createElement("canvas");
  3737. this._workingContext = this._workingCanvas.getContext("2d");
  3738. // Viewport
  3739. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3740. this.resize();
  3741. // Caps
  3742. this._caps = new EngineCapabilities();
  3743. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3744. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3745. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3746. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3747. // Infos
  3748. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3749. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3750. if (rendererInfo != null) {
  3751. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3752. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3753. }
  3754. if (!this._glVendor) {
  3755. this._glVendor = "Unknown vendor";
  3756. }
  3757. if (!this._glRenderer) {
  3758. this._glRenderer = "Unknown renderer";
  3759. }
  3760. // Extensions
  3761. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3762. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3763. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3764. 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');
  3765. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3766. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3767. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3768. // Depth buffer
  3769. this.setDepthBuffer(true);
  3770. this.setDepthFunctionToLessOrEqual();
  3771. this.setDepthWrite(true);
  3772. // Fullscreen
  3773. this._onFullscreenChange = function () {
  3774. if (document.fullscreen !== undefined) {
  3775. _this.isFullscreen = document.fullscreen;
  3776. }
  3777. else if (document.mozFullScreen !== undefined) {
  3778. _this.isFullscreen = document.mozFullScreen;
  3779. }
  3780. else if (document.webkitIsFullScreen !== undefined) {
  3781. _this.isFullscreen = document.webkitIsFullScreen;
  3782. }
  3783. else if (document.msIsFullScreen !== undefined) {
  3784. _this.isFullscreen = document.msIsFullScreen;
  3785. }
  3786. // Pointer lock
  3787. if (_this.isFullscreen && _this._pointerLockRequested) {
  3788. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3789. if (canvas.requestPointerLock) {
  3790. canvas.requestPointerLock();
  3791. }
  3792. }
  3793. };
  3794. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3795. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3796. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3797. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3798. // Pointer lock
  3799. this._onPointerLockChange = function () {
  3800. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3801. };
  3802. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3803. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3804. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3805. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3806. if (!Engine.audioEngine) {
  3807. Engine.audioEngine = new BABYLON.AudioEngine();
  3808. }
  3809. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3810. }
  3811. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3812. get: function () {
  3813. return Engine._ALPHA_DISABLE;
  3814. },
  3815. enumerable: true,
  3816. configurable: true
  3817. });
  3818. Object.defineProperty(Engine, "ALPHA_ADD", {
  3819. get: function () {
  3820. return Engine._ALPHA_ADD;
  3821. },
  3822. enumerable: true,
  3823. configurable: true
  3824. });
  3825. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3826. get: function () {
  3827. return Engine._ALPHA_COMBINE;
  3828. },
  3829. enumerable: true,
  3830. configurable: true
  3831. });
  3832. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3833. get: function () {
  3834. return Engine._DELAYLOADSTATE_NONE;
  3835. },
  3836. enumerable: true,
  3837. configurable: true
  3838. });
  3839. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3840. get: function () {
  3841. return Engine._DELAYLOADSTATE_LOADED;
  3842. },
  3843. enumerable: true,
  3844. configurable: true
  3845. });
  3846. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3847. get: function () {
  3848. return Engine._DELAYLOADSTATE_LOADING;
  3849. },
  3850. enumerable: true,
  3851. configurable: true
  3852. });
  3853. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3854. get: function () {
  3855. return Engine._DELAYLOADSTATE_NOTLOADED;
  3856. },
  3857. enumerable: true,
  3858. configurable: true
  3859. });
  3860. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3861. get: function () {
  3862. return Engine._TEXTUREFORMAT_ALPHA;
  3863. },
  3864. enumerable: true,
  3865. configurable: true
  3866. });
  3867. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3868. get: function () {
  3869. return Engine._TEXTUREFORMAT_LUMINANCE;
  3870. },
  3871. enumerable: true,
  3872. configurable: true
  3873. });
  3874. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3875. get: function () {
  3876. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3877. },
  3878. enumerable: true,
  3879. configurable: true
  3880. });
  3881. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3882. get: function () {
  3883. return Engine._TEXTUREFORMAT_RGB;
  3884. },
  3885. enumerable: true,
  3886. configurable: true
  3887. });
  3888. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3889. get: function () {
  3890. return Engine._TEXTUREFORMAT_RGBA;
  3891. },
  3892. enumerable: true,
  3893. configurable: true
  3894. });
  3895. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3896. get: function () {
  3897. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3898. },
  3899. enumerable: true,
  3900. configurable: true
  3901. });
  3902. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3903. get: function () {
  3904. return Engine._TEXTURETYPE_FLOAT;
  3905. },
  3906. enumerable: true,
  3907. configurable: true
  3908. });
  3909. Object.defineProperty(Engine, "Version", {
  3910. get: function () {
  3911. return "2.1.0 alpha";
  3912. },
  3913. enumerable: true,
  3914. configurable: true
  3915. });
  3916. Engine.prototype.getGlInfo = function () {
  3917. return {
  3918. vendor: this._glVendor,
  3919. renderer: this._glRenderer,
  3920. version: this._glVersion
  3921. };
  3922. };
  3923. Engine.prototype.getAspectRatio = function (camera) {
  3924. var viewport = camera.viewport;
  3925. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3926. };
  3927. Engine.prototype.getRenderWidth = function () {
  3928. if (this._currentRenderTarget) {
  3929. return this._currentRenderTarget._width;
  3930. }
  3931. return this._renderingCanvas.width;
  3932. };
  3933. Engine.prototype.getRenderHeight = function () {
  3934. if (this._currentRenderTarget) {
  3935. return this._currentRenderTarget._height;
  3936. }
  3937. return this._renderingCanvas.height;
  3938. };
  3939. Engine.prototype.getRenderingCanvas = function () {
  3940. return this._renderingCanvas;
  3941. };
  3942. Engine.prototype.getRenderingCanvasClientRect = function () {
  3943. return this._renderingCanvas.getBoundingClientRect();
  3944. };
  3945. Engine.prototype.setHardwareScalingLevel = function (level) {
  3946. this._hardwareScalingLevel = level;
  3947. this.resize();
  3948. };
  3949. Engine.prototype.getHardwareScalingLevel = function () {
  3950. return this._hardwareScalingLevel;
  3951. };
  3952. Engine.prototype.getLoadedTexturesCache = function () {
  3953. return this._loadedTexturesCache;
  3954. };
  3955. Engine.prototype.getCaps = function () {
  3956. return this._caps;
  3957. };
  3958. Object.defineProperty(Engine.prototype, "drawCalls", {
  3959. get: function () {
  3960. return this._drawCalls;
  3961. },
  3962. enumerable: true,
  3963. configurable: true
  3964. });
  3965. // Methods
  3966. Engine.prototype.resetDrawCalls = function () {
  3967. this._drawCalls = 0;
  3968. };
  3969. Engine.prototype.setDepthFunctionToGreater = function () {
  3970. this._depthCullingState.depthFunc = this._gl.GREATER;
  3971. };
  3972. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3973. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3974. };
  3975. Engine.prototype.setDepthFunctionToLess = function () {
  3976. this._depthCullingState.depthFunc = this._gl.LESS;
  3977. };
  3978. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3979. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3980. };
  3981. /**
  3982. * stop executing a render loop function and remove it from the execution array
  3983. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3984. */
  3985. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3986. if (!renderFunction) {
  3987. this._activeRenderLoops = [];
  3988. return;
  3989. }
  3990. var index = this._activeRenderLoops.indexOf(renderFunction);
  3991. if (index >= 0) {
  3992. this._activeRenderLoops.splice(index, 1);
  3993. }
  3994. };
  3995. Engine.prototype._renderLoop = function () {
  3996. var _this = this;
  3997. var shouldRender = true;
  3998. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3999. shouldRender = false;
  4000. }
  4001. if (shouldRender) {
  4002. // Start new frame
  4003. this.beginFrame();
  4004. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4005. var renderFunction = this._activeRenderLoops[index];
  4006. renderFunction();
  4007. }
  4008. // Present
  4009. this.endFrame();
  4010. }
  4011. if (this._activeRenderLoops.length > 0) {
  4012. // Register new frame
  4013. BABYLON.Tools.QueueNewFrame(function () {
  4014. _this._renderLoop();
  4015. });
  4016. }
  4017. else {
  4018. this._renderingQueueLaunched = false;
  4019. }
  4020. };
  4021. /**
  4022. * Register and execute a render loop. The engine can have more than one render function.
  4023. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4024. * @example
  4025. * engine.runRenderLoop(function () {
  4026. * scene.render()
  4027. * })
  4028. */
  4029. Engine.prototype.runRenderLoop = function (renderFunction) {
  4030. var _this = this;
  4031. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4032. return;
  4033. }
  4034. this._activeRenderLoops.push(renderFunction);
  4035. if (!this._renderingQueueLaunched) {
  4036. this._renderingQueueLaunched = true;
  4037. BABYLON.Tools.QueueNewFrame(function () {
  4038. _this._renderLoop();
  4039. });
  4040. }
  4041. };
  4042. /**
  4043. * Toggle full screen mode.
  4044. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4045. */
  4046. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4047. if (this.isFullscreen) {
  4048. BABYLON.Tools.ExitFullscreen();
  4049. }
  4050. else {
  4051. this._pointerLockRequested = requestPointerLock;
  4052. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4053. }
  4054. };
  4055. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4056. this.applyStates();
  4057. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4058. if (this._depthCullingState.depthMask) {
  4059. this._gl.clearDepth(1.0);
  4060. }
  4061. var mode = 0;
  4062. if (backBuffer)
  4063. mode |= this._gl.COLOR_BUFFER_BIT;
  4064. if (depthStencil && this._depthCullingState.depthMask)
  4065. mode |= this._gl.DEPTH_BUFFER_BIT;
  4066. this._gl.clear(mode);
  4067. };
  4068. /**
  4069. * Set the WebGL's viewport
  4070. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4071. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4072. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4073. */
  4074. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4075. var width = requiredWidth || this._renderingCanvas.width;
  4076. var height = requiredHeight || this._renderingCanvas.height;
  4077. var x = viewport.x || 0;
  4078. var y = viewport.y || 0;
  4079. this._cachedViewport = viewport;
  4080. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4081. };
  4082. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4083. this._cachedViewport = null;
  4084. this._gl.viewport(x, y, width, height);
  4085. };
  4086. Engine.prototype.beginFrame = function () {
  4087. this._measureFps();
  4088. };
  4089. Engine.prototype.endFrame = function () {
  4090. //this.flushFramebuffer();
  4091. };
  4092. /**
  4093. * resize the view according to the canvas' size.
  4094. * @example
  4095. * window.addEventListener("resize", function () {
  4096. * engine.resize();
  4097. * });
  4098. */
  4099. Engine.prototype.resize = function () {
  4100. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4101. };
  4102. /**
  4103. * force a specific size of the canvas
  4104. * @param {number} width - the new canvas' width
  4105. * @param {number} height - the new canvas' height
  4106. */
  4107. Engine.prototype.setSize = function (width, height) {
  4108. this._renderingCanvas.width = width;
  4109. this._renderingCanvas.height = height;
  4110. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4111. };
  4112. Engine.prototype.bindFramebuffer = function (texture) {
  4113. this._currentRenderTarget = texture;
  4114. var gl = this._gl;
  4115. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4116. this._gl.viewport(0, 0, texture._width, texture._height);
  4117. this.wipeCaches();
  4118. };
  4119. Engine.prototype.unBindFramebuffer = function (texture) {
  4120. this._currentRenderTarget = null;
  4121. if (texture.generateMipMaps) {
  4122. var gl = this._gl;
  4123. gl.bindTexture(gl.TEXTURE_2D, texture);
  4124. gl.generateMipmap(gl.TEXTURE_2D);
  4125. gl.bindTexture(gl.TEXTURE_2D, null);
  4126. }
  4127. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4128. };
  4129. Engine.prototype.flushFramebuffer = function () {
  4130. this._gl.flush();
  4131. };
  4132. Engine.prototype.restoreDefaultFramebuffer = function () {
  4133. this._currentRenderTarget = null;
  4134. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4135. this.setViewport(this._cachedViewport);
  4136. this.wipeCaches();
  4137. };
  4138. // VBOs
  4139. Engine.prototype._resetVertexBufferBinding = function () {
  4140. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4141. this._cachedVertexBuffers = null;
  4142. };
  4143. Engine.prototype.createVertexBuffer = function (vertices) {
  4144. var vbo = this._gl.createBuffer();
  4145. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4146. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4147. this._resetVertexBufferBinding();
  4148. vbo.references = 1;
  4149. return vbo;
  4150. };
  4151. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4152. var vbo = this._gl.createBuffer();
  4153. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4154. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4155. this._resetVertexBufferBinding();
  4156. vbo.references = 1;
  4157. return vbo;
  4158. };
  4159. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4160. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4161. if (offset === undefined) {
  4162. offset = 0;
  4163. }
  4164. if (vertices instanceof Float32Array) {
  4165. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4166. }
  4167. else {
  4168. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4169. }
  4170. this._resetVertexBufferBinding();
  4171. };
  4172. Engine.prototype._resetIndexBufferBinding = function () {
  4173. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4174. this._cachedIndexBuffer = null;
  4175. };
  4176. Engine.prototype.createIndexBuffer = function (indices) {
  4177. var vbo = this._gl.createBuffer();
  4178. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4179. // Check for 32 bits indices
  4180. var arrayBuffer;
  4181. var need32Bits = false;
  4182. if (this._caps.uintIndices) {
  4183. for (var index = 0; index < indices.length; index++) {
  4184. if (indices[index] > 65535) {
  4185. need32Bits = true;
  4186. break;
  4187. }
  4188. }
  4189. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4190. }
  4191. else {
  4192. arrayBuffer = new Uint16Array(indices);
  4193. }
  4194. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4195. this._resetIndexBufferBinding();
  4196. vbo.references = 1;
  4197. vbo.is32Bits = need32Bits;
  4198. return vbo;
  4199. };
  4200. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4201. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4202. this._cachedVertexBuffers = vertexBuffer;
  4203. this._cachedEffectForVertexBuffers = effect;
  4204. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4205. var offset = 0;
  4206. for (var index = 0; index < vertexDeclaration.length; index++) {
  4207. var order = effect.getAttributeLocation(index);
  4208. if (order >= 0) {
  4209. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4210. }
  4211. offset += vertexDeclaration[index] * 4;
  4212. }
  4213. }
  4214. if (this._cachedIndexBuffer !== indexBuffer) {
  4215. this._cachedIndexBuffer = indexBuffer;
  4216. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4217. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4218. }
  4219. };
  4220. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4221. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4222. this._cachedVertexBuffers = vertexBuffers;
  4223. this._cachedEffectForVertexBuffers = effect;
  4224. var attributes = effect.getAttributesNames();
  4225. for (var index = 0; index < attributes.length; index++) {
  4226. var order = effect.getAttributeLocation(index);
  4227. if (order >= 0) {
  4228. var vertexBuffer = vertexBuffers[attributes[index]];
  4229. if (!vertexBuffer) {
  4230. continue;
  4231. }
  4232. var stride = vertexBuffer.getStrideSize();
  4233. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4234. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4235. }
  4236. }
  4237. }
  4238. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4239. this._cachedIndexBuffer = indexBuffer;
  4240. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4241. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4242. }
  4243. };
  4244. Engine.prototype._releaseBuffer = function (buffer) {
  4245. buffer.references--;
  4246. if (buffer.references === 0) {
  4247. this._gl.deleteBuffer(buffer);
  4248. return true;
  4249. }
  4250. return false;
  4251. };
  4252. Engine.prototype.createInstancesBuffer = function (capacity) {
  4253. var buffer = this._gl.createBuffer();
  4254. buffer.capacity = capacity;
  4255. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4256. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4257. return buffer;
  4258. };
  4259. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4260. this._gl.deleteBuffer(buffer);
  4261. };
  4262. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4263. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4264. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4265. for (var index = 0; index < 4; index++) {
  4266. var offsetLocation = offsetLocations[index];
  4267. this._gl.enableVertexAttribArray(offsetLocation);
  4268. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4269. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4270. }
  4271. };
  4272. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4273. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4274. for (var index = 0; index < 4; index++) {
  4275. var offsetLocation = offsetLocations[index];
  4276. this._gl.disableVertexAttribArray(offsetLocation);
  4277. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4278. }
  4279. };
  4280. Engine.prototype.applyStates = function () {
  4281. this._depthCullingState.apply(this._gl);
  4282. this._alphaState.apply(this._gl);
  4283. };
  4284. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4285. // Apply states
  4286. this.applyStates();
  4287. this._drawCalls++;
  4288. // Render
  4289. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4290. if (instancesCount) {
  4291. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4292. return;
  4293. }
  4294. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4295. };
  4296. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4297. // Apply states
  4298. this.applyStates();
  4299. this._drawCalls++;
  4300. if (instancesCount) {
  4301. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4302. return;
  4303. }
  4304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4305. };
  4306. // Shaders
  4307. Engine.prototype._releaseEffect = function (effect) {
  4308. if (this._compiledEffects[effect._key]) {
  4309. delete this._compiledEffects[effect._key];
  4310. if (effect.getProgram()) {
  4311. this._gl.deleteProgram(effect.getProgram());
  4312. }
  4313. }
  4314. };
  4315. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4316. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4317. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4318. var name = vertex + "+" + fragment + "@" + defines;
  4319. if (this._compiledEffects[name]) {
  4320. return this._compiledEffects[name];
  4321. }
  4322. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4323. effect._key = name;
  4324. this._compiledEffects[name] = effect;
  4325. return effect;
  4326. };
  4327. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4328. if (uniformsNames === void 0) { uniformsNames = []; }
  4329. if (samplers === void 0) { samplers = []; }
  4330. if (defines === void 0) { defines = ""; }
  4331. return this.createEffect({
  4332. vertex: "particles",
  4333. fragmentElement: fragmentName
  4334. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4335. };
  4336. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4337. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4338. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4339. var shaderProgram = this._gl.createProgram();
  4340. this._gl.attachShader(shaderProgram, vertexShader);
  4341. this._gl.attachShader(shaderProgram, fragmentShader);
  4342. this._gl.linkProgram(shaderProgram);
  4343. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4344. if (!linked) {
  4345. var error = this._gl.getProgramInfoLog(shaderProgram);
  4346. if (error) {
  4347. throw new Error(error);
  4348. }
  4349. }
  4350. this._gl.deleteShader(vertexShader);
  4351. this._gl.deleteShader(fragmentShader);
  4352. return shaderProgram;
  4353. };
  4354. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4355. var results = [];
  4356. for (var index = 0; index < uniformsNames.length; index++) {
  4357. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4358. }
  4359. return results;
  4360. };
  4361. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4362. var results = [];
  4363. for (var index = 0; index < attributesNames.length; index++) {
  4364. try {
  4365. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4366. }
  4367. catch (e) {
  4368. results.push(-1);
  4369. }
  4370. }
  4371. return results;
  4372. };
  4373. Engine.prototype.enableEffect = function (effect) {
  4374. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4375. if (effect && effect.onBind) {
  4376. effect.onBind(effect);
  4377. }
  4378. return;
  4379. }
  4380. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4381. // Use program
  4382. this._gl.useProgram(effect.getProgram());
  4383. for (var i in this._vertexAttribArrays) {
  4384. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4385. continue;
  4386. }
  4387. this._vertexAttribArrays[i] = false;
  4388. this._gl.disableVertexAttribArray(i);
  4389. }
  4390. var attributesCount = effect.getAttributesCount();
  4391. for (var index = 0; index < attributesCount; index++) {
  4392. // Attributes
  4393. var order = effect.getAttributeLocation(index);
  4394. if (order >= 0) {
  4395. this._vertexAttribArrays[order] = true;
  4396. this._gl.enableVertexAttribArray(order);
  4397. }
  4398. }
  4399. this._currentEffect = effect;
  4400. if (effect.onBind) {
  4401. effect.onBind(effect);
  4402. }
  4403. };
  4404. Engine.prototype.setArray = function (uniform, array) {
  4405. if (!uniform)
  4406. return;
  4407. this._gl.uniform1fv(uniform, array);
  4408. };
  4409. Engine.prototype.setArray2 = function (uniform, array) {
  4410. if (!uniform || array.length % 2 !== 0)
  4411. return;
  4412. this._gl.uniform2fv(uniform, array);
  4413. };
  4414. Engine.prototype.setArray3 = function (uniform, array) {
  4415. if (!uniform || array.length % 3 !== 0)
  4416. return;
  4417. this._gl.uniform3fv(uniform, array);
  4418. };
  4419. Engine.prototype.setArray4 = function (uniform, array) {
  4420. if (!uniform || array.length % 4 !== 0)
  4421. return;
  4422. this._gl.uniform4fv(uniform, array);
  4423. };
  4424. Engine.prototype.setMatrices = function (uniform, matrices) {
  4425. if (!uniform)
  4426. return;
  4427. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4428. };
  4429. Engine.prototype.setMatrix = function (uniform, matrix) {
  4430. if (!uniform)
  4431. return;
  4432. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4433. };
  4434. Engine.prototype.setFloat = function (uniform, value) {
  4435. if (!uniform)
  4436. return;
  4437. this._gl.uniform1f(uniform, value);
  4438. };
  4439. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4440. if (!uniform)
  4441. return;
  4442. this._gl.uniform2f(uniform, x, y);
  4443. };
  4444. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4445. if (!uniform)
  4446. return;
  4447. this._gl.uniform3f(uniform, x, y, z);
  4448. };
  4449. Engine.prototype.setBool = function (uniform, bool) {
  4450. if (!uniform)
  4451. return;
  4452. this._gl.uniform1i(uniform, bool);
  4453. };
  4454. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4455. if (!uniform)
  4456. return;
  4457. this._gl.uniform4f(uniform, x, y, z, w);
  4458. };
  4459. Engine.prototype.setColor3 = function (uniform, color3) {
  4460. if (!uniform)
  4461. return;
  4462. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4463. };
  4464. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4465. if (!uniform)
  4466. return;
  4467. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4468. };
  4469. // States
  4470. Engine.prototype.setState = function (culling, force) {
  4471. // Culling
  4472. if (this._depthCullingState.cull !== culling || force) {
  4473. if (culling) {
  4474. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4475. this._depthCullingState.cull = true;
  4476. }
  4477. else {
  4478. this._depthCullingState.cull = false;
  4479. }
  4480. }
  4481. };
  4482. Engine.prototype.setDepthBuffer = function (enable) {
  4483. this._depthCullingState.depthTest = enable;
  4484. };
  4485. Engine.prototype.getDepthWrite = function () {
  4486. return this._depthCullingState.depthMask;
  4487. };
  4488. Engine.prototype.setDepthWrite = function (enable) {
  4489. this._depthCullingState.depthMask = enable;
  4490. };
  4491. Engine.prototype.setColorWrite = function (enable) {
  4492. this._gl.colorMask(enable, enable, enable, enable);
  4493. };
  4494. Engine.prototype.setAlphaMode = function (mode) {
  4495. switch (mode) {
  4496. case Engine.ALPHA_DISABLE:
  4497. this.setDepthWrite(true);
  4498. this._alphaState.alphaBlend = false;
  4499. break;
  4500. case Engine.ALPHA_COMBINE:
  4501. this.setDepthWrite(false);
  4502. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4503. this._alphaState.alphaBlend = true;
  4504. break;
  4505. case Engine.ALPHA_ADD:
  4506. this.setDepthWrite(false);
  4507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4508. this._alphaState.alphaBlend = true;
  4509. break;
  4510. }
  4511. this._alphaMode = mode;
  4512. };
  4513. Engine.prototype.getAlphaMode = function () {
  4514. return this._alphaMode;
  4515. };
  4516. Engine.prototype.setAlphaTesting = function (enable) {
  4517. this._alphaTest = enable;
  4518. };
  4519. Engine.prototype.getAlphaTesting = function () {
  4520. return this._alphaTest;
  4521. };
  4522. // Textures
  4523. Engine.prototype.wipeCaches = function () {
  4524. this._activeTexturesCache = [];
  4525. this._currentEffect = null;
  4526. this._depthCullingState.reset();
  4527. this._alphaState.reset();
  4528. this._cachedVertexBuffers = null;
  4529. this._cachedIndexBuffer = null;
  4530. this._cachedEffectForVertexBuffers = null;
  4531. };
  4532. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4533. var gl = this._gl;
  4534. gl.bindTexture(gl.TEXTURE_2D, texture);
  4535. var magFilter = gl.NEAREST;
  4536. var minFilter = gl.NEAREST;
  4537. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4538. magFilter = gl.LINEAR;
  4539. minFilter = gl.LINEAR;
  4540. }
  4541. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4542. magFilter = gl.LINEAR;
  4543. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4544. }
  4545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4547. gl.bindTexture(gl.TEXTURE_2D, null);
  4548. texture.samplingMode = samplingMode;
  4549. };
  4550. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4551. var _this = this;
  4552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4553. if (onLoad === void 0) { onLoad = null; }
  4554. if (onError === void 0) { onError = null; }
  4555. if (buffer === void 0) { buffer = null; }
  4556. var texture = this._gl.createTexture();
  4557. var extension;
  4558. var fromData = false;
  4559. if (url.substr(0, 5) === "data:") {
  4560. fromData = true;
  4561. }
  4562. if (!fromData)
  4563. extension = url.substr(url.length - 4, 4).toLowerCase();
  4564. else {
  4565. var oldUrl = url;
  4566. fromData = oldUrl.split(':');
  4567. url = oldUrl;
  4568. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4569. }
  4570. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4571. var isTGA = (extension === ".tga");
  4572. scene._addPendingData(texture);
  4573. texture.url = url;
  4574. texture.noMipmap = noMipmap;
  4575. texture.references = 1;
  4576. this._loadedTexturesCache.push(texture);
  4577. var onerror = function () {
  4578. scene._removePendingData(texture);
  4579. if (onError) {
  4580. onError();
  4581. }
  4582. };
  4583. if (isTGA) {
  4584. var callback = function (arrayBuffer) {
  4585. var data = new Uint8Array(arrayBuffer);
  4586. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4587. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4588. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4589. if (onLoad) {
  4590. onLoad();
  4591. }
  4592. }, samplingMode);
  4593. };
  4594. if (!(fromData instanceof Array))
  4595. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4596. callback(arrayBuffer);
  4597. }, onerror, scene.database, true);
  4598. else
  4599. callback(buffer);
  4600. }
  4601. else if (isDDS) {
  4602. callback = function (data) {
  4603. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4604. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4605. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4606. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4607. if (onLoad) {
  4608. onLoad();
  4609. }
  4610. }, samplingMode);
  4611. };
  4612. if (!(fromData instanceof Array))
  4613. BABYLON.Tools.LoadFile(url, function (data) {
  4614. callback(data);
  4615. }, onerror, scene.database, true);
  4616. else
  4617. callback(buffer);
  4618. }
  4619. else {
  4620. var onload = function (img) {
  4621. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4622. var isPot = (img.width === potWidth && img.height === potHeight);
  4623. if (!isPot) {
  4624. _this._workingCanvas.width = potWidth;
  4625. _this._workingCanvas.height = potHeight;
  4626. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4627. _this._workingContext.imageSmoothingEnabled = false;
  4628. _this._workingContext.mozImageSmoothingEnabled = false;
  4629. _this._workingContext.oImageSmoothingEnabled = false;
  4630. _this._workingContext.webkitImageSmoothingEnabled = false;
  4631. _this._workingContext.msImageSmoothingEnabled = false;
  4632. }
  4633. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4634. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4635. _this._workingContext.imageSmoothingEnabled = true;
  4636. _this._workingContext.mozImageSmoothingEnabled = true;
  4637. _this._workingContext.oImageSmoothingEnabled = true;
  4638. _this._workingContext.webkitImageSmoothingEnabled = true;
  4639. _this._workingContext.msImageSmoothingEnabled = true;
  4640. }
  4641. }
  4642. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4643. if (onLoad) {
  4644. onLoad();
  4645. }
  4646. }, samplingMode);
  4647. };
  4648. if (!(fromData instanceof Array))
  4649. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4650. else
  4651. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4652. }
  4653. return texture;
  4654. };
  4655. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4656. var texture = this._gl.createTexture();
  4657. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4658. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4659. // Format
  4660. var internalFormat = this._gl.RGBA;
  4661. switch (format) {
  4662. case Engine.TEXTUREFORMAT_ALPHA:
  4663. internalFormat = this._gl.ALPHA;
  4664. break;
  4665. case Engine.TEXTUREFORMAT_LUMINANCE:
  4666. internalFormat = this._gl.LUMINANCE;
  4667. break;
  4668. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4669. internalFormat = this._gl.LUMINANCE_ALPHA;
  4670. break;
  4671. case Engine.TEXTUREFORMAT_RGB:
  4672. internalFormat = this._gl.RGB;
  4673. break;
  4674. case Engine.TEXTUREFORMAT_RGBA:
  4675. internalFormat = this._gl.RGBA;
  4676. break;
  4677. }
  4678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4679. if (generateMipMaps) {
  4680. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4681. }
  4682. // Filters
  4683. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4686. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4687. this._activeTexturesCache = [];
  4688. texture._baseWidth = width;
  4689. texture._baseHeight = height;
  4690. texture._width = width;
  4691. texture._height = height;
  4692. texture.isReady = true;
  4693. texture.references = 1;
  4694. texture.samplingMode = samplingMode;
  4695. this._loadedTexturesCache.push(texture);
  4696. return texture;
  4697. };
  4698. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4699. var texture = this._gl.createTexture();
  4700. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4701. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4702. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4703. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4704. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4705. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4706. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4707. this._activeTexturesCache = [];
  4708. texture._baseWidth = width;
  4709. texture._baseHeight = height;
  4710. texture._width = width;
  4711. texture._height = height;
  4712. texture.isReady = false;
  4713. texture.generateMipMaps = generateMipMaps;
  4714. texture.references = 1;
  4715. texture.samplingMode = samplingMode;
  4716. this._loadedTexturesCache.push(texture);
  4717. return texture;
  4718. };
  4719. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4720. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4721. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4722. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4723. if (texture.generateMipMaps) {
  4724. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4725. }
  4726. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4727. this._activeTexturesCache = [];
  4728. texture.isReady = true;
  4729. };
  4730. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4731. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4732. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4733. // Scale the video if it is a NPOT using the current working canvas
  4734. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4735. if (!texture._workingCanvas) {
  4736. texture._workingCanvas = document.createElement("canvas");
  4737. texture._workingContext = texture._workingCanvas.getContext("2d");
  4738. texture._workingCanvas.width = texture._width;
  4739. texture._workingCanvas.height = texture._height;
  4740. }
  4741. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4742. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4743. }
  4744. else {
  4745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4746. }
  4747. if (texture.generateMipMaps) {
  4748. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4749. }
  4750. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4751. this._activeTexturesCache = [];
  4752. texture.isReady = true;
  4753. };
  4754. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4755. // old version had a "generateMipMaps" arg instead of options.
  4756. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4757. // in the same way, generateDepthBuffer is defaulted to true
  4758. var generateMipMaps = false;
  4759. var generateDepthBuffer = true;
  4760. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4761. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4762. if (options !== undefined) {
  4763. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4764. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4765. type = options.type === undefined ? type : options.type;
  4766. if (options.samplingMode !== undefined) {
  4767. samplingMode = options.samplingMode;
  4768. }
  4769. if (type === Engine.TEXTURETYPE_FLOAT) {
  4770. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4771. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4772. }
  4773. }
  4774. var gl = this._gl;
  4775. var texture = gl.createTexture();
  4776. gl.bindTexture(gl.TEXTURE_2D, texture);
  4777. var width = size.width || size;
  4778. var height = size.height || size;
  4779. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4780. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4781. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4782. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4783. }
  4784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4788. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4789. var depthBuffer;
  4790. // Create the depth buffer
  4791. if (generateDepthBuffer) {
  4792. depthBuffer = gl.createRenderbuffer();
  4793. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4794. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4795. }
  4796. // Create the framebuffer
  4797. var framebuffer = gl.createFramebuffer();
  4798. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4799. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4800. if (generateDepthBuffer) {
  4801. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4802. }
  4803. // Unbind
  4804. gl.bindTexture(gl.TEXTURE_2D, null);
  4805. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4806. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4807. texture._framebuffer = framebuffer;
  4808. if (generateDepthBuffer) {
  4809. texture._depthBuffer = depthBuffer;
  4810. }
  4811. texture._width = width;
  4812. texture._height = height;
  4813. texture.isReady = true;
  4814. texture.generateMipMaps = generateMipMaps;
  4815. texture.references = 1;
  4816. texture.samplingMode = samplingMode;
  4817. this._activeTexturesCache = [];
  4818. this._loadedTexturesCache.push(texture);
  4819. return texture;
  4820. };
  4821. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4822. var _this = this;
  4823. var gl = this._gl;
  4824. var texture = gl.createTexture();
  4825. texture.isCube = true;
  4826. texture.url = rootUrl;
  4827. texture.references = 1;
  4828. this._loadedTexturesCache.push(texture);
  4829. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4830. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4831. if (isDDS) {
  4832. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4833. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4834. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4835. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4836. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4837. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4838. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4839. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4840. }
  4841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4845. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4846. _this._activeTexturesCache = [];
  4847. texture._width = info.width;
  4848. texture._height = info.height;
  4849. texture.isReady = true;
  4850. }, null, null, true);
  4851. }
  4852. else {
  4853. cascadeLoad(rootUrl, scene, function (imgs) {
  4854. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4855. var height = width;
  4856. _this._workingCanvas.width = width;
  4857. _this._workingCanvas.height = height;
  4858. var faces = [
  4859. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4860. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4861. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4862. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4863. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4864. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4865. ];
  4866. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4867. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4868. for (var index = 0; index < faces.length; index++) {
  4869. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4870. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4871. }
  4872. if (!noMipmap) {
  4873. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4874. }
  4875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4879. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4880. _this._activeTexturesCache = [];
  4881. texture._width = width;
  4882. texture._height = height;
  4883. texture.isReady = true;
  4884. }, extensions);
  4885. }
  4886. return texture;
  4887. };
  4888. Engine.prototype._releaseTexture = function (texture) {
  4889. var gl = this._gl;
  4890. if (texture._framebuffer) {
  4891. gl.deleteFramebuffer(texture._framebuffer);
  4892. }
  4893. if (texture._depthBuffer) {
  4894. gl.deleteRenderbuffer(texture._depthBuffer);
  4895. }
  4896. gl.deleteTexture(texture);
  4897. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4898. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4899. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4900. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4901. this._activeTexturesCache[channel] = null;
  4902. }
  4903. var index = this._loadedTexturesCache.indexOf(texture);
  4904. if (index !== -1) {
  4905. this._loadedTexturesCache.splice(index, 1);
  4906. }
  4907. };
  4908. Engine.prototype.bindSamplers = function (effect) {
  4909. this._gl.useProgram(effect.getProgram());
  4910. var samplers = effect.getSamplers();
  4911. for (var index = 0; index < samplers.length; index++) {
  4912. var uniform = effect.getUniform(samplers[index]);
  4913. this._gl.uniform1i(uniform, index);
  4914. }
  4915. this._currentEffect = null;
  4916. };
  4917. Engine.prototype._bindTexture = function (channel, texture) {
  4918. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4919. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4920. this._activeTexturesCache[channel] = null;
  4921. };
  4922. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4923. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4924. };
  4925. Engine.prototype.setTexture = function (channel, texture) {
  4926. if (channel < 0) {
  4927. return;
  4928. }
  4929. // Not ready?
  4930. if (!texture || !texture.isReady()) {
  4931. if (this._activeTexturesCache[channel] != null) {
  4932. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4933. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4934. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4935. this._activeTexturesCache[channel] = null;
  4936. }
  4937. return;
  4938. }
  4939. // Video
  4940. if (texture instanceof BABYLON.VideoTexture) {
  4941. if (texture.update()) {
  4942. this._activeTexturesCache[channel] = null;
  4943. }
  4944. }
  4945. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4946. texture.delayLoad();
  4947. return;
  4948. }
  4949. if (this._activeTexturesCache[channel] === texture) {
  4950. return;
  4951. }
  4952. this._activeTexturesCache[channel] = texture;
  4953. var internalTexture = texture.getInternalTexture();
  4954. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4955. if (internalTexture.isCube) {
  4956. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4957. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4958. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4959. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4960. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4961. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4962. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4963. }
  4964. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4965. }
  4966. else {
  4967. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4968. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4969. internalTexture._cachedWrapU = texture.wrapU;
  4970. switch (texture.wrapU) {
  4971. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4973. break;
  4974. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4976. break;
  4977. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4978. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4979. break;
  4980. }
  4981. }
  4982. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4983. internalTexture._cachedWrapV = texture.wrapV;
  4984. switch (texture.wrapV) {
  4985. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4986. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4987. break;
  4988. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4989. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4990. break;
  4991. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4992. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4993. break;
  4994. }
  4995. }
  4996. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4997. }
  4998. };
  4999. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5000. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5001. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  5002. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  5003. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  5004. }
  5005. };
  5006. Engine.prototype.readPixels = function (x, y, width, height) {
  5007. var data = new Uint8Array(height * width * 4);
  5008. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5009. return data;
  5010. };
  5011. // Dispose
  5012. Engine.prototype.dispose = function () {
  5013. this.hideLoadingUI();
  5014. this.stopRenderLoop();
  5015. while (this.scenes.length) {
  5016. this.scenes[0].dispose();
  5017. }
  5018. // Release audio engine
  5019. Engine.audioEngine.dispose();
  5020. for (var name in this._compiledEffects) {
  5021. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5022. }
  5023. for (var i in this._vertexAttribArrays) {
  5024. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5025. continue;
  5026. }
  5027. this._gl.disableVertexAttribArray(i);
  5028. }
  5029. // Events
  5030. window.removeEventListener("blur", this._onBlur);
  5031. window.removeEventListener("focus", this._onFocus);
  5032. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5033. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5034. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5035. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5036. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5037. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5038. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5039. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5040. };
  5041. // Loading screen
  5042. Engine.prototype.displayLoadingUI = function () {
  5043. var _this = this;
  5044. this._loadingDiv = document.createElement("div");
  5045. this._loadingDiv.style.opacity = "0";
  5046. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5047. // Loading text
  5048. this._loadingTextDiv = document.createElement("div");
  5049. this._loadingTextDiv.style.position = "absolute";
  5050. this._loadingTextDiv.style.left = "0";
  5051. this._loadingTextDiv.style.top = "50%";
  5052. this._loadingTextDiv.style.marginTop = "80px";
  5053. this._loadingTextDiv.style.width = "100%";
  5054. this._loadingTextDiv.style.height = "20px";
  5055. this._loadingTextDiv.style.fontFamily = "Arial";
  5056. this._loadingTextDiv.style.fontSize = "14px";
  5057. this._loadingTextDiv.style.color = "white";
  5058. this._loadingTextDiv.style.textAlign = "center";
  5059. this._loadingTextDiv.innerHTML = "Loading";
  5060. this._loadingDiv.appendChild(this._loadingTextDiv);
  5061. // Loading img
  5062. var imgBack = new Image();
  5063. 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==";
  5064. imgBack.style.position = "absolute";
  5065. imgBack.style.left = "50%";
  5066. imgBack.style.top = "50%";
  5067. imgBack.style.marginLeft = "-50px";
  5068. imgBack.style.marginTop = "-50px";
  5069. imgBack.style.transition = "transform 1.0s ease";
  5070. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5071. var deg = 360;
  5072. var onTransitionEnd = function () {
  5073. deg += 360;
  5074. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5075. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5076. };
  5077. imgBack.addEventListener("transitionend", onTransitionEnd);
  5078. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5079. this._loadingDiv.appendChild(imgBack);
  5080. // front image
  5081. var imgFront = new Image();
  5082. 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=";
  5083. imgFront.style.position = "absolute";
  5084. imgFront.style.left = "50%";
  5085. imgFront.style.top = "50%";
  5086. imgFront.style.marginLeft = "-50px";
  5087. imgFront.style.marginTop = "-50px";
  5088. this._loadingDiv.appendChild(imgFront);
  5089. // Resize
  5090. this._resizeLoadingUI = function () {
  5091. var canvasRect = _this.getRenderingCanvasClientRect();
  5092. _this._loadingDiv.style.position = "absolute";
  5093. _this._loadingDiv.style.left = canvasRect.left + "px";
  5094. _this._loadingDiv.style.top = canvasRect.top + "px";
  5095. _this._loadingDiv.style.width = canvasRect.width + "px";
  5096. _this._loadingDiv.style.height = canvasRect.height + "px";
  5097. };
  5098. this._resizeLoadingUI();
  5099. window.addEventListener("resize", this._resizeLoadingUI);
  5100. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5101. document.body.appendChild(this._loadingDiv);
  5102. setTimeout(function () {
  5103. _this._loadingDiv.style.opacity = "1";
  5104. imgBack.style.transform = "rotateZ(360deg)";
  5105. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5106. }, 0);
  5107. };
  5108. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5109. set: function (text) {
  5110. if (!this._loadingDiv) {
  5111. return;
  5112. }
  5113. this._loadingTextDiv.innerHTML = text;
  5114. },
  5115. enumerable: true,
  5116. configurable: true
  5117. });
  5118. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5119. get: function () {
  5120. return this._loadingDivBackgroundColor;
  5121. },
  5122. set: function (color) {
  5123. this._loadingDivBackgroundColor = color;
  5124. if (!this._loadingDiv) {
  5125. return;
  5126. }
  5127. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. Engine.prototype.hideLoadingUI = function () {
  5133. var _this = this;
  5134. if (!this._loadingDiv) {
  5135. return;
  5136. }
  5137. var onTransitionEnd = function () {
  5138. if (!_this._loadingDiv) {
  5139. return;
  5140. }
  5141. document.body.removeChild(_this._loadingDiv);
  5142. window.removeEventListener("resize", _this._resizeLoadingUI);
  5143. _this._loadingDiv = null;
  5144. };
  5145. this._loadingDiv.style.opacity = "0";
  5146. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5147. };
  5148. // FPS
  5149. Engine.prototype.getFps = function () {
  5150. return this.fps;
  5151. };
  5152. Engine.prototype.getDeltaTime = function () {
  5153. return this.deltaTime;
  5154. };
  5155. Engine.prototype._measureFps = function () {
  5156. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5157. var length = this.previousFramesDuration.length;
  5158. if (length >= 2) {
  5159. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5160. }
  5161. if (length >= this.fpsRange) {
  5162. if (length > this.fpsRange) {
  5163. this.previousFramesDuration.splice(0, 1);
  5164. length = this.previousFramesDuration.length;
  5165. }
  5166. var sum = 0;
  5167. for (var id = 0; id < length - 1; id++) {
  5168. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5169. }
  5170. this.fps = 1000.0 / (sum / (length - 1));
  5171. }
  5172. };
  5173. // Statics
  5174. Engine.isSupported = function () {
  5175. try {
  5176. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5177. if (navigator.isCocoonJS) {
  5178. return true;
  5179. }
  5180. var tempcanvas = document.createElement("canvas");
  5181. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5182. return gl != null && !!window.WebGLRenderingContext;
  5183. }
  5184. catch (e) {
  5185. return false;
  5186. }
  5187. };
  5188. // Const statics
  5189. Engine._ALPHA_DISABLE = 0;
  5190. Engine._ALPHA_ADD = 1;
  5191. Engine._ALPHA_COMBINE = 2;
  5192. Engine._DELAYLOADSTATE_NONE = 0;
  5193. Engine._DELAYLOADSTATE_LOADED = 1;
  5194. Engine._DELAYLOADSTATE_LOADING = 2;
  5195. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5196. Engine._TEXTUREFORMAT_ALPHA = 0;
  5197. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5198. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5199. Engine._TEXTUREFORMAT_RGB = 4;
  5200. Engine._TEXTUREFORMAT_RGBA = 4;
  5201. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5202. Engine._TEXTURETYPE_FLOAT = 1;
  5203. // Updatable statics so stick with vars here
  5204. Engine.Epsilon = 0.001;
  5205. Engine.CollisionsEpsilon = 0.001;
  5206. Engine.ShadersRepository = "Babylon/Shaders/";
  5207. return Engine;
  5208. })();
  5209. BABYLON.Engine = Engine;
  5210. })(BABYLON || (BABYLON = {}));
  5211. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5212. (function (BABYLON) {
  5213. /**
  5214. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5215. */
  5216. var Node = (function () {
  5217. /**
  5218. * @constructor
  5219. * @param {string} name - the name and id to be given to this node
  5220. * @param {BABYLON.Scene} the scene this node will be added to
  5221. */
  5222. function Node(name, scene) {
  5223. this.state = "";
  5224. this.animations = new Array();
  5225. this._childrenFlag = -1;
  5226. this._isEnabled = true;
  5227. this._isReady = true;
  5228. this._currentRenderId = -1;
  5229. this.name = name;
  5230. this.id = name;
  5231. this._scene = scene;
  5232. this._initCache();
  5233. }
  5234. Node.prototype.getScene = function () {
  5235. return this._scene;
  5236. };
  5237. Node.prototype.getEngine = function () {
  5238. return this._scene.getEngine();
  5239. };
  5240. // override it in derived class
  5241. Node.prototype.getWorldMatrix = function () {
  5242. return BABYLON.Matrix.Identity();
  5243. };
  5244. // override it in derived class if you add new variables to the cache
  5245. // and call the parent class method
  5246. Node.prototype._initCache = function () {
  5247. this._cache = {};
  5248. this._cache.parent = undefined;
  5249. };
  5250. Node.prototype.updateCache = function (force) {
  5251. if (!force && this.isSynchronized())
  5252. return;
  5253. this._cache.parent = this.parent;
  5254. this._updateCache();
  5255. };
  5256. // override it in derived class if you add new variables to the cache
  5257. // and call the parent class method if !ignoreParentClass
  5258. Node.prototype._updateCache = function (ignoreParentClass) {
  5259. };
  5260. // override it in derived class if you add new variables to the cache
  5261. Node.prototype._isSynchronized = function () {
  5262. return true;
  5263. };
  5264. Node.prototype.isSynchronizedWithParent = function () {
  5265. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5266. };
  5267. Node.prototype.isSynchronized = function (updateCache) {
  5268. var check = this.hasNewParent();
  5269. check = check || !this.isSynchronizedWithParent();
  5270. check = check || !this._isSynchronized();
  5271. if (updateCache)
  5272. this.updateCache(true);
  5273. return !check;
  5274. };
  5275. Node.prototype.hasNewParent = function (update) {
  5276. if (this._cache.parent === this.parent)
  5277. return false;
  5278. if (update)
  5279. this._cache.parent = this.parent;
  5280. return true;
  5281. };
  5282. /**
  5283. * Is this node ready to be used/rendered
  5284. * @return {boolean} is it ready
  5285. */
  5286. Node.prototype.isReady = function () {
  5287. return this._isReady;
  5288. };
  5289. /**
  5290. * Is this node enabled.
  5291. * If the node has a parent and is enabled, the parent will be inspected as well.
  5292. * @return {boolean} whether this node (and its parent) is enabled.
  5293. * @see setEnabled
  5294. */
  5295. Node.prototype.isEnabled = function () {
  5296. if (!this._isEnabled) {
  5297. return false;
  5298. }
  5299. if (this.parent) {
  5300. return this.parent.isEnabled();
  5301. }
  5302. return true;
  5303. };
  5304. /**
  5305. * Set the enabled state of this node.
  5306. * @param {boolean} value - the new enabled state
  5307. * @see isEnabled
  5308. */
  5309. Node.prototype.setEnabled = function (value) {
  5310. this._isEnabled = value;
  5311. };
  5312. /**
  5313. * Is this node a descendant of the given node.
  5314. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5315. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5316. * @see parent
  5317. */
  5318. Node.prototype.isDescendantOf = function (ancestor) {
  5319. if (this.parent) {
  5320. if (this.parent === ancestor) {
  5321. return true;
  5322. }
  5323. return this.parent.isDescendantOf(ancestor);
  5324. }
  5325. return false;
  5326. };
  5327. Node.prototype._getDescendants = function (list, results) {
  5328. for (var index = 0; index < list.length; index++) {
  5329. var item = list[index];
  5330. if (item.isDescendantOf(this)) {
  5331. results.push(item);
  5332. }
  5333. }
  5334. };
  5335. /**
  5336. * Will return all nodes that have this node as parent.
  5337. * @return {BABYLON.Node[]} all children nodes of all types.
  5338. */
  5339. Node.prototype.getDescendants = function () {
  5340. var results = [];
  5341. this._getDescendants(this._scene.meshes, results);
  5342. this._getDescendants(this._scene.lights, results);
  5343. this._getDescendants(this._scene.cameras, results);
  5344. return results;
  5345. };
  5346. Node.prototype._setReady = function (state) {
  5347. if (state == this._isReady) {
  5348. return;
  5349. }
  5350. if (!state) {
  5351. this._isReady = false;
  5352. return;
  5353. }
  5354. this._isReady = true;
  5355. if (this.onReady) {
  5356. this.onReady(this);
  5357. }
  5358. };
  5359. return Node;
  5360. })();
  5361. BABYLON.Node = Node;
  5362. })(BABYLON || (BABYLON = {}));
  5363. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5364. (function (BABYLON) {
  5365. var BoundingSphere = (function () {
  5366. function BoundingSphere(minimum, maximum) {
  5367. this.minimum = minimum;
  5368. this.maximum = maximum;
  5369. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5370. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5371. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5372. this.radius = distance * 0.5;
  5373. this.centerWorld = BABYLON.Vector3.Zero();
  5374. this._update(BABYLON.Matrix.Identity());
  5375. }
  5376. // Methods
  5377. BoundingSphere.prototype._update = function (world) {
  5378. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5379. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5380. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5381. };
  5382. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5383. for (var i = 0; i < 6; i++) {
  5384. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5385. return false;
  5386. }
  5387. return true;
  5388. };
  5389. BoundingSphere.prototype.intersectsPoint = function (point) {
  5390. var x = this.centerWorld.x - point.x;
  5391. var y = this.centerWorld.y - point.y;
  5392. var z = this.centerWorld.z - point.z;
  5393. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5394. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5395. return false;
  5396. return true;
  5397. };
  5398. // Statics
  5399. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5400. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5401. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5402. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5403. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5404. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5405. return false;
  5406. return true;
  5407. };
  5408. return BoundingSphere;
  5409. })();
  5410. BABYLON.BoundingSphere = BoundingSphere;
  5411. })(BABYLON || (BABYLON = {}));
  5412. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5413. (function (BABYLON) {
  5414. var BoundingBox = (function () {
  5415. function BoundingBox(minimum, maximum) {
  5416. this.minimum = minimum;
  5417. this.maximum = maximum;
  5418. this.vectors = new Array();
  5419. this.vectorsWorld = new Array();
  5420. // Bounding vectors
  5421. this.vectors.push(this.minimum.clone());
  5422. this.vectors.push(this.maximum.clone());
  5423. this.vectors.push(this.minimum.clone());
  5424. this.vectors[2].x = this.maximum.x;
  5425. this.vectors.push(this.minimum.clone());
  5426. this.vectors[3].y = this.maximum.y;
  5427. this.vectors.push(this.minimum.clone());
  5428. this.vectors[4].z = this.maximum.z;
  5429. this.vectors.push(this.maximum.clone());
  5430. this.vectors[5].z = this.minimum.z;
  5431. this.vectors.push(this.maximum.clone());
  5432. this.vectors[6].x = this.minimum.x;
  5433. this.vectors.push(this.maximum.clone());
  5434. this.vectors[7].y = this.minimum.y;
  5435. // OBB
  5436. this.center = this.maximum.add(this.minimum).scale(0.5);
  5437. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5438. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5439. for (var index = 0; index < this.vectors.length; index++) {
  5440. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5441. }
  5442. this.minimumWorld = BABYLON.Vector3.Zero();
  5443. this.maximumWorld = BABYLON.Vector3.Zero();
  5444. this._update(BABYLON.Matrix.Identity());
  5445. }
  5446. // Methods
  5447. BoundingBox.prototype.getWorldMatrix = function () {
  5448. return this._worldMatrix;
  5449. };
  5450. BoundingBox.prototype._update = function (world) {
  5451. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5452. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5453. for (var index = 0; index < this.vectors.length; index++) {
  5454. var v = this.vectorsWorld[index];
  5455. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5456. if (v.x < this.minimumWorld.x)
  5457. this.minimumWorld.x = v.x;
  5458. if (v.y < this.minimumWorld.y)
  5459. this.minimumWorld.y = v.y;
  5460. if (v.z < this.minimumWorld.z)
  5461. this.minimumWorld.z = v.z;
  5462. if (v.x > this.maximumWorld.x)
  5463. this.maximumWorld.x = v.x;
  5464. if (v.y > this.maximumWorld.y)
  5465. this.maximumWorld.y = v.y;
  5466. if (v.z > this.maximumWorld.z)
  5467. this.maximumWorld.z = v.z;
  5468. }
  5469. // OBB
  5470. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5471. this.center.scaleInPlace(0.5);
  5472. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5473. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5474. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5475. this._worldMatrix = world;
  5476. };
  5477. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5478. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5479. };
  5480. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5481. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5482. };
  5483. BoundingBox.prototype.intersectsPoint = function (point) {
  5484. var delta = BABYLON.Engine.Epsilon;
  5485. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5486. return false;
  5487. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5488. return false;
  5489. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5490. return false;
  5491. return true;
  5492. };
  5493. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5494. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5495. };
  5496. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5497. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5498. return false;
  5499. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5500. return false;
  5501. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5502. return false;
  5503. return true;
  5504. };
  5505. // Statics
  5506. BoundingBox.Intersects = function (box0, box1) {
  5507. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5508. return false;
  5509. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5510. return false;
  5511. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5512. return false;
  5513. return true;
  5514. };
  5515. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5516. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5517. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5518. return (num <= (sphereRadius * sphereRadius));
  5519. };
  5520. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5521. for (var p = 0; p < 6; p++) {
  5522. for (var i = 0; i < 8; i++) {
  5523. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5524. return false;
  5525. }
  5526. }
  5527. }
  5528. return true;
  5529. };
  5530. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5531. for (var p = 0; p < 6; p++) {
  5532. var inCount = 8;
  5533. for (var i = 0; i < 8; i++) {
  5534. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5535. --inCount;
  5536. }
  5537. else {
  5538. break;
  5539. }
  5540. }
  5541. if (inCount === 0)
  5542. return false;
  5543. }
  5544. return true;
  5545. };
  5546. return BoundingBox;
  5547. })();
  5548. BABYLON.BoundingBox = BoundingBox;
  5549. })(BABYLON || (BABYLON = {}));
  5550. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5551. (function (BABYLON) {
  5552. var computeBoxExtents = function (axis, box) {
  5553. var p = BABYLON.Vector3.Dot(box.center, axis);
  5554. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5555. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5556. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5557. var r = r0 + r1 + r2;
  5558. return {
  5559. min: p - r,
  5560. max: p + r
  5561. };
  5562. };
  5563. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5564. var axisOverlap = function (axis, box0, box1) {
  5565. var result0 = computeBoxExtents(axis, box0);
  5566. var result1 = computeBoxExtents(axis, box1);
  5567. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5568. };
  5569. var BoundingInfo = (function () {
  5570. function BoundingInfo(minimum, maximum) {
  5571. this.minimum = minimum;
  5572. this.maximum = maximum;
  5573. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5574. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5575. }
  5576. // Methods
  5577. BoundingInfo.prototype._update = function (world) {
  5578. this.boundingBox._update(world);
  5579. this.boundingSphere._update(world);
  5580. };
  5581. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5582. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5583. return false;
  5584. return this.boundingBox.isInFrustum(frustumPlanes);
  5585. };
  5586. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5587. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5588. };
  5589. BoundingInfo.prototype._checkCollision = function (collider) {
  5590. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5591. };
  5592. BoundingInfo.prototype.intersectsPoint = function (point) {
  5593. if (!this.boundingSphere.centerWorld) {
  5594. return false;
  5595. }
  5596. if (!this.boundingSphere.intersectsPoint(point)) {
  5597. return false;
  5598. }
  5599. if (!this.boundingBox.intersectsPoint(point)) {
  5600. return false;
  5601. }
  5602. return true;
  5603. };
  5604. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5605. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5606. return false;
  5607. }
  5608. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5609. return false;
  5610. }
  5611. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5612. return false;
  5613. }
  5614. if (!precise) {
  5615. return true;
  5616. }
  5617. var box0 = this.boundingBox;
  5618. var box1 = boundingInfo.boundingBox;
  5619. if (!axisOverlap(box0.directions[0], box0, box1))
  5620. return false;
  5621. if (!axisOverlap(box0.directions[1], box0, box1))
  5622. return false;
  5623. if (!axisOverlap(box0.directions[2], box0, box1))
  5624. return false;
  5625. if (!axisOverlap(box1.directions[0], box0, box1))
  5626. return false;
  5627. if (!axisOverlap(box1.directions[1], box0, box1))
  5628. return false;
  5629. if (!axisOverlap(box1.directions[2], box0, box1))
  5630. return false;
  5631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5632. return false;
  5633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5634. return false;
  5635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5636. return false;
  5637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5638. return false;
  5639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5640. return false;
  5641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5642. return false;
  5643. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5644. return false;
  5645. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5646. return false;
  5647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5648. return false;
  5649. return true;
  5650. };
  5651. return BoundingInfo;
  5652. })();
  5653. BABYLON.BoundingInfo = BoundingInfo;
  5654. })(BABYLON || (BABYLON = {}));
  5655. //# sourceMappingURL=babylon.boundingInfo.js.map
  5656. var BABYLON;
  5657. (function (BABYLON) {
  5658. var Light = (function (_super) {
  5659. __extends(Light, _super);
  5660. function Light(name, scene) {
  5661. _super.call(this, name, scene);
  5662. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5663. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5664. this.intensity = 1.0;
  5665. this.range = Number.MAX_VALUE;
  5666. this.includedOnlyMeshes = new Array();
  5667. this.excludedMeshes = new Array();
  5668. this._excludedMeshesIds = new Array();
  5669. this._includedOnlyMeshesIds = new Array();
  5670. scene.lights.push(this);
  5671. }
  5672. Light.prototype.getShadowGenerator = function () {
  5673. return this._shadowGenerator;
  5674. };
  5675. Light.prototype.getAbsolutePosition = function () {
  5676. return BABYLON.Vector3.Zero();
  5677. };
  5678. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5679. };
  5680. Light.prototype._getWorldMatrix = function () {
  5681. return BABYLON.Matrix.Identity();
  5682. };
  5683. Light.prototype.canAffectMesh = function (mesh) {
  5684. if (!mesh) {
  5685. return true;
  5686. }
  5687. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5688. return false;
  5689. }
  5690. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5691. return false;
  5692. }
  5693. return true;
  5694. };
  5695. Light.prototype.getWorldMatrix = function () {
  5696. this._currentRenderId = this.getScene().getRenderId();
  5697. var worldMatrix = this._getWorldMatrix();
  5698. if (this.parent && this.parent.getWorldMatrix) {
  5699. if (!this._parentedWorldMatrix) {
  5700. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5701. }
  5702. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5703. return this._parentedWorldMatrix;
  5704. }
  5705. return worldMatrix;
  5706. };
  5707. Light.prototype.dispose = function () {
  5708. if (this._shadowGenerator) {
  5709. this._shadowGenerator.dispose();
  5710. this._shadowGenerator = null;
  5711. }
  5712. // Remove from scene
  5713. var index = this.getScene().lights.indexOf(this);
  5714. this.getScene().lights.splice(index, 1);
  5715. };
  5716. return Light;
  5717. })(BABYLON.Node);
  5718. BABYLON.Light = Light;
  5719. })(BABYLON || (BABYLON = {}));
  5720. //# sourceMappingURL=babylon.light.js.map
  5721. var BABYLON;
  5722. (function (BABYLON) {
  5723. var PointLight = (function (_super) {
  5724. __extends(PointLight, _super);
  5725. function PointLight(name, position, scene) {
  5726. _super.call(this, name, scene);
  5727. this.position = position;
  5728. }
  5729. PointLight.prototype.getAbsolutePosition = function () {
  5730. return this._transformedPosition ? this._transformedPosition : this.position;
  5731. };
  5732. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5733. if (this.parent && this.parent.getWorldMatrix) {
  5734. if (!this._transformedPosition) {
  5735. this._transformedPosition = BABYLON.Vector3.Zero();
  5736. }
  5737. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5738. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5739. return;
  5740. }
  5741. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5742. };
  5743. PointLight.prototype.getShadowGenerator = function () {
  5744. return null;
  5745. };
  5746. PointLight.prototype._getWorldMatrix = function () {
  5747. if (!this._worldMatrix) {
  5748. this._worldMatrix = BABYLON.Matrix.Identity();
  5749. }
  5750. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5751. return this._worldMatrix;
  5752. };
  5753. return PointLight;
  5754. })(BABYLON.Light);
  5755. BABYLON.PointLight = PointLight;
  5756. })(BABYLON || (BABYLON = {}));
  5757. //# sourceMappingURL=babylon.pointLight.js.map
  5758. var BABYLON;
  5759. (function (BABYLON) {
  5760. var SpotLight = (function (_super) {
  5761. __extends(SpotLight, _super);
  5762. function SpotLight(name, position, direction, angle, exponent, scene) {
  5763. _super.call(this, name, scene);
  5764. this.position = position;
  5765. this.direction = direction;
  5766. this.angle = angle;
  5767. this.exponent = exponent;
  5768. }
  5769. SpotLight.prototype.getAbsolutePosition = function () {
  5770. return this.transformedPosition ? this.transformedPosition : this.position;
  5771. };
  5772. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5773. var activeCamera = this.getScene().activeCamera;
  5774. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5775. };
  5776. SpotLight.prototype.supportsVSM = function () {
  5777. return true;
  5778. };
  5779. SpotLight.prototype.needRefreshPerFrame = function () {
  5780. return false;
  5781. };
  5782. SpotLight.prototype.setDirectionToTarget = function (target) {
  5783. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5784. return this.direction;
  5785. };
  5786. SpotLight.prototype.computeTransformedPosition = function () {
  5787. if (this.parent && this.parent.getWorldMatrix) {
  5788. if (!this.transformedPosition) {
  5789. this.transformedPosition = BABYLON.Vector3.Zero();
  5790. }
  5791. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5792. return true;
  5793. }
  5794. return false;
  5795. };
  5796. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5797. var normalizeDirection;
  5798. if (this.parent && this.parent.getWorldMatrix) {
  5799. if (!this._transformedDirection) {
  5800. this._transformedDirection = BABYLON.Vector3.Zero();
  5801. }
  5802. this.computeTransformedPosition();
  5803. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5804. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5805. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5806. }
  5807. else {
  5808. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5809. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5810. }
  5811. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5812. };
  5813. SpotLight.prototype._getWorldMatrix = function () {
  5814. if (!this._worldMatrix) {
  5815. this._worldMatrix = BABYLON.Matrix.Identity();
  5816. }
  5817. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5818. return this._worldMatrix;
  5819. };
  5820. return SpotLight;
  5821. })(BABYLON.Light);
  5822. BABYLON.SpotLight = SpotLight;
  5823. })(BABYLON || (BABYLON = {}));
  5824. //# sourceMappingURL=babylon.spotLight.js.map
  5825. var BABYLON;
  5826. (function (BABYLON) {
  5827. var DirectionalLight = (function (_super) {
  5828. __extends(DirectionalLight, _super);
  5829. function DirectionalLight(name, direction, scene) {
  5830. _super.call(this, name, scene);
  5831. this.direction = direction;
  5832. this.shadowOrthoScale = 0.1;
  5833. this.position = direction.scale(-1);
  5834. }
  5835. DirectionalLight.prototype.getAbsolutePosition = function () {
  5836. return this.transformedPosition ? this.transformedPosition : this.position;
  5837. };
  5838. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5839. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5840. return this.direction;
  5841. };
  5842. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5843. var orthoLeft = Number.MAX_VALUE;
  5844. var orthoRight = Number.MIN_VALUE;
  5845. var orthoTop = Number.MIN_VALUE;
  5846. var orthoBottom = Number.MAX_VALUE;
  5847. var tempVector3 = BABYLON.Vector3.Zero();
  5848. var activeCamera = this.getScene().activeCamera;
  5849. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5850. var mesh = renderList[meshIndex];
  5851. if (!mesh) {
  5852. continue;
  5853. }
  5854. var boundingInfo = mesh.getBoundingInfo();
  5855. if (!boundingInfo) {
  5856. continue;
  5857. }
  5858. var boundingBox = boundingInfo.boundingBox;
  5859. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5860. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5861. if (tempVector3.x < orthoLeft)
  5862. orthoLeft = tempVector3.x;
  5863. if (tempVector3.y < orthoBottom)
  5864. orthoBottom = tempVector3.y;
  5865. if (tempVector3.x > orthoRight)
  5866. orthoRight = tempVector3.x;
  5867. if (tempVector3.y > orthoTop)
  5868. orthoTop = tempVector3.y;
  5869. }
  5870. }
  5871. var xOffset = orthoRight - orthoLeft;
  5872. var yOffset = orthoTop - orthoBottom;
  5873. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5874. };
  5875. DirectionalLight.prototype.supportsVSM = function () {
  5876. return true;
  5877. };
  5878. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5879. return true;
  5880. };
  5881. DirectionalLight.prototype.computeTransformedPosition = function () {
  5882. if (this.parent && this.parent.getWorldMatrix) {
  5883. if (!this.transformedPosition) {
  5884. this.transformedPosition = BABYLON.Vector3.Zero();
  5885. }
  5886. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5887. return true;
  5888. }
  5889. return false;
  5890. };
  5891. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5892. if (this.parent && this.parent.getWorldMatrix) {
  5893. if (!this._transformedDirection) {
  5894. this._transformedDirection = BABYLON.Vector3.Zero();
  5895. }
  5896. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5897. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5898. return;
  5899. }
  5900. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5901. };
  5902. DirectionalLight.prototype._getWorldMatrix = function () {
  5903. if (!this._worldMatrix) {
  5904. this._worldMatrix = BABYLON.Matrix.Identity();
  5905. }
  5906. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5907. return this._worldMatrix;
  5908. };
  5909. return DirectionalLight;
  5910. })(BABYLON.Light);
  5911. BABYLON.DirectionalLight = DirectionalLight;
  5912. })(BABYLON || (BABYLON = {}));
  5913. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5914. (function (BABYLON) {
  5915. var ShadowGenerator = (function () {
  5916. function ShadowGenerator(mapSize, light) {
  5917. var _this = this;
  5918. // Members
  5919. this.filter = ShadowGenerator.FILTER_NONE;
  5920. this.blurScale = 2;
  5921. this._blurBoxOffset = 0;
  5922. this._bias = 0.00005;
  5923. this._darkness = 0;
  5924. this._transparencyShadow = false;
  5925. this._viewMatrix = BABYLON.Matrix.Zero();
  5926. this._projectionMatrix = BABYLON.Matrix.Zero();
  5927. this._transformMatrix = BABYLON.Matrix.Zero();
  5928. this._worldViewProjection = BABYLON.Matrix.Zero();
  5929. this._light = light;
  5930. this._scene = light.getScene();
  5931. this._mapSize = mapSize;
  5932. light._shadowGenerator = this;
  5933. // Render target
  5934. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5935. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5936. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5937. this._shadowMap.renderParticles = false;
  5938. this._shadowMap.onAfterUnbind = function () {
  5939. if (!_this.useBlurVarianceShadowMap) {
  5940. return;
  5941. }
  5942. if (!_this._shadowMap2) {
  5943. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5944. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5945. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5946. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5947. _this._downSamplePostprocess.onApply = function (effect) {
  5948. effect.setTexture("textureSampler", _this._shadowMap);
  5949. };
  5950. _this.blurBoxOffset = 1;
  5951. }
  5952. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5953. };
  5954. // Custom render function
  5955. var renderSubMesh = function (subMesh) {
  5956. var mesh = subMesh.getRenderingMesh();
  5957. var scene = _this._scene;
  5958. var engine = scene.getEngine();
  5959. // Culling
  5960. engine.setState(subMesh.getMaterial().backFaceCulling);
  5961. // Managing instances
  5962. var batch = mesh._getInstancesRenderList(subMesh._id);
  5963. if (batch.mustReturn) {
  5964. return;
  5965. }
  5966. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5967. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5968. engine.enableEffect(_this._effect);
  5969. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5970. var material = subMesh.getMaterial();
  5971. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5972. // Alpha test
  5973. if (material && material.needAlphaTesting()) {
  5974. var alphaTexture = material.getAlphaTestTexture();
  5975. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5976. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5977. }
  5978. // Bones
  5979. if (mesh.useBones) {
  5980. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5981. }
  5982. // Draw
  5983. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5984. }
  5985. else {
  5986. // Need to reset refresh rate of the shadowMap
  5987. _this._shadowMap.resetRefreshCounter();
  5988. }
  5989. };
  5990. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5991. var index;
  5992. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5993. renderSubMesh(opaqueSubMeshes.data[index]);
  5994. }
  5995. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5996. renderSubMesh(alphaTestSubMeshes.data[index]);
  5997. }
  5998. if (_this._transparencyShadow) {
  5999. for (index = 0; index < transparentSubMeshes.length; index++) {
  6000. renderSubMesh(transparentSubMeshes.data[index]);
  6001. }
  6002. }
  6003. };
  6004. this._shadowMap.onClear = function (engine) {
  6005. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6006. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6007. }
  6008. else {
  6009. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6010. }
  6011. };
  6012. }
  6013. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6014. // Static
  6015. get: function () {
  6016. return ShadowGenerator._FILTER_NONE;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6022. get: function () {
  6023. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6029. get: function () {
  6030. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6031. },
  6032. enumerable: true,
  6033. configurable: true
  6034. });
  6035. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6036. get: function () {
  6037. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6038. },
  6039. enumerable: true,
  6040. configurable: true
  6041. });
  6042. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6043. get: function () {
  6044. return this._bias;
  6045. },
  6046. set: function (bias) {
  6047. this._bias = bias;
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6053. get: function () {
  6054. return this._blurBoxOffset;
  6055. },
  6056. set: function (value) {
  6057. var _this = this;
  6058. if (this._blurBoxOffset === value) {
  6059. return;
  6060. }
  6061. this._blurBoxOffset = value;
  6062. if (this._boxBlurPostprocess) {
  6063. this._boxBlurPostprocess.dispose();
  6064. }
  6065. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6066. this._boxBlurPostprocess.onApply = function (effect) {
  6067. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6068. };
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6074. get: function () {
  6075. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6076. },
  6077. set: function (value) {
  6078. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6079. },
  6080. enumerable: true,
  6081. configurable: true
  6082. });
  6083. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6084. get: function () {
  6085. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6086. },
  6087. set: function (value) {
  6088. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6094. get: function () {
  6095. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6096. },
  6097. set: function (value) {
  6098. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6104. var defines = [];
  6105. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6106. defines.push("#define VSM");
  6107. }
  6108. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6109. var mesh = subMesh.getMesh();
  6110. var material = subMesh.getMaterial();
  6111. // Alpha test
  6112. if (material && material.needAlphaTesting()) {
  6113. defines.push("#define ALPHATEST");
  6114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6115. attribs.push(BABYLON.VertexBuffer.UVKind);
  6116. defines.push("#define UV1");
  6117. }
  6118. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6119. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6120. defines.push("#define UV2");
  6121. }
  6122. }
  6123. // Bones
  6124. if (mesh.useBones) {
  6125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6127. defines.push("#define BONES");
  6128. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6129. }
  6130. // Instances
  6131. if (useInstances) {
  6132. defines.push("#define INSTANCES");
  6133. attribs.push("world0");
  6134. attribs.push("world1");
  6135. attribs.push("world2");
  6136. attribs.push("world3");
  6137. }
  6138. // Get correct effect
  6139. var join = defines.join("\n");
  6140. if (this._cachedDefines !== join) {
  6141. this._cachedDefines = join;
  6142. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6143. }
  6144. return this._effect.isReady();
  6145. };
  6146. ShadowGenerator.prototype.getShadowMap = function () {
  6147. return this._shadowMap;
  6148. };
  6149. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6150. if (this._shadowMap2) {
  6151. return this._shadowMap2;
  6152. }
  6153. return this._shadowMap;
  6154. };
  6155. ShadowGenerator.prototype.getLight = function () {
  6156. return this._light;
  6157. };
  6158. // Methods
  6159. ShadowGenerator.prototype.getTransformMatrix = function () {
  6160. var scene = this._scene;
  6161. if (this._currentRenderID === scene.getRenderId()) {
  6162. return this._transformMatrix;
  6163. }
  6164. this._currentRenderID = scene.getRenderId();
  6165. var lightPosition = this._light.position;
  6166. var lightDirection = this._light.direction;
  6167. if (this._light.computeTransformedPosition()) {
  6168. lightPosition = this._light.transformedPosition;
  6169. }
  6170. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6171. this._cachedPosition = lightPosition.clone();
  6172. this._cachedDirection = lightDirection.clone();
  6173. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6174. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6175. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6176. }
  6177. return this._transformMatrix;
  6178. };
  6179. ShadowGenerator.prototype.getDarkness = function () {
  6180. return this._darkness;
  6181. };
  6182. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6183. if (darkness >= 1.0)
  6184. this._darkness = 1.0;
  6185. else if (darkness <= 0.0)
  6186. this._darkness = 0.0;
  6187. else
  6188. this._darkness = darkness;
  6189. };
  6190. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6191. this._transparencyShadow = hasShadow;
  6192. };
  6193. ShadowGenerator.prototype._packHalf = function (depth) {
  6194. var scale = depth * 255.0;
  6195. var fract = scale - Math.floor(scale);
  6196. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6197. };
  6198. ShadowGenerator.prototype.dispose = function () {
  6199. this._shadowMap.dispose();
  6200. if (this._shadowMap2) {
  6201. this._shadowMap2.dispose();
  6202. }
  6203. if (this._downSamplePostprocess) {
  6204. this._downSamplePostprocess.dispose();
  6205. }
  6206. if (this._boxBlurPostprocess) {
  6207. this._boxBlurPostprocess.dispose();
  6208. }
  6209. };
  6210. ShadowGenerator._FILTER_NONE = 0;
  6211. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6212. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6213. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6214. return ShadowGenerator;
  6215. })();
  6216. BABYLON.ShadowGenerator = ShadowGenerator;
  6217. })(BABYLON || (BABYLON = {}));
  6218. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6219. var BABYLON;
  6220. (function (BABYLON) {
  6221. var HemisphericLight = (function (_super) {
  6222. __extends(HemisphericLight, _super);
  6223. function HemisphericLight(name, direction, scene) {
  6224. _super.call(this, name, scene);
  6225. this.direction = direction;
  6226. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6227. }
  6228. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6229. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6230. return this.direction;
  6231. };
  6232. HemisphericLight.prototype.getShadowGenerator = function () {
  6233. return null;
  6234. };
  6235. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6236. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6237. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6238. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6239. };
  6240. HemisphericLight.prototype._getWorldMatrix = function () {
  6241. if (!this._worldMatrix) {
  6242. this._worldMatrix = BABYLON.Matrix.Identity();
  6243. }
  6244. return this._worldMatrix;
  6245. };
  6246. return HemisphericLight;
  6247. })(BABYLON.Light);
  6248. BABYLON.HemisphericLight = HemisphericLight;
  6249. })(BABYLON || (BABYLON = {}));
  6250. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6251. (function (BABYLON) {
  6252. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6253. if (boxMin.x > sphereCenter.x + sphereRadius)
  6254. return false;
  6255. if (sphereCenter.x - sphereRadius > boxMax.x)
  6256. return false;
  6257. if (boxMin.y > sphereCenter.y + sphereRadius)
  6258. return false;
  6259. if (sphereCenter.y - sphereRadius > boxMax.y)
  6260. return false;
  6261. if (boxMin.z > sphereCenter.z + sphereRadius)
  6262. return false;
  6263. if (sphereCenter.z - sphereRadius > boxMax.z)
  6264. return false;
  6265. return true;
  6266. };
  6267. var getLowestRoot = function (a, b, c, maxR) {
  6268. var determinant = b * b - 4.0 * a * c;
  6269. var result = { root: 0, found: false };
  6270. if (determinant < 0)
  6271. return result;
  6272. var sqrtD = Math.sqrt(determinant);
  6273. var r1 = (-b - sqrtD) / (2.0 * a);
  6274. var r2 = (-b + sqrtD) / (2.0 * a);
  6275. if (r1 > r2) {
  6276. var temp = r2;
  6277. r2 = r1;
  6278. r1 = temp;
  6279. }
  6280. if (r1 > 0 && r1 < maxR) {
  6281. result.root = r1;
  6282. result.found = true;
  6283. return result;
  6284. }
  6285. if (r2 > 0 && r2 < maxR) {
  6286. result.root = r2;
  6287. result.found = true;
  6288. return result;
  6289. }
  6290. return result;
  6291. };
  6292. var Collider = (function () {
  6293. function Collider() {
  6294. this.radius = new BABYLON.Vector3(1, 1, 1);
  6295. this.retry = 0;
  6296. this.basePointWorld = BABYLON.Vector3.Zero();
  6297. this.velocityWorld = BABYLON.Vector3.Zero();
  6298. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6299. this._collisionPoint = BABYLON.Vector3.Zero();
  6300. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6301. this._tempVector = BABYLON.Vector3.Zero();
  6302. this._tempVector2 = BABYLON.Vector3.Zero();
  6303. this._tempVector3 = BABYLON.Vector3.Zero();
  6304. this._tempVector4 = BABYLON.Vector3.Zero();
  6305. this._edge = BABYLON.Vector3.Zero();
  6306. this._baseToVertex = BABYLON.Vector3.Zero();
  6307. this._destinationPoint = BABYLON.Vector3.Zero();
  6308. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6309. this._displacementVector = BABYLON.Vector3.Zero();
  6310. }
  6311. // Methods
  6312. Collider.prototype._initialize = function (source, dir, e) {
  6313. this.velocity = dir;
  6314. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6315. this.basePoint = source;
  6316. source.multiplyToRef(this.radius, this.basePointWorld);
  6317. dir.multiplyToRef(this.radius, this.velocityWorld);
  6318. this.velocityWorldLength = this.velocityWorld.length();
  6319. this.epsilon = e;
  6320. this.collisionFound = false;
  6321. };
  6322. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6323. pa.subtractToRef(point, this._tempVector);
  6324. pb.subtractToRef(point, this._tempVector2);
  6325. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6326. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6327. if (d < 0)
  6328. return false;
  6329. pc.subtractToRef(point, this._tempVector3);
  6330. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6331. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6332. if (d < 0)
  6333. return false;
  6334. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6335. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6336. return d >= 0;
  6337. };
  6338. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6339. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6340. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6341. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6342. return false;
  6343. }
  6344. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6345. return false;
  6346. return true;
  6347. };
  6348. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6349. var t0;
  6350. var embeddedInPlane = false;
  6351. if (!subMesh._trianglePlanes) {
  6352. subMesh._trianglePlanes = [];
  6353. }
  6354. if (!subMesh._trianglePlanes[faceIndex]) {
  6355. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6356. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6357. }
  6358. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6359. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6360. return;
  6361. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6362. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6363. if (normalDotVelocity == 0) {
  6364. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6365. return;
  6366. embeddedInPlane = true;
  6367. t0 = 0;
  6368. }
  6369. else {
  6370. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6371. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6372. if (t0 > t1) {
  6373. var temp = t1;
  6374. t1 = t0;
  6375. t0 = temp;
  6376. }
  6377. if (t0 > 1.0 || t1 < 0.0)
  6378. return;
  6379. if (t0 < 0)
  6380. t0 = 0;
  6381. if (t0 > 1.0)
  6382. t0 = 1.0;
  6383. }
  6384. this._collisionPoint.copyFromFloats(0, 0, 0);
  6385. var found = false;
  6386. var t = 1.0;
  6387. if (!embeddedInPlane) {
  6388. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6389. this.velocity.scaleToRef(t0, this._tempVector);
  6390. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6391. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6392. found = true;
  6393. t = t0;
  6394. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6395. }
  6396. }
  6397. if (!found) {
  6398. var velocitySquaredLength = this.velocity.lengthSquared();
  6399. var a = velocitySquaredLength;
  6400. this.basePoint.subtractToRef(p1, this._tempVector);
  6401. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6402. var c = this._tempVector.lengthSquared() - 1.0;
  6403. var lowestRoot = getLowestRoot(a, b, c, t);
  6404. if (lowestRoot.found) {
  6405. t = lowestRoot.root;
  6406. found = true;
  6407. this._collisionPoint.copyFrom(p1);
  6408. }
  6409. this.basePoint.subtractToRef(p2, this._tempVector);
  6410. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6411. c = this._tempVector.lengthSquared() - 1.0;
  6412. lowestRoot = getLowestRoot(a, b, c, t);
  6413. if (lowestRoot.found) {
  6414. t = lowestRoot.root;
  6415. found = true;
  6416. this._collisionPoint.copyFrom(p2);
  6417. }
  6418. this.basePoint.subtractToRef(p3, this._tempVector);
  6419. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6420. c = this._tempVector.lengthSquared() - 1.0;
  6421. lowestRoot = getLowestRoot(a, b, c, t);
  6422. if (lowestRoot.found) {
  6423. t = lowestRoot.root;
  6424. found = true;
  6425. this._collisionPoint.copyFrom(p3);
  6426. }
  6427. p2.subtractToRef(p1, this._edge);
  6428. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6429. var edgeSquaredLength = this._edge.lengthSquared();
  6430. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6431. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6432. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6433. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6434. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6435. lowestRoot = getLowestRoot(a, b, c, t);
  6436. if (lowestRoot.found) {
  6437. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6438. if (f >= 0.0 && f <= 1.0) {
  6439. t = lowestRoot.root;
  6440. found = true;
  6441. this._edge.scaleInPlace(f);
  6442. p1.addToRef(this._edge, this._collisionPoint);
  6443. }
  6444. }
  6445. p3.subtractToRef(p2, this._edge);
  6446. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6447. edgeSquaredLength = this._edge.lengthSquared();
  6448. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6449. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6450. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6451. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6452. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6453. lowestRoot = getLowestRoot(a, b, c, t);
  6454. if (lowestRoot.found) {
  6455. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6456. if (f >= 0.0 && f <= 1.0) {
  6457. t = lowestRoot.root;
  6458. found = true;
  6459. this._edge.scaleInPlace(f);
  6460. p2.addToRef(this._edge, this._collisionPoint);
  6461. }
  6462. }
  6463. p1.subtractToRef(p3, this._edge);
  6464. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6465. edgeSquaredLength = this._edge.lengthSquared();
  6466. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6467. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6468. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6469. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6470. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6471. lowestRoot = getLowestRoot(a, b, c, t);
  6472. if (lowestRoot.found) {
  6473. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6474. if (f >= 0.0 && f <= 1.0) {
  6475. t = lowestRoot.root;
  6476. found = true;
  6477. this._edge.scaleInPlace(f);
  6478. p3.addToRef(this._edge, this._collisionPoint);
  6479. }
  6480. }
  6481. }
  6482. if (found) {
  6483. var distToCollision = t * this.velocity.length();
  6484. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6485. if (!this.intersectionPoint) {
  6486. this.intersectionPoint = this._collisionPoint.clone();
  6487. }
  6488. else {
  6489. this.intersectionPoint.copyFrom(this._collisionPoint);
  6490. }
  6491. this.nearestDistance = distToCollision;
  6492. this.collisionFound = true;
  6493. this.collidedMesh = subMesh.getMesh();
  6494. }
  6495. }
  6496. };
  6497. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6498. for (var i = indexStart; i < indexEnd; i += 3) {
  6499. var p1 = pts[indices[i] - decal];
  6500. var p2 = pts[indices[i + 1] - decal];
  6501. var p3 = pts[indices[i + 2] - decal];
  6502. this._testTriangle(i, subMesh, p3, p2, p1);
  6503. }
  6504. };
  6505. Collider.prototype._getResponse = function (pos, vel) {
  6506. pos.addToRef(vel, this._destinationPoint);
  6507. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6508. this.basePoint.addToRef(vel, pos);
  6509. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6510. this._slidePlaneNormal.normalize();
  6511. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6512. pos.addInPlace(this._displacementVector);
  6513. this.intersectionPoint.addInPlace(this._displacementVector);
  6514. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6515. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6516. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6517. };
  6518. return Collider;
  6519. })();
  6520. BABYLON.Collider = Collider;
  6521. })(BABYLON || (BABYLON = {}));
  6522. //# sourceMappingURL=babylon.collider.js.map
  6523. var BABYLON;
  6524. (function (BABYLON) {
  6525. var Camera = (function (_super) {
  6526. __extends(Camera, _super);
  6527. function Camera(name, position, scene) {
  6528. _super.call(this, name, scene);
  6529. this.position = position;
  6530. // Members
  6531. this.upVector = BABYLON.Vector3.Up();
  6532. this.orthoLeft = null;
  6533. this.orthoRight = null;
  6534. this.orthoBottom = null;
  6535. this.orthoTop = null;
  6536. this.fov = 0.8;
  6537. this.minZ = 1.0;
  6538. this.maxZ = 10000.0;
  6539. this.inertia = 0.9;
  6540. this.mode = Camera.PERSPECTIVE_CAMERA;
  6541. this.isIntermediate = false;
  6542. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6543. this.subCameras = [];
  6544. this.layerMask = 0xFFFFFFFF;
  6545. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6546. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6547. this._projectionMatrix = new BABYLON.Matrix();
  6548. this._postProcesses = new Array();
  6549. this._postProcessesTakenIndices = [];
  6550. this._activeMeshes = new BABYLON.SmartArray(256);
  6551. scene.cameras.push(this);
  6552. if (!scene.activeCamera) {
  6553. scene.activeCamera = this;
  6554. }
  6555. }
  6556. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6557. get: function () {
  6558. return Camera._PERSPECTIVE_CAMERA;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6564. get: function () {
  6565. return Camera._ORTHOGRAPHIC_CAMERA;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6571. get: function () {
  6572. return Camera._FOVMODE_VERTICAL_FIXED;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6578. get: function () {
  6579. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Camera.prototype.getActiveMeshes = function () {
  6585. return this._activeMeshes;
  6586. };
  6587. Camera.prototype.isActiveMesh = function (mesh) {
  6588. return (this._activeMeshes.indexOf(mesh) !== -1);
  6589. };
  6590. //Cache
  6591. Camera.prototype._initCache = function () {
  6592. _super.prototype._initCache.call(this);
  6593. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6594. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6595. this._cache.mode = undefined;
  6596. this._cache.minZ = undefined;
  6597. this._cache.maxZ = undefined;
  6598. this._cache.fov = undefined;
  6599. this._cache.aspectRatio = undefined;
  6600. this._cache.orthoLeft = undefined;
  6601. this._cache.orthoRight = undefined;
  6602. this._cache.orthoBottom = undefined;
  6603. this._cache.orthoTop = undefined;
  6604. this._cache.renderWidth = undefined;
  6605. this._cache.renderHeight = undefined;
  6606. };
  6607. Camera.prototype._updateCache = function (ignoreParentClass) {
  6608. if (!ignoreParentClass) {
  6609. _super.prototype._updateCache.call(this);
  6610. }
  6611. var engine = this.getEngine();
  6612. this._cache.position.copyFrom(this.position);
  6613. this._cache.upVector.copyFrom(this.upVector);
  6614. this._cache.mode = this.mode;
  6615. this._cache.minZ = this.minZ;
  6616. this._cache.maxZ = this.maxZ;
  6617. this._cache.fov = this.fov;
  6618. this._cache.aspectRatio = engine.getAspectRatio(this);
  6619. this._cache.orthoLeft = this.orthoLeft;
  6620. this._cache.orthoRight = this.orthoRight;
  6621. this._cache.orthoBottom = this.orthoBottom;
  6622. this._cache.orthoTop = this.orthoTop;
  6623. this._cache.renderWidth = engine.getRenderWidth();
  6624. this._cache.renderHeight = engine.getRenderHeight();
  6625. };
  6626. Camera.prototype._updateFromScene = function () {
  6627. this.updateCache();
  6628. this._update();
  6629. };
  6630. // Synchronized
  6631. Camera.prototype._isSynchronized = function () {
  6632. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6633. };
  6634. Camera.prototype._isSynchronizedViewMatrix = function () {
  6635. if (!_super.prototype._isSynchronized.call(this))
  6636. return false;
  6637. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6638. };
  6639. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6640. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6641. if (!check) {
  6642. return false;
  6643. }
  6644. var engine = this.getEngine();
  6645. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6646. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6647. }
  6648. else {
  6649. 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();
  6650. }
  6651. return check;
  6652. };
  6653. // Controls
  6654. Camera.prototype.attachControl = function (element) {
  6655. };
  6656. Camera.prototype.detachControl = function (element) {
  6657. };
  6658. Camera.prototype._update = function () {
  6659. };
  6660. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6661. if (insertAt === void 0) { insertAt = null; }
  6662. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6663. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6664. return 0;
  6665. }
  6666. if (insertAt == null || insertAt < 0) {
  6667. this._postProcesses.push(postProcess);
  6668. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6669. return this._postProcesses.length - 1;
  6670. }
  6671. var add = 0;
  6672. if (this._postProcesses[insertAt]) {
  6673. var start = this._postProcesses.length - 1;
  6674. for (var i = start; i >= insertAt + 1; --i) {
  6675. this._postProcesses[i + 1] = this._postProcesses[i];
  6676. }
  6677. add = 1;
  6678. }
  6679. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6680. if (this._postProcessesTakenIndices[i] < insertAt) {
  6681. continue;
  6682. }
  6683. start = this._postProcessesTakenIndices.length - 1;
  6684. for (var j = start; j >= i; --j) {
  6685. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6686. }
  6687. this._postProcessesTakenIndices[i] = insertAt;
  6688. break;
  6689. }
  6690. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6691. this._postProcessesTakenIndices.push(insertAt);
  6692. }
  6693. var result = insertAt + add;
  6694. this._postProcesses[result] = postProcess;
  6695. return result;
  6696. };
  6697. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6698. if (atIndices === void 0) { atIndices = null; }
  6699. var result = [];
  6700. if (!atIndices) {
  6701. var length = this._postProcesses.length;
  6702. for (var i = 0; i < length; i++) {
  6703. if (this._postProcesses[i] !== postProcess) {
  6704. continue;
  6705. }
  6706. delete this._postProcesses[i];
  6707. var index = this._postProcessesTakenIndices.indexOf(i);
  6708. this._postProcessesTakenIndices.splice(index, 1);
  6709. }
  6710. }
  6711. else {
  6712. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6713. for (i = 0; i < atIndices.length; i++) {
  6714. var foundPostProcess = this._postProcesses[atIndices[i]];
  6715. if (foundPostProcess !== postProcess) {
  6716. result.push(i);
  6717. continue;
  6718. }
  6719. delete this._postProcesses[atIndices[i]];
  6720. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6721. this._postProcessesTakenIndices.splice(index, 1);
  6722. }
  6723. }
  6724. return result;
  6725. };
  6726. Camera.prototype.getWorldMatrix = function () {
  6727. if (!this._worldMatrix) {
  6728. this._worldMatrix = BABYLON.Matrix.Identity();
  6729. }
  6730. var viewMatrix = this.getViewMatrix();
  6731. viewMatrix.invertToRef(this._worldMatrix);
  6732. return this._worldMatrix;
  6733. };
  6734. Camera.prototype._getViewMatrix = function () {
  6735. return BABYLON.Matrix.Identity();
  6736. };
  6737. Camera.prototype.getViewMatrix = function () {
  6738. this._computedViewMatrix = this._computeViewMatrix();
  6739. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6740. return this._computedViewMatrix;
  6741. }
  6742. if (!this._worldMatrix) {
  6743. this._worldMatrix = BABYLON.Matrix.Identity();
  6744. }
  6745. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6746. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6747. this._computedViewMatrix.invert();
  6748. this._currentRenderId = this.getScene().getRenderId();
  6749. return this._computedViewMatrix;
  6750. };
  6751. Camera.prototype._computeViewMatrix = function (force) {
  6752. if (!force && this._isSynchronizedViewMatrix()) {
  6753. return this._computedViewMatrix;
  6754. }
  6755. this._computedViewMatrix = this._getViewMatrix();
  6756. if (!this.parent || !this.parent.getWorldMatrix) {
  6757. this._currentRenderId = this.getScene().getRenderId();
  6758. }
  6759. return this._computedViewMatrix;
  6760. };
  6761. Camera.prototype.getProjectionMatrix = function (force) {
  6762. if (!force && this._isSynchronizedProjectionMatrix()) {
  6763. return this._projectionMatrix;
  6764. }
  6765. var engine = this.getEngine();
  6766. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6767. if (this.minZ <= 0) {
  6768. this.minZ = 0.1;
  6769. }
  6770. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6771. return this._projectionMatrix;
  6772. }
  6773. var halfWidth = engine.getRenderWidth() / 2.0;
  6774. var halfHeight = engine.getRenderHeight() / 2.0;
  6775. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6776. return this._projectionMatrix;
  6777. };
  6778. Camera.prototype.dispose = function () {
  6779. // Remove from scene
  6780. var index = this.getScene().cameras.indexOf(this);
  6781. this.getScene().cameras.splice(index, 1);
  6782. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6783. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6784. }
  6785. };
  6786. // Statics
  6787. Camera._PERSPECTIVE_CAMERA = 0;
  6788. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6789. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6790. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6791. return Camera;
  6792. })(BABYLON.Node);
  6793. BABYLON.Camera = Camera;
  6794. })(BABYLON || (BABYLON = {}));
  6795. //# sourceMappingURL=babylon.camera.js.map
  6796. var BABYLON;
  6797. (function (BABYLON) {
  6798. var TargetCamera = (function (_super) {
  6799. __extends(TargetCamera, _super);
  6800. function TargetCamera(name, position, scene) {
  6801. _super.call(this, name, position, scene);
  6802. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6803. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6804. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6805. this.speed = 2.0;
  6806. this.noRotationConstraint = false;
  6807. this.lockedTarget = null;
  6808. this._currentTarget = BABYLON.Vector3.Zero();
  6809. this._viewMatrix = BABYLON.Matrix.Zero();
  6810. this._camMatrix = BABYLON.Matrix.Zero();
  6811. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6812. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6813. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6814. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6815. this._lookAtTemp = BABYLON.Matrix.Zero();
  6816. this._tempMatrix = BABYLON.Matrix.Zero();
  6817. }
  6818. TargetCamera.prototype._getLockedTargetPosition = function () {
  6819. if (!this.lockedTarget) {
  6820. return null;
  6821. }
  6822. return this.lockedTarget.position || this.lockedTarget;
  6823. };
  6824. // Cache
  6825. TargetCamera.prototype._initCache = function () {
  6826. _super.prototype._initCache.call(this);
  6827. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6828. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6829. };
  6830. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6831. if (!ignoreParentClass) {
  6832. _super.prototype._updateCache.call(this);
  6833. }
  6834. var lockedTargetPosition = this._getLockedTargetPosition();
  6835. if (!lockedTargetPosition) {
  6836. this._cache.lockedTarget = null;
  6837. }
  6838. else {
  6839. if (!this._cache.lockedTarget) {
  6840. this._cache.lockedTarget = lockedTargetPosition.clone();
  6841. }
  6842. else {
  6843. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6844. }
  6845. }
  6846. this._cache.rotation.copyFrom(this.rotation);
  6847. };
  6848. // Synchronized
  6849. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6850. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6851. return false;
  6852. }
  6853. var lockedTargetPosition = this._getLockedTargetPosition();
  6854. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6855. };
  6856. // Methods
  6857. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6858. var engine = this.getEngine();
  6859. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6860. };
  6861. // Target
  6862. TargetCamera.prototype.setTarget = function (target) {
  6863. this.upVector.normalize();
  6864. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6865. this._camMatrix.invert();
  6866. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6867. var vDir = target.subtract(this.position);
  6868. if (vDir.x >= 0.0) {
  6869. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6870. }
  6871. else {
  6872. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6873. }
  6874. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6875. if (isNaN(this.rotation.x)) {
  6876. this.rotation.x = 0;
  6877. }
  6878. if (isNaN(this.rotation.y)) {
  6879. this.rotation.y = 0;
  6880. }
  6881. if (isNaN(this.rotation.z)) {
  6882. this.rotation.z = 0;
  6883. }
  6884. };
  6885. TargetCamera.prototype.getTarget = function () {
  6886. return this._currentTarget;
  6887. };
  6888. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6889. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6890. };
  6891. TargetCamera.prototype._updatePosition = function () {
  6892. this.position.addInPlace(this.cameraDirection);
  6893. };
  6894. TargetCamera.prototype._update = function () {
  6895. var needToMove = this._decideIfNeedsToMove();
  6896. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6897. // Move
  6898. if (needToMove) {
  6899. this._updatePosition();
  6900. }
  6901. // Rotate
  6902. if (needToRotate) {
  6903. this.rotation.x += this.cameraRotation.x;
  6904. this.rotation.y += this.cameraRotation.y;
  6905. if (!this.noRotationConstraint) {
  6906. var limit = (Math.PI / 2) * 0.95;
  6907. if (this.rotation.x > limit)
  6908. this.rotation.x = limit;
  6909. if (this.rotation.x < -limit)
  6910. this.rotation.x = -limit;
  6911. }
  6912. }
  6913. // Inertia
  6914. if (needToMove) {
  6915. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6916. this.cameraDirection.x = 0;
  6917. }
  6918. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6919. this.cameraDirection.y = 0;
  6920. }
  6921. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6922. this.cameraDirection.z = 0;
  6923. }
  6924. this.cameraDirection.scaleInPlace(this.inertia);
  6925. }
  6926. if (needToRotate) {
  6927. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6928. this.cameraRotation.x = 0;
  6929. }
  6930. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6931. this.cameraRotation.y = 0;
  6932. }
  6933. this.cameraRotation.scaleInPlace(this.inertia);
  6934. }
  6935. };
  6936. TargetCamera.prototype._getViewMatrix = function () {
  6937. if (!this.lockedTarget) {
  6938. // Compute
  6939. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6940. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6941. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6942. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6943. this._lookAtTemp.invert();
  6944. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6945. }
  6946. else {
  6947. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6948. }
  6949. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6950. // Computing target and final matrix
  6951. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6952. }
  6953. else {
  6954. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6955. }
  6956. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6957. return this._viewMatrix;
  6958. };
  6959. return TargetCamera;
  6960. })(BABYLON.Camera);
  6961. BABYLON.TargetCamera = TargetCamera;
  6962. })(BABYLON || (BABYLON = {}));
  6963. //# sourceMappingURL=babylon.targetCamera.js.map
  6964. var BABYLON;
  6965. (function (BABYLON) {
  6966. var FollowCamera = (function (_super) {
  6967. __extends(FollowCamera, _super);
  6968. function FollowCamera(name, position, scene) {
  6969. _super.call(this, name, position, scene);
  6970. this.radius = 12;
  6971. this.rotationOffset = 0;
  6972. this.heightOffset = 4;
  6973. this.cameraAcceleration = 0.05;
  6974. this.maxCameraSpeed = 20;
  6975. }
  6976. FollowCamera.prototype.getRadians = function (degrees) {
  6977. return degrees * Math.PI / 180;
  6978. };
  6979. FollowCamera.prototype.follow = function (cameraTarget) {
  6980. if (!cameraTarget)
  6981. return;
  6982. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6983. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6984. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6985. var dx = targetX - this.position.x;
  6986. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6987. var dz = (targetZ) - this.position.z;
  6988. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6989. var vy = dy * this.cameraAcceleration;
  6990. var vz = dz * this.cameraAcceleration * 2;
  6991. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6992. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6993. }
  6994. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6995. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6996. }
  6997. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6998. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6999. }
  7000. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7001. this.setTarget(cameraTarget.position);
  7002. };
  7003. FollowCamera.prototype._update = function () {
  7004. _super.prototype._update.call(this);
  7005. this.follow(this.target);
  7006. };
  7007. return FollowCamera;
  7008. })(BABYLON.TargetCamera);
  7009. BABYLON.FollowCamera = FollowCamera;
  7010. })(BABYLON || (BABYLON = {}));
  7011. //# sourceMappingURL=babylon.followCamera.js.map
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var FreeCamera = (function (_super) {
  7015. __extends(FreeCamera, _super);
  7016. function FreeCamera(name, position, scene) {
  7017. _super.call(this, name, position, scene);
  7018. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7019. this.keysUp = [38];
  7020. this.keysDown = [40];
  7021. this.keysLeft = [37];
  7022. this.keysRight = [39];
  7023. this.checkCollisions = false;
  7024. this.applyGravity = false;
  7025. this.angularSensibility = 2000.0;
  7026. this._keys = [];
  7027. this._collider = new BABYLON.Collider();
  7028. this._needMoveForGravity = true;
  7029. this._oldPosition = BABYLON.Vector3.Zero();
  7030. this._diffPosition = BABYLON.Vector3.Zero();
  7031. this._newPosition = BABYLON.Vector3.Zero();
  7032. }
  7033. // Controls
  7034. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7035. var _this = this;
  7036. var previousPosition;
  7037. var engine = this.getEngine();
  7038. if (this._attachedElement) {
  7039. return;
  7040. }
  7041. this._attachedElement = element;
  7042. if (this._onMouseDown === undefined) {
  7043. this._onMouseDown = function (evt) {
  7044. previousPosition = {
  7045. x: evt.clientX,
  7046. y: evt.clientY
  7047. };
  7048. if (!noPreventDefault) {
  7049. evt.preventDefault();
  7050. }
  7051. };
  7052. this._onMouseUp = function (evt) {
  7053. previousPosition = null;
  7054. if (!noPreventDefault) {
  7055. evt.preventDefault();
  7056. }
  7057. };
  7058. this._onMouseOut = function (evt) {
  7059. previousPosition = null;
  7060. _this._keys = [];
  7061. if (!noPreventDefault) {
  7062. evt.preventDefault();
  7063. }
  7064. };
  7065. this._onMouseMove = function (evt) {
  7066. if (!previousPosition && !engine.isPointerLock) {
  7067. return;
  7068. }
  7069. var offsetX;
  7070. var offsetY;
  7071. if (!engine.isPointerLock) {
  7072. offsetX = evt.clientX - previousPosition.x;
  7073. offsetY = evt.clientY - previousPosition.y;
  7074. }
  7075. else {
  7076. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7077. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7078. }
  7079. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7080. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7081. previousPosition = {
  7082. x: evt.clientX,
  7083. y: evt.clientY
  7084. };
  7085. if (!noPreventDefault) {
  7086. evt.preventDefault();
  7087. }
  7088. };
  7089. this._onKeyDown = function (evt) {
  7090. 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) {
  7091. var index = _this._keys.indexOf(evt.keyCode);
  7092. if (index === -1) {
  7093. _this._keys.push(evt.keyCode);
  7094. }
  7095. if (!noPreventDefault) {
  7096. evt.preventDefault();
  7097. }
  7098. }
  7099. };
  7100. this._onKeyUp = function (evt) {
  7101. 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) {
  7102. var index = _this._keys.indexOf(evt.keyCode);
  7103. if (index >= 0) {
  7104. _this._keys.splice(index, 1);
  7105. }
  7106. if (!noPreventDefault) {
  7107. evt.preventDefault();
  7108. }
  7109. }
  7110. };
  7111. this._onLostFocus = function () {
  7112. _this._keys = [];
  7113. };
  7114. this._reset = function () {
  7115. _this._keys = [];
  7116. previousPosition = null;
  7117. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7118. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7119. };
  7120. }
  7121. element.addEventListener("mousedown", this._onMouseDown, false);
  7122. element.addEventListener("mouseup", this._onMouseUp, false);
  7123. element.addEventListener("mouseout", this._onMouseOut, false);
  7124. element.addEventListener("mousemove", this._onMouseMove, false);
  7125. BABYLON.Tools.RegisterTopRootEvents([
  7126. { name: "keydown", handler: this._onKeyDown },
  7127. { name: "keyup", handler: this._onKeyUp },
  7128. { name: "blur", handler: this._onLostFocus }
  7129. ]);
  7130. };
  7131. FreeCamera.prototype.detachControl = function (element) {
  7132. if (this._attachedElement != element) {
  7133. return;
  7134. }
  7135. element.removeEventListener("mousedown", this._onMouseDown);
  7136. element.removeEventListener("mouseup", this._onMouseUp);
  7137. element.removeEventListener("mouseout", this._onMouseOut);
  7138. element.removeEventListener("mousemove", this._onMouseMove);
  7139. BABYLON.Tools.UnregisterTopRootEvents([
  7140. { name: "keydown", handler: this._onKeyDown },
  7141. { name: "keyup", handler: this._onKeyUp },
  7142. { name: "blur", handler: this._onLostFocus }
  7143. ]);
  7144. this._attachedElement = null;
  7145. if (this._reset) {
  7146. this._reset();
  7147. }
  7148. };
  7149. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7150. var globalPosition;
  7151. if (this.parent) {
  7152. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7153. }
  7154. else {
  7155. globalPosition = this.position;
  7156. }
  7157. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7158. this._collider.radius = this.ellipsoid;
  7159. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7160. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7161. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7162. this.position.addInPlace(this._diffPosition);
  7163. if (this.onCollide) {
  7164. this.onCollide(this._collider.collidedMesh);
  7165. }
  7166. }
  7167. };
  7168. FreeCamera.prototype._checkInputs = function () {
  7169. if (!this._localDirection) {
  7170. this._localDirection = BABYLON.Vector3.Zero();
  7171. this._transformedDirection = BABYLON.Vector3.Zero();
  7172. }
  7173. for (var index = 0; index < this._keys.length; index++) {
  7174. var keyCode = this._keys[index];
  7175. var speed = this._computeLocalCameraSpeed();
  7176. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7177. this._localDirection.copyFromFloats(-speed, 0, 0);
  7178. }
  7179. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7180. this._localDirection.copyFromFloats(0, 0, speed);
  7181. }
  7182. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7183. this._localDirection.copyFromFloats(speed, 0, 0);
  7184. }
  7185. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7186. this._localDirection.copyFromFloats(0, 0, -speed);
  7187. }
  7188. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7189. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7190. this.cameraDirection.addInPlace(this._transformedDirection);
  7191. }
  7192. };
  7193. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7194. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7195. };
  7196. FreeCamera.prototype._updatePosition = function () {
  7197. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7198. this._collideWithWorld(this.cameraDirection);
  7199. if (this.applyGravity) {
  7200. var oldPosition = this.position;
  7201. this._collideWithWorld(this.getScene().gravity);
  7202. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7203. }
  7204. }
  7205. else {
  7206. this.position.addInPlace(this.cameraDirection);
  7207. }
  7208. };
  7209. FreeCamera.prototype._update = function () {
  7210. this._checkInputs();
  7211. _super.prototype._update.call(this);
  7212. };
  7213. return FreeCamera;
  7214. })(BABYLON.TargetCamera);
  7215. BABYLON.FreeCamera = FreeCamera;
  7216. })(BABYLON || (BABYLON = {}));
  7217. //# sourceMappingURL=babylon.freeCamera.js.map
  7218. var BABYLON;
  7219. (function (BABYLON) {
  7220. // We're mainly based on the logic defined into the FreeCamera code
  7221. var TouchCamera = (function (_super) {
  7222. __extends(TouchCamera, _super);
  7223. function TouchCamera(name, position, scene) {
  7224. _super.call(this, name, position, scene);
  7225. this._offsetX = null;
  7226. this._offsetY = null;
  7227. this._pointerCount = 0;
  7228. this._pointerPressed = [];
  7229. this.angularSensibility = 200000.0;
  7230. this.moveSensibility = 500.0;
  7231. }
  7232. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7233. var _this = this;
  7234. var previousPosition;
  7235. if (this._attachedCanvas) {
  7236. return;
  7237. }
  7238. this._attachedCanvas = canvas;
  7239. if (this._onPointerDown === undefined) {
  7240. this._onPointerDown = function (evt) {
  7241. if (!noPreventDefault) {
  7242. evt.preventDefault();
  7243. }
  7244. _this._pointerPressed.push(evt.pointerId);
  7245. if (_this._pointerPressed.length !== 1) {
  7246. return;
  7247. }
  7248. previousPosition = {
  7249. x: evt.clientX,
  7250. y: evt.clientY
  7251. };
  7252. };
  7253. this._onPointerUp = function (evt) {
  7254. if (!noPreventDefault) {
  7255. evt.preventDefault();
  7256. }
  7257. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7258. if (index === -1) {
  7259. return;
  7260. }
  7261. _this._pointerPressed.splice(index, 1);
  7262. if (index != 0) {
  7263. return;
  7264. }
  7265. previousPosition = null;
  7266. _this._offsetX = null;
  7267. _this._offsetY = null;
  7268. };
  7269. this._onPointerMove = function (evt) {
  7270. if (!noPreventDefault) {
  7271. evt.preventDefault();
  7272. }
  7273. if (!previousPosition) {
  7274. return;
  7275. }
  7276. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7277. if (index != 0) {
  7278. return;
  7279. }
  7280. _this._offsetX = evt.clientX - previousPosition.x;
  7281. _this._offsetY = -(evt.clientY - previousPosition.y);
  7282. };
  7283. this._onLostFocus = function () {
  7284. _this._offsetX = null;
  7285. _this._offsetY = null;
  7286. };
  7287. }
  7288. canvas.addEventListener("pointerdown", this._onPointerDown);
  7289. canvas.addEventListener("pointerup", this._onPointerUp);
  7290. canvas.addEventListener("pointerout", this._onPointerUp);
  7291. canvas.addEventListener("pointermove", this._onPointerMove);
  7292. BABYLON.Tools.RegisterTopRootEvents([
  7293. { name: "blur", handler: this._onLostFocus }
  7294. ]);
  7295. };
  7296. TouchCamera.prototype.detachControl = function (canvas) {
  7297. if (this._attachedCanvas != canvas) {
  7298. return;
  7299. }
  7300. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7301. canvas.removeEventListener("pointerup", this._onPointerUp);
  7302. canvas.removeEventListener("pointerout", this._onPointerUp);
  7303. canvas.removeEventListener("pointermove", this._onPointerMove);
  7304. BABYLON.Tools.UnregisterTopRootEvents([
  7305. { name: "blur", handler: this._onLostFocus }
  7306. ]);
  7307. this._attachedCanvas = null;
  7308. };
  7309. TouchCamera.prototype._checkInputs = function () {
  7310. if (!this._offsetX) {
  7311. return;
  7312. }
  7313. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7314. if (this._pointerPressed.length > 1) {
  7315. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7316. }
  7317. else {
  7318. var speed = this._computeLocalCameraSpeed();
  7319. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7320. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7321. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7322. }
  7323. };
  7324. return TouchCamera;
  7325. })(BABYLON.FreeCamera);
  7326. BABYLON.TouchCamera = TouchCamera;
  7327. })(BABYLON || (BABYLON = {}));
  7328. //# sourceMappingURL=babylon.touchCamera.js.map
  7329. var BABYLON;
  7330. (function (BABYLON) {
  7331. // We're mainly based on the logic defined into the FreeCamera code
  7332. var DeviceOrientationCamera = (function (_super) {
  7333. __extends(DeviceOrientationCamera, _super);
  7334. function DeviceOrientationCamera(name, position, scene) {
  7335. var _this = this;
  7336. _super.call(this, name, position, scene);
  7337. this._offsetX = null;
  7338. this._offsetY = null;
  7339. this._orientationGamma = 0;
  7340. this._orientationBeta = 0;
  7341. this._initialOrientationGamma = 0;
  7342. this._initialOrientationBeta = 0;
  7343. this.angularSensibility = 10000.0;
  7344. this.moveSensibility = 50.0;
  7345. window.addEventListener("resize", function () {
  7346. _this._initialOrientationGamma = null;
  7347. }, false);
  7348. }
  7349. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7350. var _this = this;
  7351. if (this._attachedCanvas) {
  7352. return;
  7353. }
  7354. this._attachedCanvas = canvas;
  7355. if (!this._orientationChanged) {
  7356. this._orientationChanged = function (evt) {
  7357. if (!_this._initialOrientationGamma) {
  7358. _this._initialOrientationGamma = evt.gamma;
  7359. _this._initialOrientationBeta = evt.beta;
  7360. }
  7361. _this._orientationGamma = evt.gamma;
  7362. _this._orientationBeta = evt.beta;
  7363. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7364. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7365. };
  7366. }
  7367. window.addEventListener("deviceorientation", this._orientationChanged);
  7368. };
  7369. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7370. if (this._attachedCanvas != canvas) {
  7371. return;
  7372. }
  7373. window.removeEventListener("deviceorientation", this._orientationChanged);
  7374. this._attachedCanvas = null;
  7375. this._orientationGamma = 0;
  7376. this._orientationBeta = 0;
  7377. this._initialOrientationGamma = 0;
  7378. this._initialOrientationBeta = 0;
  7379. };
  7380. DeviceOrientationCamera.prototype._checkInputs = function () {
  7381. if (!this._offsetX) {
  7382. return;
  7383. }
  7384. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7385. var speed = this._computeLocalCameraSpeed();
  7386. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7387. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7388. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7389. };
  7390. return DeviceOrientationCamera;
  7391. })(BABYLON.FreeCamera);
  7392. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7393. })(BABYLON || (BABYLON = {}));
  7394. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7395. var BABYLON;
  7396. (function (BABYLON) {
  7397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7398. var ArcRotateCamera = (function (_super) {
  7399. __extends(ArcRotateCamera, _super);
  7400. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7401. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7402. this.alpha = alpha;
  7403. this.beta = beta;
  7404. this.radius = radius;
  7405. this.target = target;
  7406. this.inertialAlphaOffset = 0;
  7407. this.inertialBetaOffset = 0;
  7408. this.inertialRadiusOffset = 0;
  7409. this.lowerAlphaLimit = null;
  7410. this.upperAlphaLimit = null;
  7411. this.lowerBetaLimit = 0.01;
  7412. this.upperBetaLimit = Math.PI;
  7413. this.lowerRadiusLimit = null;
  7414. this.upperRadiusLimit = null;
  7415. this.angularSensibility = 1000.0;
  7416. this.wheelPrecision = 3.0;
  7417. this.keysUp = [38];
  7418. this.keysDown = [40];
  7419. this.keysLeft = [37];
  7420. this.keysRight = [39];
  7421. this.zoomOnFactor = 1;
  7422. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7423. this._keys = [];
  7424. this._viewMatrix = new BABYLON.Matrix();
  7425. this.checkCollisions = false;
  7426. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7427. this._collider = new BABYLON.Collider();
  7428. this._previousPosition = BABYLON.Vector3.Zero();
  7429. this._collisionVelocity = BABYLON.Vector3.Zero();
  7430. this._newPosition = BABYLON.Vector3.Zero();
  7431. // Pinch
  7432. // value for pinch step scaling
  7433. // set to 20 by default
  7434. this.pinchPrecision = 20;
  7435. this.getViewMatrix();
  7436. }
  7437. ArcRotateCamera.prototype._getTargetPosition = function () {
  7438. return this.target.position || this.target;
  7439. };
  7440. // Cache
  7441. ArcRotateCamera.prototype._initCache = function () {
  7442. _super.prototype._initCache.call(this);
  7443. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7444. this._cache.alpha = undefined;
  7445. this._cache.beta = undefined;
  7446. this._cache.radius = undefined;
  7447. this._cache.targetScreenOffset = undefined;
  7448. };
  7449. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7450. if (!ignoreParentClass) {
  7451. _super.prototype._updateCache.call(this);
  7452. }
  7453. this._cache.target.copyFrom(this._getTargetPosition());
  7454. this._cache.alpha = this.alpha;
  7455. this._cache.beta = this.beta;
  7456. this._cache.radius = this.radius;
  7457. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7458. };
  7459. // Synchronized
  7460. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7461. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7462. return false;
  7463. 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);
  7464. };
  7465. // Methods
  7466. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7467. var _this = this;
  7468. var previousPosition;
  7469. var pointerId;
  7470. // to know if pinch started
  7471. var pinchStarted = false;
  7472. // two pinch point on X
  7473. // that will use for find if user action is pinch open or pinch close
  7474. var pinchPointX1, pinchPointX2;
  7475. if (this._attachedElement) {
  7476. return;
  7477. }
  7478. this._attachedElement = element;
  7479. var engine = this.getEngine();
  7480. if (this._onPointerDown === undefined) {
  7481. this._onPointerDown = function (evt) {
  7482. if (pointerId) {
  7483. return;
  7484. }
  7485. pointerId = evt.pointerId;
  7486. previousPosition = {
  7487. x: evt.clientX,
  7488. y: evt.clientY
  7489. };
  7490. if (!noPreventDefault) {
  7491. evt.preventDefault();
  7492. }
  7493. };
  7494. this._onPointerUp = function (evt) {
  7495. previousPosition = null;
  7496. pointerId = null;
  7497. if (!noPreventDefault) {
  7498. evt.preventDefault();
  7499. }
  7500. };
  7501. this._onPointerMove = function (evt) {
  7502. if (!previousPosition) {
  7503. return;
  7504. }
  7505. if (pointerId !== evt.pointerId) {
  7506. return;
  7507. }
  7508. // return pinch is started
  7509. if (pinchStarted) {
  7510. return;
  7511. }
  7512. var offsetX = evt.clientX - previousPosition.x;
  7513. var offsetY = evt.clientY - previousPosition.y;
  7514. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7515. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7516. previousPosition = {
  7517. x: evt.clientX,
  7518. y: evt.clientY
  7519. };
  7520. if (!noPreventDefault) {
  7521. evt.preventDefault();
  7522. }
  7523. };
  7524. this._onMouseMove = function (evt) {
  7525. if (!engine.isPointerLock) {
  7526. return;
  7527. }
  7528. // return pinch is started
  7529. if (pinchStarted) {
  7530. return;
  7531. }
  7532. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7533. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7534. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7535. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7536. if (!noPreventDefault) {
  7537. evt.preventDefault();
  7538. }
  7539. };
  7540. this._wheel = function (event) {
  7541. var delta = 0;
  7542. if (event.wheelDelta) {
  7543. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7544. }
  7545. else if (event.detail) {
  7546. delta = -event.detail / _this.wheelPrecision;
  7547. }
  7548. if (delta)
  7549. _this.inertialRadiusOffset += delta;
  7550. if (event.preventDefault) {
  7551. if (!noPreventDefault) {
  7552. event.preventDefault();
  7553. }
  7554. }
  7555. };
  7556. this._onKeyDown = function (evt) {
  7557. 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) {
  7558. var index = _this._keys.indexOf(evt.keyCode);
  7559. if (index === -1) {
  7560. _this._keys.push(evt.keyCode);
  7561. }
  7562. if (evt.preventDefault) {
  7563. if (!noPreventDefault) {
  7564. evt.preventDefault();
  7565. }
  7566. }
  7567. }
  7568. };
  7569. this._onKeyUp = function (evt) {
  7570. 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) {
  7571. var index = _this._keys.indexOf(evt.keyCode);
  7572. if (index >= 0) {
  7573. _this._keys.splice(index, 1);
  7574. }
  7575. if (evt.preventDefault) {
  7576. if (!noPreventDefault) {
  7577. evt.preventDefault();
  7578. }
  7579. }
  7580. }
  7581. };
  7582. this._onLostFocus = function () {
  7583. _this._keys = [];
  7584. pointerId = null;
  7585. };
  7586. this._onGestureStart = function (e) {
  7587. if (window.MSGesture === undefined) {
  7588. return;
  7589. }
  7590. if (!_this._MSGestureHandler) {
  7591. _this._MSGestureHandler = new MSGesture();
  7592. _this._MSGestureHandler.target = element;
  7593. }
  7594. _this._MSGestureHandler.addPointer(e.pointerId);
  7595. };
  7596. this._onGesture = function (e) {
  7597. _this.radius *= e.scale;
  7598. if (e.preventDefault) {
  7599. if (!noPreventDefault) {
  7600. e.stopPropagation();
  7601. e.preventDefault();
  7602. }
  7603. }
  7604. };
  7605. this._reset = function () {
  7606. _this._keys = [];
  7607. _this.inertialAlphaOffset = 0;
  7608. _this.inertialBetaOffset = 0;
  7609. _this.inertialRadiusOffset = 0;
  7610. previousPosition = null;
  7611. pointerId = null;
  7612. };
  7613. this._touchStart = function (event) {
  7614. if (event.touches.length === 2) {
  7615. //-- start pinch if two fingers on the screen
  7616. pinchStarted = true;
  7617. _this._pinchStart(event);
  7618. }
  7619. };
  7620. this._touchMove = function (event) {
  7621. if (pinchStarted) {
  7622. //-- make scaling
  7623. _this._pinchMove(event);
  7624. }
  7625. };
  7626. this._touchEnd = function (event) {
  7627. if (pinchStarted) {
  7628. //-- end of pinch
  7629. _this._pinchEnd(event);
  7630. }
  7631. };
  7632. this._pinchStart = function (event) {
  7633. // save origin touch point
  7634. pinchPointX1 = event.touches[0].clientX;
  7635. pinchPointX2 = event.touches[1].clientX;
  7636. // block the camera
  7637. // if not it rotate around target during pinch
  7638. pinchStarted = true;
  7639. };
  7640. this._pinchMove = function (event) {
  7641. // variable for new camera's radius
  7642. var delta = 0;
  7643. // variables to know if pinch open or pinch close
  7644. var direction = 1;
  7645. var distanceXOrigine, distanceXNow;
  7646. if (event.touches.length !== 2)
  7647. return;
  7648. // calculate absolute distances of the two fingers
  7649. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7650. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7651. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7652. if (distanceXNow < distanceXOrigine) {
  7653. direction = -1;
  7654. }
  7655. // calculate new radius
  7656. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7657. // set new radius
  7658. _this.inertialRadiusOffset -= delta;
  7659. // save origin touch point
  7660. pinchPointX1 = event.touches[0].clientX;
  7661. pinchPointX2 = event.touches[1].clientX;
  7662. };
  7663. this._pinchEnd = function (event) {
  7664. // cancel pinch and deblock camera rotation
  7665. pinchStarted = false;
  7666. };
  7667. }
  7668. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7669. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7670. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7671. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7672. element.addEventListener("mousemove", this._onMouseMove, false);
  7673. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7674. element.addEventListener("MSGestureChange", this._onGesture, false);
  7675. element.addEventListener('mousewheel', this._wheel, false);
  7676. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7677. // pinch
  7678. element.addEventListener('touchstart', this._touchStart, false);
  7679. element.addEventListener('touchmove', this._touchMove, false);
  7680. element.addEventListener('touchend', this._touchEnd, false);
  7681. BABYLON.Tools.RegisterTopRootEvents([
  7682. { name: "keydown", handler: this._onKeyDown },
  7683. { name: "keyup", handler: this._onKeyUp },
  7684. { name: "blur", handler: this._onLostFocus }
  7685. ]);
  7686. };
  7687. ArcRotateCamera.prototype.detachControl = function (element) {
  7688. if (this._attachedElement != element) {
  7689. return;
  7690. }
  7691. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7692. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7693. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7694. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7695. element.removeEventListener("mousemove", this._onMouseMove);
  7696. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7697. element.removeEventListener("MSGestureChange", this._onGesture);
  7698. element.removeEventListener('mousewheel', this._wheel);
  7699. element.removeEventListener('DOMMouseScroll', this._wheel);
  7700. // pinch
  7701. element.removeEventListener('touchstart', this._touchStart);
  7702. element.removeEventListener('touchmove', this._touchMove);
  7703. element.removeEventListener('touchend', this._touchEnd);
  7704. BABYLON.Tools.UnregisterTopRootEvents([
  7705. { name: "keydown", handler: this._onKeyDown },
  7706. { name: "keyup", handler: this._onKeyUp },
  7707. { name: "blur", handler: this._onLostFocus }
  7708. ]);
  7709. this._MSGestureHandler = null;
  7710. this._attachedElement = null;
  7711. if (this._reset) {
  7712. this._reset();
  7713. }
  7714. };
  7715. ArcRotateCamera.prototype._update = function () {
  7716. for (var index = 0; index < this._keys.length; index++) {
  7717. var keyCode = this._keys[index];
  7718. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7719. this.inertialAlphaOffset -= 0.01;
  7720. }
  7721. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7722. this.inertialBetaOffset -= 0.01;
  7723. }
  7724. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7725. this.inertialAlphaOffset += 0.01;
  7726. }
  7727. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7728. this.inertialBetaOffset += 0.01;
  7729. }
  7730. }
  7731. // Inertia
  7732. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7733. this.alpha += this.inertialAlphaOffset;
  7734. this.beta += this.inertialBetaOffset;
  7735. this.radius -= this.inertialRadiusOffset;
  7736. this.inertialAlphaOffset *= this.inertia;
  7737. this.inertialBetaOffset *= this.inertia;
  7738. this.inertialRadiusOffset *= this.inertia;
  7739. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7740. this.inertialAlphaOffset = 0;
  7741. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7742. this.inertialBetaOffset = 0;
  7743. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7744. this.inertialRadiusOffset = 0;
  7745. }
  7746. // Limits
  7747. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7748. this.alpha = this.lowerAlphaLimit;
  7749. }
  7750. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7751. this.alpha = this.upperAlphaLimit;
  7752. }
  7753. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7754. this.beta = this.lowerBetaLimit;
  7755. }
  7756. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7757. this.beta = this.upperBetaLimit;
  7758. }
  7759. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7760. this.radius = this.lowerRadiusLimit;
  7761. }
  7762. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7763. this.radius = this.upperRadiusLimit;
  7764. }
  7765. };
  7766. ArcRotateCamera.prototype.setPosition = function (position) {
  7767. var radiusv3 = position.subtract(this._getTargetPosition());
  7768. this.radius = radiusv3.length();
  7769. // Alpha
  7770. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7771. if (radiusv3.z < 0) {
  7772. this.alpha = 2 * Math.PI - this.alpha;
  7773. }
  7774. // Beta
  7775. this.beta = Math.acos(radiusv3.y / this.radius);
  7776. };
  7777. ArcRotateCamera.prototype._getViewMatrix = function () {
  7778. // Compute
  7779. var cosa = Math.cos(this.alpha);
  7780. var sina = Math.sin(this.alpha);
  7781. var cosb = Math.cos(this.beta);
  7782. var sinb = Math.sin(this.beta);
  7783. var target = this._getTargetPosition();
  7784. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7785. if (this.checkCollisions) {
  7786. this._collider.radius = this.collisionRadius;
  7787. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7788. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7789. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7790. this.position.copyFrom(this._previousPosition);
  7791. this.alpha = this._previousAlpha;
  7792. this.beta = this._previousBeta;
  7793. this.radius = this._previousRadius;
  7794. if (this.onCollide) {
  7795. this.onCollide(this._collider.collidedMesh);
  7796. }
  7797. }
  7798. }
  7799. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7800. this._previousAlpha = this.alpha;
  7801. this._previousBeta = this.beta;
  7802. this._previousRadius = this.radius;
  7803. this._previousPosition.copyFrom(this.position);
  7804. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7805. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7806. return this._viewMatrix;
  7807. };
  7808. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7809. meshes = meshes || this.getScene().meshes;
  7810. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7811. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7812. this.radius = distance * this.zoomOnFactor;
  7813. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7814. };
  7815. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7816. var meshesOrMinMaxVector;
  7817. var distance;
  7818. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7819. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7820. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7821. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7822. }
  7823. else {
  7824. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7825. distance = meshesOrMinMaxVectorAndDistance.distance;
  7826. }
  7827. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7828. this.maxZ = distance * 2;
  7829. };
  7830. return ArcRotateCamera;
  7831. })(BABYLON.Camera);
  7832. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7833. })(BABYLON || (BABYLON = {}));
  7834. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7835. (function (BABYLON) {
  7836. /**
  7837. * Represents a scene to be rendered by the engine.
  7838. * @see http://doc.babylonjs.com/page.php?p=21911
  7839. */
  7840. var Scene = (function () {
  7841. /**
  7842. * @constructor
  7843. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7844. */
  7845. function Scene(engine) {
  7846. // Members
  7847. this.autoClear = true;
  7848. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7849. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7850. this.forceWireframe = false;
  7851. this.forcePointsCloud = false;
  7852. this.forceShowBoundingBoxes = false;
  7853. this.animationsEnabled = true;
  7854. 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
  7855. // Fog
  7856. /**
  7857. * is fog enabled on this scene.
  7858. * @type {boolean}
  7859. */
  7860. this.fogEnabled = true;
  7861. this.fogMode = Scene.FOGMODE_NONE;
  7862. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7863. this.fogDensity = 0.1;
  7864. this.fogStart = 0;
  7865. this.fogEnd = 1000.0;
  7866. // Lights
  7867. /**
  7868. * is shadow enabled on this scene.
  7869. * @type {boolean}
  7870. */
  7871. this.shadowsEnabled = true;
  7872. /**
  7873. * is light enabled on this scene.
  7874. * @type {boolean}
  7875. */
  7876. this.lightsEnabled = true;
  7877. /**
  7878. * All of the lights added to this scene.
  7879. * @see BABYLON.Light
  7880. * @type {BABYLON.Light[]}
  7881. */
  7882. this.lights = new Array();
  7883. // Cameras
  7884. /**
  7885. * All of the cameras added to this scene.
  7886. * @see BABYLON.Camera
  7887. * @type {BABYLON.Camera[]}
  7888. */
  7889. this.cameras = new Array();
  7890. this.activeCameras = new Array();
  7891. // Meshes
  7892. /**
  7893. * All of the (abstract) meshes added to this scene.
  7894. * @see BABYLON.AbstractMesh
  7895. * @type {BABYLON.AbstractMesh[]}
  7896. */
  7897. this.meshes = new Array();
  7898. // Geometries
  7899. this._geometries = new Array();
  7900. this.materials = new Array();
  7901. this.multiMaterials = new Array();
  7902. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7903. // Textures
  7904. this.texturesEnabled = true;
  7905. this.textures = new Array();
  7906. // Particles
  7907. this.particlesEnabled = true;
  7908. this.particleSystems = new Array();
  7909. // Sprites
  7910. this.spritesEnabled = true;
  7911. this.spriteManagers = new Array();
  7912. // Layers
  7913. this.layers = new Array();
  7914. // Skeletons
  7915. this.skeletonsEnabled = true;
  7916. this.skeletons = new Array();
  7917. // Lens flares
  7918. this.lensFlaresEnabled = true;
  7919. this.lensFlareSystems = new Array();
  7920. // Collisions
  7921. this.collisionsEnabled = true;
  7922. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7923. // Postprocesses
  7924. this.postProcessesEnabled = true;
  7925. // Customs render targets
  7926. this.renderTargetsEnabled = true;
  7927. this.dumpNextRenderTargets = false;
  7928. this.customRenderTargets = new Array();
  7929. // Imported meshes
  7930. this.importedMeshesFiles = new Array();
  7931. this._actionManagers = new Array();
  7932. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7933. // Procedural textures
  7934. this.proceduralTexturesEnabled = true;
  7935. this._proceduralTextures = new Array();
  7936. this.soundTracks = new Array();
  7937. this._audioEnabled = true;
  7938. this._totalVertices = 0;
  7939. this._activeVertices = 0;
  7940. this._activeParticles = 0;
  7941. this._lastFrameDuration = 0;
  7942. this._evaluateActiveMeshesDuration = 0;
  7943. this._renderTargetsDuration = 0;
  7944. this._particlesDuration = 0;
  7945. this._renderDuration = 0;
  7946. this._spritesDuration = 0;
  7947. this._animationRatio = 0;
  7948. this._renderId = 0;
  7949. this._executeWhenReadyTimeoutId = -1;
  7950. this._toBeDisposed = new BABYLON.SmartArray(256);
  7951. this._onReadyCallbacks = new Array();
  7952. this._pendingData = []; //ANY
  7953. this._onBeforeRenderCallbacks = new Array();
  7954. this._onAfterRenderCallbacks = new Array();
  7955. this._activeMeshes = new BABYLON.SmartArray(256);
  7956. this._processedMaterials = new BABYLON.SmartArray(256);
  7957. this._renderTargets = new BABYLON.SmartArray(256);
  7958. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7959. this._activeSkeletons = new BABYLON.SmartArray(32);
  7960. this._activeBones = 0;
  7961. this._activeAnimatables = new Array();
  7962. this._transformMatrix = BABYLON.Matrix.Zero();
  7963. this._scaledPosition = BABYLON.Vector3.Zero();
  7964. this._scaledVelocity = BABYLON.Vector3.Zero();
  7965. this._engine = engine;
  7966. engine.scenes.push(this);
  7967. this._renderingManager = new BABYLON.RenderingManager(this);
  7968. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7969. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7970. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7971. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7972. this.attachControl();
  7973. this._debugLayer = new BABYLON.DebugLayer(this);
  7974. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7975. //simplification queue
  7976. this.simplificationQueue = new BABYLON.SimplificationQueue();
  7977. }
  7978. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7979. get: function () {
  7980. return Scene._FOGMODE_NONE;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7986. get: function () {
  7987. return Scene._FOGMODE_EXP;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7993. get: function () {
  7994. return Scene._FOGMODE_EXP2;
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8000. get: function () {
  8001. return Scene._FOGMODE_LINEAR;
  8002. },
  8003. enumerable: true,
  8004. configurable: true
  8005. });
  8006. Object.defineProperty(Scene.prototype, "debugLayer", {
  8007. // Properties
  8008. get: function () {
  8009. return this._debugLayer;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8015. /**
  8016. * The mesh that is currently under the pointer.
  8017. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8018. */
  8019. get: function () {
  8020. return this._meshUnderPointer;
  8021. },
  8022. enumerable: true,
  8023. configurable: true
  8024. });
  8025. Object.defineProperty(Scene.prototype, "pointerX", {
  8026. /**
  8027. * Current on-screen X position of the pointer
  8028. * @return {number} X position of the pointer
  8029. */
  8030. get: function () {
  8031. return this._pointerX;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Scene.prototype, "pointerY", {
  8037. /**
  8038. * Current on-screen Y position of the pointer
  8039. * @return {number} Y position of the pointer
  8040. */
  8041. get: function () {
  8042. return this._pointerY;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Scene.prototype.getCachedMaterial = function () {
  8048. return this._cachedMaterial;
  8049. };
  8050. Scene.prototype.getBoundingBoxRenderer = function () {
  8051. return this._boundingBoxRenderer;
  8052. };
  8053. Scene.prototype.getOutlineRenderer = function () {
  8054. return this._outlineRenderer;
  8055. };
  8056. Scene.prototype.getEngine = function () {
  8057. return this._engine;
  8058. };
  8059. Scene.prototype.getTotalVertices = function () {
  8060. return this._totalVertices;
  8061. };
  8062. Scene.prototype.getActiveVertices = function () {
  8063. return this._activeVertices;
  8064. };
  8065. Scene.prototype.getActiveParticles = function () {
  8066. return this._activeParticles;
  8067. };
  8068. Scene.prototype.getActiveBones = function () {
  8069. return this._activeBones;
  8070. };
  8071. // Stats
  8072. Scene.prototype.getLastFrameDuration = function () {
  8073. return this._lastFrameDuration;
  8074. };
  8075. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8076. return this._evaluateActiveMeshesDuration;
  8077. };
  8078. Scene.prototype.getActiveMeshes = function () {
  8079. return this._activeMeshes;
  8080. };
  8081. Scene.prototype.getRenderTargetsDuration = function () {
  8082. return this._renderTargetsDuration;
  8083. };
  8084. Scene.prototype.getRenderDuration = function () {
  8085. return this._renderDuration;
  8086. };
  8087. Scene.prototype.getParticlesDuration = function () {
  8088. return this._particlesDuration;
  8089. };
  8090. Scene.prototype.getSpritesDuration = function () {
  8091. return this._spritesDuration;
  8092. };
  8093. Scene.prototype.getAnimationRatio = function () {
  8094. return this._animationRatio;
  8095. };
  8096. Scene.prototype.getRenderId = function () {
  8097. return this._renderId;
  8098. };
  8099. Scene.prototype.incrementRenderId = function () {
  8100. this._renderId++;
  8101. };
  8102. Scene.prototype._updatePointerPosition = function (evt) {
  8103. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8104. this._pointerX = evt.clientX - canvasRect.left;
  8105. this._pointerY = evt.clientY - canvasRect.top;
  8106. if (this.cameraToUseForPointers) {
  8107. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8108. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8109. }
  8110. };
  8111. // Pointers handling
  8112. Scene.prototype.attachControl = function () {
  8113. var _this = this;
  8114. this._onPointerMove = function (evt) {
  8115. var canvas = _this._engine.getRenderingCanvas();
  8116. _this._updatePointerPosition(evt);
  8117. 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);
  8118. if (pickResult.hit) {
  8119. _this._meshUnderPointer = pickResult.pickedMesh;
  8120. _this.setPointerOverMesh(pickResult.pickedMesh);
  8121. canvas.style.cursor = "pointer";
  8122. }
  8123. else {
  8124. _this.setPointerOverMesh(null);
  8125. canvas.style.cursor = "";
  8126. _this._meshUnderPointer = null;
  8127. }
  8128. };
  8129. this._onPointerDown = function (evt) {
  8130. var predicate = null;
  8131. if (!_this.onPointerDown) {
  8132. predicate = function (mesh) {
  8133. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8134. };
  8135. }
  8136. _this._updatePointerPosition(evt);
  8137. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8138. if (pickResult.hit) {
  8139. if (pickResult.pickedMesh.actionManager) {
  8140. switch (evt.button) {
  8141. case 0:
  8142. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8143. break;
  8144. case 1:
  8145. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8146. break;
  8147. case 2:
  8148. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8149. break;
  8150. }
  8151. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8152. }
  8153. }
  8154. if (_this.onPointerDown) {
  8155. _this.onPointerDown(evt, pickResult);
  8156. }
  8157. };
  8158. this._onKeyDown = function (evt) {
  8159. if (_this.actionManager) {
  8160. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8161. }
  8162. };
  8163. this._onKeyUp = function (evt) {
  8164. if (_this.actionManager) {
  8165. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8166. }
  8167. };
  8168. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8169. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8170. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8171. BABYLON.Tools.RegisterTopRootEvents([
  8172. { name: "keydown", handler: this._onKeyDown },
  8173. { name: "keyup", handler: this._onKeyUp }
  8174. ]);
  8175. };
  8176. Scene.prototype.detachControl = function () {
  8177. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8178. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8179. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8180. BABYLON.Tools.UnregisterTopRootEvents([
  8181. { name: "keydown", handler: this._onKeyDown },
  8182. { name: "keyup", handler: this._onKeyUp }
  8183. ]);
  8184. };
  8185. // Ready
  8186. Scene.prototype.isReady = function () {
  8187. if (this._pendingData.length > 0) {
  8188. return false;
  8189. }
  8190. for (var index = 0; index < this._geometries.length; index++) {
  8191. var geometry = this._geometries[index];
  8192. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8193. return false;
  8194. }
  8195. }
  8196. for (index = 0; index < this.meshes.length; index++) {
  8197. var mesh = this.meshes[index];
  8198. if (!mesh.isReady()) {
  8199. return false;
  8200. }
  8201. var mat = mesh.material;
  8202. if (mat) {
  8203. if (!mat.isReady(mesh)) {
  8204. return false;
  8205. }
  8206. }
  8207. }
  8208. return true;
  8209. };
  8210. Scene.prototype.resetCachedMaterial = function () {
  8211. this._cachedMaterial = null;
  8212. };
  8213. Scene.prototype.registerBeforeRender = function (func) {
  8214. this._onBeforeRenderCallbacks.push(func);
  8215. };
  8216. Scene.prototype.unregisterBeforeRender = function (func) {
  8217. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8218. if (index > -1) {
  8219. this._onBeforeRenderCallbacks.splice(index, 1);
  8220. }
  8221. };
  8222. Scene.prototype.registerAfterRender = function (func) {
  8223. this._onAfterRenderCallbacks.push(func);
  8224. };
  8225. Scene.prototype.unregisterAfterRender = function (func) {
  8226. var index = this._onAfterRenderCallbacks.indexOf(func);
  8227. if (index > -1) {
  8228. this._onAfterRenderCallbacks.splice(index, 1);
  8229. }
  8230. };
  8231. Scene.prototype._addPendingData = function (data) {
  8232. this._pendingData.push(data);
  8233. };
  8234. Scene.prototype._removePendingData = function (data) {
  8235. var index = this._pendingData.indexOf(data);
  8236. if (index !== -1) {
  8237. this._pendingData.splice(index, 1);
  8238. }
  8239. };
  8240. Scene.prototype.getWaitingItemsCount = function () {
  8241. return this._pendingData.length;
  8242. };
  8243. /**
  8244. * Registers a function to be executed when the scene is ready.
  8245. * @param {Function} func - the function to be executed.
  8246. */
  8247. Scene.prototype.executeWhenReady = function (func) {
  8248. var _this = this;
  8249. this._onReadyCallbacks.push(func);
  8250. if (this._executeWhenReadyTimeoutId !== -1) {
  8251. return;
  8252. }
  8253. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8254. _this._checkIsReady();
  8255. }, 150);
  8256. };
  8257. Scene.prototype._checkIsReady = function () {
  8258. var _this = this;
  8259. if (this.isReady()) {
  8260. this._onReadyCallbacks.forEach(function (func) {
  8261. func();
  8262. });
  8263. this._onReadyCallbacks = [];
  8264. this._executeWhenReadyTimeoutId = -1;
  8265. return;
  8266. }
  8267. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8268. _this._checkIsReady();
  8269. }, 150);
  8270. };
  8271. // Animations
  8272. /**
  8273. * Will start the animation sequence of a given target
  8274. * @param target - the target
  8275. * @param {number} from - from which frame should animation start
  8276. * @param {number} to - till which frame should animation run.
  8277. * @param {boolean} [loop] - should the animation loop
  8278. * @param {number} [speedRatio] - the speed in which to run the animation
  8279. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8280. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8281. * @return {BABYLON.Animatable} the animatable object created for this animation
  8282. * @see BABYLON.Animatable
  8283. * @see http://doc.babylonjs.com/page.php?p=22081
  8284. */
  8285. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8286. if (speedRatio === undefined) {
  8287. speedRatio = 1.0;
  8288. }
  8289. this.stopAnimation(target);
  8290. if (!animatable) {
  8291. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8292. }
  8293. // Local animations
  8294. if (target.animations) {
  8295. animatable.appendAnimations(target, target.animations);
  8296. }
  8297. // Children animations
  8298. if (target.getAnimatables) {
  8299. var animatables = target.getAnimatables();
  8300. for (var index = 0; index < animatables.length; index++) {
  8301. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8302. }
  8303. }
  8304. return animatable;
  8305. };
  8306. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8307. if (speedRatio === undefined) {
  8308. speedRatio = 1.0;
  8309. }
  8310. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8311. return animatable;
  8312. };
  8313. Scene.prototype.getAnimatableByTarget = function (target) {
  8314. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8315. if (this._activeAnimatables[index].target === target) {
  8316. return this._activeAnimatables[index];
  8317. }
  8318. }
  8319. return null;
  8320. };
  8321. /**
  8322. * Will stop the animation of the given target
  8323. * @param target - the target
  8324. * @see beginAnimation
  8325. */
  8326. Scene.prototype.stopAnimation = function (target) {
  8327. var animatable = this.getAnimatableByTarget(target);
  8328. if (animatable) {
  8329. animatable.stop();
  8330. }
  8331. };
  8332. Scene.prototype._animate = function () {
  8333. if (!this.animationsEnabled) {
  8334. return;
  8335. }
  8336. if (!this._animationStartDate) {
  8337. this._animationStartDate = BABYLON.Tools.Now;
  8338. }
  8339. // Getting time
  8340. var now = BABYLON.Tools.Now;
  8341. var delay = now - this._animationStartDate;
  8342. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8343. if (!this._activeAnimatables[index]._animate(delay)) {
  8344. this._activeAnimatables.splice(index, 1);
  8345. index--;
  8346. }
  8347. }
  8348. };
  8349. // Matrix
  8350. Scene.prototype.getViewMatrix = function () {
  8351. return this._viewMatrix;
  8352. };
  8353. Scene.prototype.getProjectionMatrix = function () {
  8354. return this._projectionMatrix;
  8355. };
  8356. Scene.prototype.getTransformMatrix = function () {
  8357. return this._transformMatrix;
  8358. };
  8359. Scene.prototype.setTransformMatrix = function (view, projection) {
  8360. this._viewMatrix = view;
  8361. this._projectionMatrix = projection;
  8362. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8363. };
  8364. // Methods
  8365. /**
  8366. * sets the active camera of the scene using its ID
  8367. * @param {string} id - the camera's ID
  8368. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8369. * @see activeCamera
  8370. */
  8371. Scene.prototype.setActiveCameraByID = function (id) {
  8372. var camera = this.getCameraByID(id);
  8373. if (camera) {
  8374. this.activeCamera = camera;
  8375. return camera;
  8376. }
  8377. return null;
  8378. };
  8379. /**
  8380. * sets the active camera of the scene using its name
  8381. * @param {string} name - the camera's name
  8382. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8383. * @see activeCamera
  8384. */
  8385. Scene.prototype.setActiveCameraByName = function (name) {
  8386. var camera = this.getCameraByName(name);
  8387. if (camera) {
  8388. this.activeCamera = camera;
  8389. return camera;
  8390. }
  8391. return null;
  8392. };
  8393. /**
  8394. * get a material using its id
  8395. * @param {string} the material's ID
  8396. * @return {BABYLON.Material|null} the material or null if none found.
  8397. */
  8398. Scene.prototype.getMaterialByID = function (id) {
  8399. for (var index = 0; index < this.materials.length; index++) {
  8400. if (this.materials[index].id === id) {
  8401. return this.materials[index];
  8402. }
  8403. }
  8404. return null;
  8405. };
  8406. /**
  8407. * get a material using its name
  8408. * @param {string} the material's name
  8409. * @return {BABYLON.Material|null} the material or null if none found.
  8410. */
  8411. Scene.prototype.getMaterialByName = function (name) {
  8412. for (var index = 0; index < this.materials.length; index++) {
  8413. if (this.materials[index].name === name) {
  8414. return this.materials[index];
  8415. }
  8416. }
  8417. return null;
  8418. };
  8419. Scene.prototype.getCameraByID = function (id) {
  8420. for (var index = 0; index < this.cameras.length; index++) {
  8421. if (this.cameras[index].id === id) {
  8422. return this.cameras[index];
  8423. }
  8424. }
  8425. return null;
  8426. };
  8427. /**
  8428. * get a camera using its name
  8429. * @param {string} the camera's name
  8430. * @return {BABYLON.Camera|null} the camera or null if none found.
  8431. */
  8432. Scene.prototype.getCameraByName = function (name) {
  8433. for (var index = 0; index < this.cameras.length; index++) {
  8434. if (this.cameras[index].name === name) {
  8435. return this.cameras[index];
  8436. }
  8437. }
  8438. return null;
  8439. };
  8440. /**
  8441. * get a light node using its name
  8442. * @param {string} the light's name
  8443. * @return {BABYLON.Light|null} the light or null if none found.
  8444. */
  8445. Scene.prototype.getLightByName = function (name) {
  8446. for (var index = 0; index < this.lights.length; index++) {
  8447. if (this.lights[index].name === name) {
  8448. return this.lights[index];
  8449. }
  8450. }
  8451. return null;
  8452. };
  8453. /**
  8454. * get a light node using its ID
  8455. * @param {string} the light's id
  8456. * @return {BABYLON.Light|null} the light or null if none found.
  8457. */
  8458. Scene.prototype.getLightByID = function (id) {
  8459. for (var index = 0; index < this.lights.length; index++) {
  8460. if (this.lights[index].id === id) {
  8461. return this.lights[index];
  8462. }
  8463. }
  8464. return null;
  8465. };
  8466. /**
  8467. * get a geometry using its ID
  8468. * @param {string} the geometry's id
  8469. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8470. */
  8471. Scene.prototype.getGeometryByID = function (id) {
  8472. for (var index = 0; index < this._geometries.length; index++) {
  8473. if (this._geometries[index].id === id) {
  8474. return this._geometries[index];
  8475. }
  8476. }
  8477. return null;
  8478. };
  8479. /**
  8480. * add a new geometry to this scene.
  8481. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8482. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8483. * @return {boolean} was the geometry added or not
  8484. */
  8485. Scene.prototype.pushGeometry = function (geometry, force) {
  8486. if (!force && this.getGeometryByID(geometry.id)) {
  8487. return false;
  8488. }
  8489. this._geometries.push(geometry);
  8490. return true;
  8491. };
  8492. Scene.prototype.getGeometries = function () {
  8493. return this._geometries;
  8494. };
  8495. /**
  8496. * Get a the first added mesh found of a given ID
  8497. * @param {string} id - the id to search for
  8498. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8499. */
  8500. Scene.prototype.getMeshByID = function (id) {
  8501. for (var index = 0; index < this.meshes.length; index++) {
  8502. if (this.meshes[index].id === id) {
  8503. return this.meshes[index];
  8504. }
  8505. }
  8506. return null;
  8507. };
  8508. /**
  8509. * Get a the last added mesh found of a given ID
  8510. * @param {string} id - the id to search for
  8511. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8512. */
  8513. Scene.prototype.getLastMeshByID = function (id) {
  8514. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8515. if (this.meshes[index].id === id) {
  8516. return this.meshes[index];
  8517. }
  8518. }
  8519. return null;
  8520. };
  8521. /**
  8522. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8523. * @param {string} id - the id to search for
  8524. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8525. */
  8526. Scene.prototype.getLastEntryByID = function (id) {
  8527. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8528. if (this.meshes[index].id === id) {
  8529. return this.meshes[index];
  8530. }
  8531. }
  8532. for (index = this.cameras.length - 1; index >= 0; index--) {
  8533. if (this.cameras[index].id === id) {
  8534. return this.cameras[index];
  8535. }
  8536. }
  8537. for (index = this.lights.length - 1; index >= 0; index--) {
  8538. if (this.lights[index].id === id) {
  8539. return this.lights[index];
  8540. }
  8541. }
  8542. return null;
  8543. };
  8544. Scene.prototype.getNodeByName = function (name) {
  8545. var mesh = this.getMeshByName(name);
  8546. if (mesh) {
  8547. return mesh;
  8548. }
  8549. var light = this.getLightByName(name);
  8550. if (light) {
  8551. return light;
  8552. }
  8553. return this.getCameraByName(name);
  8554. };
  8555. Scene.prototype.getMeshByName = function (name) {
  8556. for (var index = 0; index < this.meshes.length; index++) {
  8557. if (this.meshes[index].name === name) {
  8558. return this.meshes[index];
  8559. }
  8560. }
  8561. return null;
  8562. };
  8563. Scene.prototype.getSoundByName = function (name) {
  8564. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8565. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8566. return this.mainSoundTrack.soundCollection[index];
  8567. }
  8568. }
  8569. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8570. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8571. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8572. return this.soundTracks[sdIndex].soundCollection[index];
  8573. }
  8574. }
  8575. }
  8576. return null;
  8577. };
  8578. Scene.prototype.getLastSkeletonByID = function (id) {
  8579. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8580. if (this.skeletons[index].id === id) {
  8581. return this.skeletons[index];
  8582. }
  8583. }
  8584. return null;
  8585. };
  8586. Scene.prototype.getSkeletonById = function (id) {
  8587. for (var index = 0; index < this.skeletons.length; index++) {
  8588. if (this.skeletons[index].id === id) {
  8589. return this.skeletons[index];
  8590. }
  8591. }
  8592. return null;
  8593. };
  8594. Scene.prototype.getSkeletonByName = function (name) {
  8595. for (var index = 0; index < this.skeletons.length; index++) {
  8596. if (this.skeletons[index].name === name) {
  8597. return this.skeletons[index];
  8598. }
  8599. }
  8600. return null;
  8601. };
  8602. Scene.prototype.isActiveMesh = function (mesh) {
  8603. return (this._activeMeshes.indexOf(mesh) !== -1);
  8604. };
  8605. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8606. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8607. var material = subMesh.getMaterial();
  8608. if (mesh.showSubMeshesBoundingBox) {
  8609. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8610. }
  8611. if (material) {
  8612. // Render targets
  8613. if (material.getRenderTargetTextures) {
  8614. if (this._processedMaterials.indexOf(material) === -1) {
  8615. this._processedMaterials.push(material);
  8616. this._renderTargets.concat(material.getRenderTargetTextures());
  8617. }
  8618. }
  8619. // Dispatch
  8620. this._activeVertices += subMesh.indexCount;
  8621. this._renderingManager.dispatch(subMesh);
  8622. }
  8623. }
  8624. };
  8625. Scene.prototype._evaluateActiveMeshes = function () {
  8626. this.activeCamera._activeMeshes.reset();
  8627. this._activeMeshes.reset();
  8628. this._renderingManager.reset();
  8629. this._processedMaterials.reset();
  8630. this._activeParticleSystems.reset();
  8631. this._activeSkeletons.reset();
  8632. this._boundingBoxRenderer.reset();
  8633. if (!this._frustumPlanes) {
  8634. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8635. }
  8636. else {
  8637. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8638. }
  8639. // Meshes
  8640. var meshes;
  8641. var len;
  8642. if (this._selectionOctree) {
  8643. var selection = this._selectionOctree.select(this._frustumPlanes);
  8644. meshes = selection.data;
  8645. len = selection.length;
  8646. }
  8647. else {
  8648. len = this.meshes.length;
  8649. meshes = this.meshes;
  8650. }
  8651. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8652. var mesh = meshes[meshIndex];
  8653. if (mesh.isBlocked) {
  8654. continue;
  8655. }
  8656. this._totalVertices += mesh.getTotalVertices();
  8657. if (!mesh.isReady()) {
  8658. continue;
  8659. }
  8660. mesh.computeWorldMatrix();
  8661. // Intersections
  8662. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8663. this._meshesForIntersections.pushNoDuplicate(mesh);
  8664. }
  8665. // Switch to current LOD
  8666. var meshLOD = mesh.getLOD(this.activeCamera);
  8667. if (!meshLOD) {
  8668. continue;
  8669. }
  8670. mesh._preActivate();
  8671. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8672. this._activeMeshes.push(mesh);
  8673. this.activeCamera._activeMeshes.push(mesh);
  8674. mesh._activate(this._renderId);
  8675. this._activeMesh(meshLOD);
  8676. }
  8677. }
  8678. // Particle systems
  8679. var beforeParticlesDate = BABYLON.Tools.Now;
  8680. if (this.particlesEnabled) {
  8681. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8682. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8683. var particleSystem = this.particleSystems[particleIndex];
  8684. if (!particleSystem.isStarted()) {
  8685. continue;
  8686. }
  8687. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8688. this._activeParticleSystems.push(particleSystem);
  8689. particleSystem.animate();
  8690. }
  8691. }
  8692. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8693. }
  8694. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8695. };
  8696. Scene.prototype._activeMesh = function (mesh) {
  8697. if (mesh.skeleton && this.skeletonsEnabled) {
  8698. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8699. }
  8700. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8701. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8702. }
  8703. if (mesh && mesh.subMeshes) {
  8704. // Submeshes Octrees
  8705. var len;
  8706. var subMeshes;
  8707. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8708. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8709. len = intersections.length;
  8710. subMeshes = intersections.data;
  8711. }
  8712. else {
  8713. subMeshes = mesh.subMeshes;
  8714. len = subMeshes.length;
  8715. }
  8716. for (var subIndex = 0; subIndex < len; subIndex++) {
  8717. var subMesh = subMeshes[subIndex];
  8718. this._evaluateSubMesh(subMesh, mesh);
  8719. }
  8720. }
  8721. };
  8722. Scene.prototype.updateTransformMatrix = function (force) {
  8723. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8724. };
  8725. Scene.prototype._renderForCamera = function (camera) {
  8726. var engine = this._engine;
  8727. this.activeCamera = camera;
  8728. if (!this.activeCamera)
  8729. throw new Error("Active camera not set");
  8730. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8731. // Viewport
  8732. engine.setViewport(this.activeCamera.viewport);
  8733. // Camera
  8734. this._renderId++;
  8735. this.updateTransformMatrix();
  8736. if (this.beforeCameraRender) {
  8737. this.beforeCameraRender(this.activeCamera);
  8738. }
  8739. // Meshes
  8740. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8741. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8742. this._evaluateActiveMeshes();
  8743. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8744. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8745. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8746. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8747. skeleton.prepare();
  8748. }
  8749. // Render targets
  8750. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8751. if (this.renderTargetsEnabled) {
  8752. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8753. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8754. var renderTarget = this._renderTargets.data[renderIndex];
  8755. if (renderTarget._shouldRender()) {
  8756. this._renderId++;
  8757. renderTarget.render(false, this.dumpNextRenderTargets);
  8758. }
  8759. }
  8760. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8761. this._renderId++;
  8762. }
  8763. if (this._renderTargets.length > 0) {
  8764. engine.restoreDefaultFramebuffer();
  8765. }
  8766. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8767. // Prepare Frame
  8768. this.postProcessManager._prepareFrame();
  8769. var beforeRenderDate = BABYLON.Tools.Now;
  8770. // Backgrounds
  8771. if (this.layers.length) {
  8772. engine.setDepthBuffer(false);
  8773. var layerIndex;
  8774. var layer;
  8775. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8776. layer = this.layers[layerIndex];
  8777. if (layer.isBackground) {
  8778. layer.render();
  8779. }
  8780. }
  8781. engine.setDepthBuffer(true);
  8782. }
  8783. // Render
  8784. BABYLON.Tools.StartPerformanceCounter("Main render");
  8785. this._renderingManager.render(null, null, true, true);
  8786. BABYLON.Tools.EndPerformanceCounter("Main render");
  8787. // Bounding boxes
  8788. this._boundingBoxRenderer.render();
  8789. // Lens flares
  8790. if (this.lensFlaresEnabled) {
  8791. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8792. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8793. this.lensFlareSystems[lensFlareSystemIndex].render();
  8794. }
  8795. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8796. }
  8797. // Foregrounds
  8798. if (this.layers.length) {
  8799. engine.setDepthBuffer(false);
  8800. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8801. layer = this.layers[layerIndex];
  8802. if (!layer.isBackground) {
  8803. layer.render();
  8804. }
  8805. }
  8806. engine.setDepthBuffer(true);
  8807. }
  8808. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8809. // Finalize frame
  8810. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8811. // Update camera
  8812. this.activeCamera._updateFromScene();
  8813. // Reset some special arrays
  8814. this._renderTargets.reset();
  8815. if (this.afterCameraRender) {
  8816. this.afterCameraRender(this.activeCamera);
  8817. }
  8818. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8819. };
  8820. Scene.prototype._processSubCameras = function (camera) {
  8821. if (camera.subCameras.length === 0) {
  8822. this._renderForCamera(camera);
  8823. return;
  8824. }
  8825. for (var index = 0; index < camera.subCameras.length; index++) {
  8826. this._renderForCamera(camera.subCameras[index]);
  8827. }
  8828. this.activeCamera = camera;
  8829. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8830. // Update camera
  8831. this.activeCamera._updateFromScene();
  8832. };
  8833. Scene.prototype._checkIntersections = function () {
  8834. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8835. var sourceMesh = this._meshesForIntersections.data[index];
  8836. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8837. var action = sourceMesh.actionManager.actions[actionIndex];
  8838. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8839. var parameters = action.getTriggerParameter();
  8840. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8841. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8842. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8843. if (areIntersecting && currentIntersectionInProgress === -1) {
  8844. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8845. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8846. sourceMesh._intersectionsInProgress.push(otherMesh);
  8847. }
  8848. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8849. sourceMesh._intersectionsInProgress.push(otherMesh);
  8850. }
  8851. }
  8852. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8853. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8854. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8855. if (indexOfOther > -1) {
  8856. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8857. }
  8858. }
  8859. }
  8860. }
  8861. }
  8862. };
  8863. Scene.prototype.render = function () {
  8864. var startDate = BABYLON.Tools.Now;
  8865. this._particlesDuration = 0;
  8866. this._spritesDuration = 0;
  8867. this._activeParticles = 0;
  8868. this._renderDuration = 0;
  8869. this._renderTargetsDuration = 0;
  8870. this._evaluateActiveMeshesDuration = 0;
  8871. this._totalVertices = 0;
  8872. this._activeVertices = 0;
  8873. this._activeBones = 0;
  8874. this.getEngine().resetDrawCalls();
  8875. this._meshesForIntersections.reset();
  8876. this.resetCachedMaterial();
  8877. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8878. // Actions
  8879. if (this.actionManager) {
  8880. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8881. }
  8882. //Simplification Queue
  8883. if (!this.simplificationQueue.running) {
  8884. this.simplificationQueue.executeNext();
  8885. }
  8886. // Before render
  8887. if (this.beforeRender) {
  8888. this.beforeRender();
  8889. }
  8890. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8891. this._onBeforeRenderCallbacks[callbackIndex]();
  8892. }
  8893. // Animations
  8894. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8895. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8896. this._animate();
  8897. // Physics
  8898. if (this._physicsEngine) {
  8899. BABYLON.Tools.StartPerformanceCounter("Physics");
  8900. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8901. BABYLON.Tools.EndPerformanceCounter("Physics");
  8902. }
  8903. // Customs render targets
  8904. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8905. var engine = this.getEngine();
  8906. var currentActiveCamera = this.activeCamera;
  8907. if (this.renderTargetsEnabled) {
  8908. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8909. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8910. var renderTarget = this.customRenderTargets[customIndex];
  8911. if (renderTarget._shouldRender()) {
  8912. this._renderId++;
  8913. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8914. if (!this.activeCamera)
  8915. throw new Error("Active camera not set");
  8916. // Viewport
  8917. engine.setViewport(this.activeCamera.viewport);
  8918. // Camera
  8919. this.updateTransformMatrix();
  8920. renderTarget.render(false, this.dumpNextRenderTargets);
  8921. }
  8922. }
  8923. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8924. this._renderId++;
  8925. }
  8926. if (this.customRenderTargets.length > 0) {
  8927. engine.restoreDefaultFramebuffer();
  8928. }
  8929. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8930. this.activeCamera = currentActiveCamera;
  8931. // Procedural textures
  8932. if (this.proceduralTexturesEnabled) {
  8933. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8934. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8935. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8936. if (proceduralTexture._shouldRender()) {
  8937. proceduralTexture.render();
  8938. }
  8939. }
  8940. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8941. }
  8942. // Clear
  8943. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8944. // Shadows
  8945. if (this.shadowsEnabled) {
  8946. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8947. var light = this.lights[lightIndex];
  8948. var shadowGenerator = light.getShadowGenerator();
  8949. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8950. this._renderTargets.push(shadowGenerator.getShadowMap());
  8951. }
  8952. }
  8953. }
  8954. // Depth renderer
  8955. if (this._depthRenderer) {
  8956. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8957. }
  8958. // RenderPipeline
  8959. this.postProcessRenderPipelineManager.update();
  8960. // Multi-cameras?
  8961. if (this.activeCameras.length > 0) {
  8962. var currentRenderId = this._renderId;
  8963. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8964. this._renderId = currentRenderId;
  8965. this._processSubCameras(this.activeCameras[cameraIndex]);
  8966. }
  8967. }
  8968. else {
  8969. if (!this.activeCamera) {
  8970. throw new Error("No camera defined");
  8971. }
  8972. this._processSubCameras(this.activeCamera);
  8973. }
  8974. // Intersection checks
  8975. this._checkIntersections();
  8976. // Update the audio listener attached to the camera
  8977. this._updateAudioParameters();
  8978. // After render
  8979. if (this.afterRender) {
  8980. this.afterRender();
  8981. }
  8982. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8983. this._onAfterRenderCallbacks[callbackIndex]();
  8984. }
  8985. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8986. this._toBeDisposed.data[index].dispose();
  8987. this._toBeDisposed[index] = null;
  8988. }
  8989. this._toBeDisposed.reset();
  8990. if (this.dumpNextRenderTargets) {
  8991. this.dumpNextRenderTargets = false;
  8992. }
  8993. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8994. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8995. };
  8996. Scene.prototype._updateAudioParameters = function () {
  8997. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8998. return;
  8999. }
  9000. var listeningCamera;
  9001. var audioEngine = BABYLON.Engine.audioEngine;
  9002. if (this.activeCameras.length > 0) {
  9003. listeningCamera = this.activeCameras[0];
  9004. }
  9005. else {
  9006. listeningCamera = this.activeCamera;
  9007. }
  9008. if (listeningCamera && audioEngine.canUseWebAudio) {
  9009. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9010. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9011. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9012. cameraDirection.normalize();
  9013. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9014. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9015. var sound = this.mainSoundTrack.soundCollection[i];
  9016. if (sound.useCustomAttenuation) {
  9017. sound.updateDistanceFromListener();
  9018. }
  9019. }
  9020. for (i = 0; i < this.soundTracks.length; i++) {
  9021. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9022. sound = this.soundTracks[i].soundCollection[j];
  9023. if (sound.useCustomAttenuation) {
  9024. sound.updateDistanceFromListener();
  9025. }
  9026. }
  9027. }
  9028. }
  9029. };
  9030. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9031. get: function () {
  9032. return this._audioEnabled;
  9033. },
  9034. set: function (value) {
  9035. this._audioEnabled = value;
  9036. if (this._audioEnabled) {
  9037. this._enableAudio();
  9038. }
  9039. else {
  9040. this._disableAudio();
  9041. }
  9042. },
  9043. enumerable: true,
  9044. configurable: true
  9045. });
  9046. Scene.prototype._disableAudio = function () {
  9047. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9048. this.mainSoundTrack.soundCollection[i].pause();
  9049. }
  9050. for (i = 0; i < this.soundTracks.length; i++) {
  9051. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9052. this.soundTracks[i].soundCollection[j].pause();
  9053. }
  9054. }
  9055. };
  9056. Scene.prototype._enableAudio = function () {
  9057. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9058. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9059. this.mainSoundTrack.soundCollection[i].play();
  9060. }
  9061. }
  9062. for (i = 0; i < this.soundTracks.length; i++) {
  9063. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9064. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9065. this.soundTracks[i].soundCollection[j].play();
  9066. }
  9067. }
  9068. }
  9069. };
  9070. Scene.prototype.enableDepthRenderer = function () {
  9071. if (this._depthRenderer) {
  9072. return this._depthRenderer;
  9073. }
  9074. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9075. return this._depthRenderer;
  9076. };
  9077. Scene.prototype.disableDepthRenderer = function () {
  9078. if (!this._depthRenderer) {
  9079. return;
  9080. }
  9081. this._depthRenderer.dispose();
  9082. this._depthRenderer = null;
  9083. };
  9084. Scene.prototype.dispose = function () {
  9085. this.beforeRender = null;
  9086. this.afterRender = null;
  9087. this.skeletons = [];
  9088. this._boundingBoxRenderer.dispose();
  9089. if (this._depthRenderer) {
  9090. this._depthRenderer.dispose();
  9091. }
  9092. // Debug layer
  9093. this.debugLayer.hide();
  9094. // Events
  9095. if (this.onDispose) {
  9096. this.onDispose();
  9097. }
  9098. this._onBeforeRenderCallbacks = [];
  9099. this._onAfterRenderCallbacks = [];
  9100. this.detachControl();
  9101. // Release sounds & sounds tracks
  9102. this.disposeSounds();
  9103. // Detach cameras
  9104. var canvas = this._engine.getRenderingCanvas();
  9105. var index;
  9106. for (index = 0; index < this.cameras.length; index++) {
  9107. this.cameras[index].detachControl(canvas);
  9108. }
  9109. while (this.lights.length) {
  9110. this.lights[0].dispose();
  9111. }
  9112. while (this.meshes.length) {
  9113. this.meshes[0].dispose(true);
  9114. }
  9115. while (this.cameras.length) {
  9116. this.cameras[0].dispose();
  9117. }
  9118. while (this.materials.length) {
  9119. this.materials[0].dispose();
  9120. }
  9121. while (this.particleSystems.length) {
  9122. this.particleSystems[0].dispose();
  9123. }
  9124. while (this.spriteManagers.length) {
  9125. this.spriteManagers[0].dispose();
  9126. }
  9127. while (this.layers.length) {
  9128. this.layers[0].dispose();
  9129. }
  9130. while (this.textures.length) {
  9131. this.textures[0].dispose();
  9132. }
  9133. // Post-processes
  9134. this.postProcessManager.dispose();
  9135. // Physics
  9136. if (this._physicsEngine) {
  9137. this.disablePhysicsEngine();
  9138. }
  9139. // Remove from engine
  9140. index = this._engine.scenes.indexOf(this);
  9141. if (index > -1) {
  9142. this._engine.scenes.splice(index, 1);
  9143. }
  9144. this._engine.wipeCaches();
  9145. };
  9146. // Release sounds & sounds tracks
  9147. Scene.prototype.disposeSounds = function () {
  9148. this.mainSoundTrack.dispose();
  9149. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9150. this.soundTracks[scIndex].dispose();
  9151. }
  9152. };
  9153. // Collisions
  9154. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9155. if (excludedMesh === void 0) { excludedMesh = null; }
  9156. position.divideToRef(collider.radius, this._scaledPosition);
  9157. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9158. collider.retry = 0;
  9159. collider.initialVelocity = this._scaledVelocity;
  9160. collider.initialPosition = this._scaledPosition;
  9161. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9162. finalPosition.multiplyInPlace(collider.radius);
  9163. };
  9164. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9165. if (excludedMesh === void 0) { excludedMesh = null; }
  9166. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9167. if (collider.retry >= maximumRetry) {
  9168. finalPosition.copyFrom(position);
  9169. return;
  9170. }
  9171. collider._initialize(position, velocity, closeDistance);
  9172. for (var index = 0; index < this.meshes.length; index++) {
  9173. var mesh = this.meshes[index];
  9174. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9175. mesh._checkCollision(collider);
  9176. }
  9177. }
  9178. if (!collider.collisionFound) {
  9179. position.addToRef(velocity, finalPosition);
  9180. return;
  9181. }
  9182. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9183. collider._getResponse(position, velocity);
  9184. }
  9185. if (velocity.length() <= closeDistance) {
  9186. finalPosition.copyFrom(position);
  9187. return;
  9188. }
  9189. collider.retry++;
  9190. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9191. };
  9192. // Octrees
  9193. Scene.prototype.getWorldExtends = function () {
  9194. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9195. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9196. for (var index = 0; index < this.meshes.length; index++) {
  9197. var mesh = this.meshes[index];
  9198. mesh.computeWorldMatrix(true);
  9199. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9200. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9201. BABYLON.Tools.CheckExtends(minBox, min, max);
  9202. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9203. }
  9204. return {
  9205. min: min,
  9206. max: max
  9207. };
  9208. };
  9209. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9210. if (maxCapacity === void 0) { maxCapacity = 64; }
  9211. if (maxDepth === void 0) { maxDepth = 2; }
  9212. if (!this._selectionOctree) {
  9213. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9214. }
  9215. var worldExtends = this.getWorldExtends();
  9216. // Update octree
  9217. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9218. return this._selectionOctree;
  9219. };
  9220. // Picking
  9221. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9222. var engine = this._engine;
  9223. if (!camera) {
  9224. if (!this.activeCamera)
  9225. throw new Error("Active camera not set");
  9226. camera = this.activeCamera;
  9227. }
  9228. var cameraViewport = camera.viewport;
  9229. var viewport = cameraViewport.toGlobal(engine);
  9230. // Moving coordinates to local viewport world
  9231. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9232. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9233. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9234. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9235. };
  9236. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9237. var pickingInfo = null;
  9238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9239. var mesh = this.meshes[meshIndex];
  9240. if (predicate) {
  9241. if (!predicate(mesh)) {
  9242. continue;
  9243. }
  9244. }
  9245. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9246. continue;
  9247. }
  9248. var world = mesh.getWorldMatrix();
  9249. var ray = rayFunction(world);
  9250. var result = mesh.intersects(ray, fastCheck);
  9251. if (!result || !result.hit)
  9252. continue;
  9253. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9254. continue;
  9255. pickingInfo = result;
  9256. if (fastCheck) {
  9257. break;
  9258. }
  9259. }
  9260. return pickingInfo || new BABYLON.PickingInfo();
  9261. };
  9262. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9263. var _this = this;
  9264. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9265. /// <param name="x">X position on screen</param>
  9266. /// <param name="y">Y position on screen</param>
  9267. /// <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>
  9268. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9269. /// <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>
  9270. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9271. };
  9272. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9273. var _this = this;
  9274. return this._internalPick(function (world) {
  9275. if (!_this._pickWithRayInverseMatrix) {
  9276. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9277. }
  9278. world.invertToRef(_this._pickWithRayInverseMatrix);
  9279. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9280. }, predicate, fastCheck);
  9281. };
  9282. Scene.prototype.setPointerOverMesh = function (mesh) {
  9283. if (this._pointerOverMesh === mesh) {
  9284. return;
  9285. }
  9286. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9287. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9288. }
  9289. this._pointerOverMesh = mesh;
  9290. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9291. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9292. }
  9293. };
  9294. Scene.prototype.getPointerOverMesh = function () {
  9295. return this._pointerOverMesh;
  9296. };
  9297. // Physics
  9298. Scene.prototype.getPhysicsEngine = function () {
  9299. return this._physicsEngine;
  9300. };
  9301. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9302. if (this._physicsEngine) {
  9303. return true;
  9304. }
  9305. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9306. if (!this._physicsEngine.isSupported()) {
  9307. this._physicsEngine = null;
  9308. return false;
  9309. }
  9310. this._physicsEngine._initialize(gravity);
  9311. return true;
  9312. };
  9313. Scene.prototype.disablePhysicsEngine = function () {
  9314. if (!this._physicsEngine) {
  9315. return;
  9316. }
  9317. this._physicsEngine.dispose();
  9318. this._physicsEngine = undefined;
  9319. };
  9320. Scene.prototype.isPhysicsEnabled = function () {
  9321. return this._physicsEngine !== undefined;
  9322. };
  9323. Scene.prototype.setGravity = function (gravity) {
  9324. if (!this._physicsEngine) {
  9325. return;
  9326. }
  9327. this._physicsEngine._setGravity(gravity);
  9328. };
  9329. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9330. if (parts.parts) {
  9331. options = parts;
  9332. parts = parts.parts;
  9333. }
  9334. if (!this._physicsEngine) {
  9335. return null;
  9336. }
  9337. for (var index = 0; index < parts.length; index++) {
  9338. var mesh = parts[index].mesh;
  9339. mesh._physicImpostor = parts[index].impostor;
  9340. mesh._physicsMass = options.mass / parts.length;
  9341. mesh._physicsFriction = options.friction;
  9342. mesh._physicRestitution = options.restitution;
  9343. }
  9344. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9345. };
  9346. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9347. for (var index = 0; index < compound.parts.length; index++) {
  9348. var mesh = compound.parts[index].mesh;
  9349. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9350. this._physicsEngine._unregisterMesh(mesh);
  9351. }
  9352. };
  9353. // Misc.
  9354. Scene.prototype.createDefaultCameraOrLight = function () {
  9355. // Light
  9356. if (this.lights.length === 0) {
  9357. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9358. }
  9359. // Camera
  9360. if (!this.activeCamera) {
  9361. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9362. // Compute position
  9363. var worldExtends = this.getWorldExtends();
  9364. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9365. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9366. camera.setTarget(worldCenter);
  9367. this.activeCamera = camera;
  9368. }
  9369. };
  9370. // Tags
  9371. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9372. if (tagsQuery === undefined) {
  9373. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9374. return list;
  9375. }
  9376. var listByTags = [];
  9377. forEach = forEach || (function (item) {
  9378. return;
  9379. });
  9380. for (var i in list) {
  9381. var item = list[i];
  9382. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9383. listByTags.push(item);
  9384. forEach(item);
  9385. }
  9386. }
  9387. return listByTags;
  9388. };
  9389. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9390. return this._getByTags(this.meshes, tagsQuery, forEach);
  9391. };
  9392. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9393. return this._getByTags(this.cameras, tagsQuery, forEach);
  9394. };
  9395. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9396. return this._getByTags(this.lights, tagsQuery, forEach);
  9397. };
  9398. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9399. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9400. };
  9401. // Audio
  9402. Scene.prototype.switchAudioModeForHeadphones = function () {
  9403. this.mainSoundTrack.switchPanningModelToHRTF();
  9404. for (var i = 0; i < this.soundTracks.length; i++) {
  9405. this.soundTracks[i].switchPanningModelToHRTF();
  9406. }
  9407. };
  9408. Scene.prototype.switchAudioModeForNormalSpeakers = function () {
  9409. this.mainSoundTrack.switchPanningModelToEqualPower();
  9410. for (var i = 0; i < this.soundTracks.length; i++) {
  9411. this.soundTracks[i].switchPanningModelToEqualPower();
  9412. }
  9413. };
  9414. // Statics
  9415. Scene._FOGMODE_NONE = 0;
  9416. Scene._FOGMODE_EXP = 1;
  9417. Scene._FOGMODE_EXP2 = 2;
  9418. Scene._FOGMODE_LINEAR = 3;
  9419. Scene.MinDeltaTime = 1.0;
  9420. Scene.MaxDeltaTime = 1000.0;
  9421. return Scene;
  9422. })();
  9423. BABYLON.Scene = Scene;
  9424. })(BABYLON || (BABYLON = {}));
  9425. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9426. (function (BABYLON) {
  9427. var VertexBuffer = (function () {
  9428. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9429. if (engine instanceof BABYLON.Mesh) {
  9430. this._engine = engine.getScene().getEngine();
  9431. }
  9432. else {
  9433. this._engine = engine;
  9434. }
  9435. this._updatable = updatable;
  9436. this._data = data;
  9437. if (!postponeInternalCreation) {
  9438. this.create();
  9439. }
  9440. this._kind = kind;
  9441. if (stride) {
  9442. this._strideSize = stride;
  9443. return;
  9444. }
  9445. switch (kind) {
  9446. case VertexBuffer.PositionKind:
  9447. this._strideSize = 3;
  9448. break;
  9449. case VertexBuffer.NormalKind:
  9450. this._strideSize = 3;
  9451. break;
  9452. case VertexBuffer.UVKind:
  9453. this._strideSize = 2;
  9454. break;
  9455. case VertexBuffer.UV2Kind:
  9456. this._strideSize = 2;
  9457. break;
  9458. case VertexBuffer.ColorKind:
  9459. this._strideSize = 4;
  9460. break;
  9461. case VertexBuffer.MatricesIndicesKind:
  9462. this._strideSize = 4;
  9463. break;
  9464. case VertexBuffer.MatricesWeightsKind:
  9465. this._strideSize = 4;
  9466. break;
  9467. }
  9468. }
  9469. // Properties
  9470. VertexBuffer.prototype.isUpdatable = function () {
  9471. return this._updatable;
  9472. };
  9473. VertexBuffer.prototype.getData = function () {
  9474. return this._data;
  9475. };
  9476. VertexBuffer.prototype.getBuffer = function () {
  9477. return this._buffer;
  9478. };
  9479. VertexBuffer.prototype.getStrideSize = function () {
  9480. return this._strideSize;
  9481. };
  9482. // Methods
  9483. VertexBuffer.prototype.create = function (data) {
  9484. if (!data && this._buffer) {
  9485. return; // nothing to do
  9486. }
  9487. data = data || this._data;
  9488. if (!this._buffer) {
  9489. if (this._updatable) {
  9490. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9491. }
  9492. else {
  9493. this._buffer = this._engine.createVertexBuffer(data);
  9494. }
  9495. }
  9496. if (this._updatable) {
  9497. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9498. this._data = data;
  9499. }
  9500. };
  9501. VertexBuffer.prototype.update = function (data) {
  9502. this.create(data);
  9503. };
  9504. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9505. if (!this._buffer) {
  9506. return;
  9507. }
  9508. if (this._updatable) {
  9509. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9510. this._data = null;
  9511. }
  9512. };
  9513. VertexBuffer.prototype.dispose = function () {
  9514. if (!this._buffer) {
  9515. return;
  9516. }
  9517. if (this._engine._releaseBuffer(this._buffer)) {
  9518. this._buffer = null;
  9519. }
  9520. };
  9521. Object.defineProperty(VertexBuffer, "PositionKind", {
  9522. get: function () {
  9523. return VertexBuffer._PositionKind;
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Object.defineProperty(VertexBuffer, "NormalKind", {
  9529. get: function () {
  9530. return VertexBuffer._NormalKind;
  9531. },
  9532. enumerable: true,
  9533. configurable: true
  9534. });
  9535. Object.defineProperty(VertexBuffer, "UVKind", {
  9536. get: function () {
  9537. return VertexBuffer._UVKind;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9543. get: function () {
  9544. return VertexBuffer._UV2Kind;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(VertexBuffer, "ColorKind", {
  9550. get: function () {
  9551. return VertexBuffer._ColorKind;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9557. get: function () {
  9558. return VertexBuffer._MatricesIndicesKind;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9564. get: function () {
  9565. return VertexBuffer._MatricesWeightsKind;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. // Enums
  9571. VertexBuffer._PositionKind = "position";
  9572. VertexBuffer._NormalKind = "normal";
  9573. VertexBuffer._UVKind = "uv";
  9574. VertexBuffer._UV2Kind = "uv2";
  9575. VertexBuffer._ColorKind = "color";
  9576. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9577. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9578. return VertexBuffer;
  9579. })();
  9580. BABYLON.VertexBuffer = VertexBuffer;
  9581. })(BABYLON || (BABYLON = {}));
  9582. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9583. var BABYLON;
  9584. (function (BABYLON) {
  9585. var AbstractMesh = (function (_super) {
  9586. __extends(AbstractMesh, _super);
  9587. function AbstractMesh(name, scene) {
  9588. _super.call(this, name, scene);
  9589. // Properties
  9590. this.definedFacingForward = true; // orientation for POV movement & rotation
  9591. this.position = new BABYLON.Vector3(0, 0, 0);
  9592. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9593. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9594. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9595. this.visibility = 1.0;
  9596. this.alphaIndex = Number.MAX_VALUE;
  9597. this.infiniteDistance = false;
  9598. this.isVisible = true;
  9599. this.isPickable = true;
  9600. this.showBoundingBox = false;
  9601. this.showSubMeshesBoundingBox = false;
  9602. this.onDispose = null;
  9603. this.checkCollisions = false;
  9604. this.isBlocker = false;
  9605. this.renderingGroupId = 0;
  9606. this.receiveShadows = false;
  9607. this.renderOutline = false;
  9608. this.outlineColor = BABYLON.Color3.Red();
  9609. this.outlineWidth = 0.02;
  9610. this.renderOverlay = false;
  9611. this.overlayColor = BABYLON.Color3.Red();
  9612. this.overlayAlpha = 0.5;
  9613. this.hasVertexAlpha = false;
  9614. this.useVertexColors = true;
  9615. this.applyFog = true;
  9616. this.useOctreeForRenderingSelection = true;
  9617. this.useOctreeForPicking = true;
  9618. this.useOctreeForCollisions = true;
  9619. this.layerMask = 0xFFFFFFFF;
  9620. // Physics
  9621. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9622. // Collisions
  9623. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9624. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9625. this._collider = new BABYLON.Collider();
  9626. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9627. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9628. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9629. // Cache
  9630. this._localScaling = BABYLON.Matrix.Zero();
  9631. this._localRotation = BABYLON.Matrix.Zero();
  9632. this._localTranslation = BABYLON.Matrix.Zero();
  9633. this._localBillboard = BABYLON.Matrix.Zero();
  9634. this._localPivotScaling = BABYLON.Matrix.Zero();
  9635. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9636. this._localWorld = BABYLON.Matrix.Zero();
  9637. this._worldMatrix = BABYLON.Matrix.Zero();
  9638. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9639. this._absolutePosition = BABYLON.Vector3.Zero();
  9640. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9641. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9642. this._isDirty = false;
  9643. this._pivotMatrix = BABYLON.Matrix.Identity();
  9644. this._isDisposed = false;
  9645. this._renderId = 0;
  9646. this._intersectionsInProgress = new Array();
  9647. this._onAfterWorldMatrixUpdate = new Array();
  9648. scene.meshes.push(this);
  9649. }
  9650. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9651. get: function () {
  9652. return AbstractMesh._BILLBOARDMODE_NONE;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9658. get: function () {
  9659. return AbstractMesh._BILLBOARDMODE_X;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9665. get: function () {
  9666. return AbstractMesh._BILLBOARDMODE_Y;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9672. get: function () {
  9673. return AbstractMesh._BILLBOARDMODE_Z;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9679. get: function () {
  9680. return AbstractMesh._BILLBOARDMODE_ALL;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9686. // Methods
  9687. get: function () {
  9688. return false;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. AbstractMesh.prototype.getLOD = function (camera) {
  9694. return this;
  9695. };
  9696. AbstractMesh.prototype.getTotalVertices = function () {
  9697. return 0;
  9698. };
  9699. AbstractMesh.prototype.getIndices = function () {
  9700. return null;
  9701. };
  9702. AbstractMesh.prototype.getVerticesData = function (kind) {
  9703. return null;
  9704. };
  9705. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9706. return false;
  9707. };
  9708. AbstractMesh.prototype.getBoundingInfo = function () {
  9709. if (this._masterMesh) {
  9710. return this._masterMesh.getBoundingInfo();
  9711. }
  9712. if (!this._boundingInfo) {
  9713. this._updateBoundingInfo();
  9714. }
  9715. return this._boundingInfo;
  9716. };
  9717. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9718. get: function () {
  9719. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9720. },
  9721. enumerable: true,
  9722. configurable: true
  9723. });
  9724. AbstractMesh.prototype._preActivate = function () {
  9725. };
  9726. AbstractMesh.prototype._activate = function (renderId) {
  9727. this._renderId = renderId;
  9728. };
  9729. AbstractMesh.prototype.getWorldMatrix = function () {
  9730. if (this._masterMesh) {
  9731. return this._masterMesh.getWorldMatrix();
  9732. }
  9733. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9734. this.computeWorldMatrix();
  9735. }
  9736. return this._worldMatrix;
  9737. };
  9738. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9739. get: function () {
  9740. return this._worldMatrix;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9746. get: function () {
  9747. return this._absolutePosition;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9753. if (!this.rotationQuaternion) {
  9754. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9755. this.rotation = BABYLON.Vector3.Zero();
  9756. }
  9757. if (!space || space == 0 /* LOCAL */) {
  9758. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9759. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9760. }
  9761. else {
  9762. if (this.parent) {
  9763. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9764. invertParentWorldMatrix.invert();
  9765. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9766. }
  9767. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9768. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9769. }
  9770. };
  9771. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9772. var displacementVector = axis.scale(distance);
  9773. if (!space || space == 0 /* LOCAL */) {
  9774. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9775. this.setPositionWithLocalVector(tempV3);
  9776. }
  9777. else {
  9778. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9779. }
  9780. };
  9781. AbstractMesh.prototype.getAbsolutePosition = function () {
  9782. this.computeWorldMatrix();
  9783. return this._absolutePosition;
  9784. };
  9785. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9786. if (!absolutePosition) {
  9787. return;
  9788. }
  9789. var absolutePositionX;
  9790. var absolutePositionY;
  9791. var absolutePositionZ;
  9792. if (absolutePosition.x === undefined) {
  9793. if (arguments.length < 3) {
  9794. return;
  9795. }
  9796. absolutePositionX = arguments[0];
  9797. absolutePositionY = arguments[1];
  9798. absolutePositionZ = arguments[2];
  9799. }
  9800. else {
  9801. absolutePositionX = absolutePosition.x;
  9802. absolutePositionY = absolutePosition.y;
  9803. absolutePositionZ = absolutePosition.z;
  9804. }
  9805. if (this.parent) {
  9806. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9807. invertParentWorldMatrix.invert();
  9808. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9809. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9810. }
  9811. else {
  9812. this.position.x = absolutePositionX;
  9813. this.position.y = absolutePositionY;
  9814. this.position.z = absolutePositionZ;
  9815. }
  9816. };
  9817. // ================================== Point of View Movement =================================
  9818. /**
  9819. * Perform relative position change from the point of view of behind the front of the mesh.
  9820. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9821. * Supports definition of mesh facing forward or backward.
  9822. * @param {number} amountRight
  9823. * @param {number} amountUp
  9824. * @param {number} amountForward
  9825. */
  9826. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9827. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9828. };
  9829. /**
  9830. * Calculate relative position change from the point of view of behind the front of the mesh.
  9831. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9832. * Supports definition of mesh facing forward or backward.
  9833. * @param {number} amountRight
  9834. * @param {number} amountUp
  9835. * @param {number} amountForward
  9836. */
  9837. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9838. var rotMatrix = new BABYLON.Matrix();
  9839. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9840. rotQuaternion.toRotationMatrix(rotMatrix);
  9841. var translationDelta = BABYLON.Vector3.Zero();
  9842. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9843. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9844. return translationDelta;
  9845. };
  9846. // ================================== Point of View Rotation =================================
  9847. /**
  9848. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9849. * Supports definition of mesh facing forward or backward.
  9850. * @param {number} flipBack
  9851. * @param {number} twirlClockwise
  9852. * @param {number} tiltRight
  9853. */
  9854. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9855. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9856. };
  9857. /**
  9858. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9859. * Supports definition of mesh facing forward or backward.
  9860. * @param {number} flipBack
  9861. * @param {number} twirlClockwise
  9862. * @param {number} tiltRight
  9863. */
  9864. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9865. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9866. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9867. };
  9868. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9869. this._pivotMatrix = matrix;
  9870. this._cache.pivotMatrixUpdated = true;
  9871. };
  9872. AbstractMesh.prototype.getPivotMatrix = function () {
  9873. return this._pivotMatrix;
  9874. };
  9875. AbstractMesh.prototype._isSynchronized = function () {
  9876. if (this._isDirty) {
  9877. return false;
  9878. }
  9879. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9880. return false;
  9881. if (this._cache.pivotMatrixUpdated) {
  9882. return false;
  9883. }
  9884. if (this.infiniteDistance) {
  9885. return false;
  9886. }
  9887. if (!this._cache.position.equals(this.position))
  9888. return false;
  9889. if (this.rotationQuaternion) {
  9890. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9891. return false;
  9892. }
  9893. else {
  9894. if (!this._cache.rotation.equals(this.rotation))
  9895. return false;
  9896. }
  9897. if (!this._cache.scaling.equals(this.scaling))
  9898. return false;
  9899. return true;
  9900. };
  9901. AbstractMesh.prototype._initCache = function () {
  9902. _super.prototype._initCache.call(this);
  9903. this._cache.localMatrixUpdated = false;
  9904. this._cache.position = BABYLON.Vector3.Zero();
  9905. this._cache.scaling = BABYLON.Vector3.Zero();
  9906. this._cache.rotation = BABYLON.Vector3.Zero();
  9907. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9908. };
  9909. AbstractMesh.prototype.markAsDirty = function (property) {
  9910. if (property === "rotation") {
  9911. this.rotationQuaternion = null;
  9912. }
  9913. this._currentRenderId = Number.MAX_VALUE;
  9914. this._isDirty = true;
  9915. };
  9916. AbstractMesh.prototype._updateBoundingInfo = function () {
  9917. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9918. this._boundingInfo._update(this.worldMatrixFromCache);
  9919. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9920. };
  9921. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9922. if (!this.subMeshes) {
  9923. return;
  9924. }
  9925. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9926. var subMesh = this.subMeshes[subIndex];
  9927. subMesh.updateBoundingInfo(matrix);
  9928. }
  9929. };
  9930. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9931. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9932. return this._worldMatrix;
  9933. }
  9934. this._cache.position.copyFrom(this.position);
  9935. this._cache.scaling.copyFrom(this.scaling);
  9936. this._cache.pivotMatrixUpdated = false;
  9937. this._currentRenderId = this.getScene().getRenderId();
  9938. this._isDirty = false;
  9939. // Scaling
  9940. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9941. // Rotation
  9942. if (this.rotationQuaternion) {
  9943. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9944. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9945. }
  9946. else {
  9947. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9948. this._cache.rotation.copyFrom(this.rotation);
  9949. }
  9950. // Translation
  9951. if (this.infiniteDistance && !this.parent) {
  9952. var camera = this.getScene().activeCamera;
  9953. var cameraWorldMatrix = camera.getWorldMatrix();
  9954. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9955. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9956. }
  9957. else {
  9958. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9959. }
  9960. // Composing transformations
  9961. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9962. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9963. // Billboarding
  9964. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9965. var localPosition = this.position.clone();
  9966. var zero = this.getScene().activeCamera.position.clone();
  9967. if (this.parent && this.parent.position) {
  9968. localPosition.addInPlace(this.parent.position);
  9969. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9970. }
  9971. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9972. zero = this.getScene().activeCamera.position;
  9973. }
  9974. else {
  9975. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9976. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9977. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9978. zero.y = localPosition.y + 0.001;
  9979. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9980. zero.z = localPosition.z + 0.001;
  9981. }
  9982. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9983. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9984. this._localBillboard.invert();
  9985. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9986. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9987. }
  9988. // Local world
  9989. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9990. // Parent
  9991. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9992. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9993. }
  9994. else {
  9995. this._worldMatrix.copyFrom(this._localWorld);
  9996. }
  9997. // Bounding info
  9998. this._updateBoundingInfo();
  9999. // Absolute position
  10000. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10001. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10002. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10003. }
  10004. return this._worldMatrix;
  10005. };
  10006. /**
  10007. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10008. * @param func: callback function to add
  10009. */
  10010. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10011. this._onAfterWorldMatrixUpdate.push(func);
  10012. };
  10013. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10014. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10015. if (index > -1) {
  10016. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10017. }
  10018. };
  10019. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10020. this.computeWorldMatrix();
  10021. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10022. };
  10023. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10024. this.computeWorldMatrix();
  10025. var invLocalWorldMatrix = this._localWorld.clone();
  10026. invLocalWorldMatrix.invert();
  10027. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10028. };
  10029. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10030. this.computeWorldMatrix();
  10031. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10032. };
  10033. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10034. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10035. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  10036. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10037. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10038. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10039. /// <returns>Mesh oriented towards targetMesh</returns>
  10040. yawCor = yawCor || 0; // default to zero if undefined
  10041. pitchCor = pitchCor || 0;
  10042. rollCor = rollCor || 0;
  10043. var dv = targetPoint.subtract(this.position);
  10044. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10045. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10046. var pitch = Math.atan2(dv.y, len);
  10047. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10048. };
  10049. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10050. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10051. return false;
  10052. }
  10053. return true;
  10054. };
  10055. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10056. if (!camera) {
  10057. camera = this.getScene().activeCamera;
  10058. }
  10059. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10060. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10061. return false;
  10062. }
  10063. return true;
  10064. };
  10065. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10066. if (!this._boundingInfo || !mesh._boundingInfo) {
  10067. return false;
  10068. }
  10069. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10070. };
  10071. AbstractMesh.prototype.intersectsPoint = function (point) {
  10072. if (!this._boundingInfo) {
  10073. return false;
  10074. }
  10075. return this._boundingInfo.intersectsPoint(point);
  10076. };
  10077. // Physics
  10078. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10079. var physicsEngine = this.getScene().getPhysicsEngine();
  10080. if (!physicsEngine) {
  10081. return;
  10082. }
  10083. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10084. if (impostor.impostor) {
  10085. // Old API
  10086. options = impostor;
  10087. impostor = impostor.impostor;
  10088. }
  10089. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10090. physicsEngine._unregisterMesh(this);
  10091. return;
  10092. }
  10093. if (!options) {
  10094. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10095. }
  10096. else {
  10097. if (!options.mass && options.mass !== 0)
  10098. options.mass = 0;
  10099. if (!options.friction && options.friction !== 0)
  10100. options.friction = 0.2;
  10101. if (!options.restitution && options.restitution !== 0)
  10102. options.restitution = 0.2;
  10103. }
  10104. this._physicImpostor = impostor;
  10105. this._physicsMass = options.mass;
  10106. this._physicsFriction = options.friction;
  10107. this._physicRestitution = options.restitution;
  10108. return physicsEngine._registerMesh(this, impostor, options);
  10109. };
  10110. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10111. if (!this._physicImpostor) {
  10112. return BABYLON.PhysicsEngine.NoImpostor;
  10113. }
  10114. return this._physicImpostor;
  10115. };
  10116. AbstractMesh.prototype.getPhysicsMass = function () {
  10117. if (!this._physicsMass) {
  10118. return 0;
  10119. }
  10120. return this._physicsMass;
  10121. };
  10122. AbstractMesh.prototype.getPhysicsFriction = function () {
  10123. if (!this._physicsFriction) {
  10124. return 0;
  10125. }
  10126. return this._physicsFriction;
  10127. };
  10128. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10129. if (!this._physicRestitution) {
  10130. return 0;
  10131. }
  10132. return this._physicRestitution;
  10133. };
  10134. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10135. if (!camera) {
  10136. camera = this.getScene().activeCamera;
  10137. }
  10138. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10139. };
  10140. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10141. if (!camera) {
  10142. camera = this.getScene().activeCamera;
  10143. }
  10144. return this.absolutePosition.subtract(camera.position).length();
  10145. };
  10146. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10147. if (!this._physicImpostor) {
  10148. return;
  10149. }
  10150. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10151. };
  10152. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10153. if (!this._physicImpostor) {
  10154. return;
  10155. }
  10156. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10157. };
  10158. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10159. if (!this._physicImpostor) {
  10160. return;
  10161. }
  10162. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10163. };
  10164. // Collisions
  10165. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10166. var globalPosition = this.getAbsolutePosition();
  10167. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10168. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10169. this._collider.radius = this.ellipsoid;
  10170. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10171. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10172. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10173. this.position.addInPlace(this._diffPositionForCollisions);
  10174. }
  10175. };
  10176. // Submeshes octree
  10177. /**
  10178. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10179. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10180. */
  10181. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10182. if (maxCapacity === void 0) { maxCapacity = 64; }
  10183. if (maxDepth === void 0) { maxDepth = 2; }
  10184. if (!this._submeshesOctree) {
  10185. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10186. }
  10187. this.computeWorldMatrix(true);
  10188. // Update octree
  10189. var bbox = this.getBoundingInfo().boundingBox;
  10190. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10191. return this._submeshesOctree;
  10192. };
  10193. // Collisions
  10194. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10195. this._generatePointsArray();
  10196. // Transformation
  10197. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10198. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10199. subMesh._lastColliderWorldVertices = [];
  10200. subMesh._trianglePlanes = [];
  10201. var start = subMesh.verticesStart;
  10202. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10203. for (var i = start; i < end; i++) {
  10204. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10205. }
  10206. }
  10207. // Collide
  10208. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10209. };
  10210. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10211. var subMeshes;
  10212. var len;
  10213. // Octrees
  10214. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10215. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10216. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10217. len = intersections.length;
  10218. subMeshes = intersections.data;
  10219. }
  10220. else {
  10221. subMeshes = this.subMeshes;
  10222. len = subMeshes.length;
  10223. }
  10224. for (var index = 0; index < len; index++) {
  10225. var subMesh = subMeshes[index];
  10226. // Bounding test
  10227. if (len > 1 && !subMesh._checkCollision(collider))
  10228. continue;
  10229. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10230. }
  10231. };
  10232. AbstractMesh.prototype._checkCollision = function (collider) {
  10233. // Bounding box test
  10234. if (!this._boundingInfo._checkCollision(collider))
  10235. return;
  10236. // Transformation matrix
  10237. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10238. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10239. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10240. };
  10241. // Picking
  10242. AbstractMesh.prototype._generatePointsArray = function () {
  10243. return false;
  10244. };
  10245. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10246. var pickingInfo = new BABYLON.PickingInfo();
  10247. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10248. return pickingInfo;
  10249. }
  10250. if (!this._generatePointsArray()) {
  10251. return pickingInfo;
  10252. }
  10253. var intersectInfo = null;
  10254. // Octrees
  10255. var subMeshes;
  10256. var len;
  10257. if (this._submeshesOctree && this.useOctreeForPicking) {
  10258. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10259. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10260. len = intersections.length;
  10261. subMeshes = intersections.data;
  10262. }
  10263. else {
  10264. subMeshes = this.subMeshes;
  10265. len = subMeshes.length;
  10266. }
  10267. for (var index = 0; index < len; index++) {
  10268. var subMesh = subMeshes[index];
  10269. // Bounding test
  10270. if (len > 1 && !subMesh.canIntersects(ray))
  10271. continue;
  10272. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10273. if (currentIntersectInfo) {
  10274. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10275. intersectInfo = currentIntersectInfo;
  10276. intersectInfo.subMeshId = index;
  10277. if (fastCheck) {
  10278. break;
  10279. }
  10280. }
  10281. }
  10282. }
  10283. if (intersectInfo) {
  10284. // Get picked point
  10285. var world = this.getWorldMatrix();
  10286. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10287. var direction = ray.direction.clone();
  10288. direction = direction.scale(intersectInfo.distance);
  10289. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10290. var pickedPoint = worldOrigin.add(worldDirection);
  10291. // Return result
  10292. pickingInfo.hit = true;
  10293. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10294. pickingInfo.pickedPoint = pickedPoint;
  10295. pickingInfo.pickedMesh = this;
  10296. pickingInfo.bu = intersectInfo.bu;
  10297. pickingInfo.bv = intersectInfo.bv;
  10298. pickingInfo.faceId = intersectInfo.faceId;
  10299. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10300. return pickingInfo;
  10301. }
  10302. return pickingInfo;
  10303. };
  10304. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10305. return null;
  10306. };
  10307. AbstractMesh.prototype.releaseSubMeshes = function () {
  10308. if (this.subMeshes) {
  10309. while (this.subMeshes.length) {
  10310. this.subMeshes[0].dispose();
  10311. }
  10312. }
  10313. else {
  10314. this.subMeshes = new Array();
  10315. }
  10316. };
  10317. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10318. // Physics
  10319. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10320. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10321. }
  10322. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10323. var other = this._intersectionsInProgress[index];
  10324. var pos = other._intersectionsInProgress.indexOf(this);
  10325. other._intersectionsInProgress.splice(pos, 1);
  10326. }
  10327. this._intersectionsInProgress = [];
  10328. // SubMeshes
  10329. this.releaseSubMeshes();
  10330. // Remove from scene
  10331. var index = this.getScene().meshes.indexOf(this);
  10332. if (index != -1) {
  10333. // Remove from the scene if mesh found
  10334. this.getScene().meshes.splice(index, 1);
  10335. }
  10336. if (!doNotRecurse) {
  10337. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10338. if (this.getScene().particleSystems[index].emitter == this) {
  10339. this.getScene().particleSystems[index].dispose();
  10340. index--;
  10341. }
  10342. }
  10343. // Children
  10344. var objects = this.getScene().meshes.slice(0);
  10345. for (index = 0; index < objects.length; index++) {
  10346. if (objects[index].parent == this) {
  10347. objects[index].dispose();
  10348. }
  10349. }
  10350. }
  10351. else {
  10352. for (index = 0; index < this.getScene().meshes.length; index++) {
  10353. var obj = this.getScene().meshes[index];
  10354. if (obj.parent === this) {
  10355. obj.parent = null;
  10356. obj.computeWorldMatrix(true);
  10357. }
  10358. }
  10359. }
  10360. this._onAfterWorldMatrixUpdate = [];
  10361. this._isDisposed = true;
  10362. // Callback
  10363. if (this.onDispose) {
  10364. this.onDispose();
  10365. }
  10366. };
  10367. // Statics
  10368. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10369. AbstractMesh._BILLBOARDMODE_X = 1;
  10370. AbstractMesh._BILLBOARDMODE_Y = 2;
  10371. AbstractMesh._BILLBOARDMODE_Z = 4;
  10372. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10373. return AbstractMesh;
  10374. })(BABYLON.Node);
  10375. BABYLON.AbstractMesh = AbstractMesh;
  10376. })(BABYLON || (BABYLON = {}));
  10377. //# sourceMappingURL=babylon.abstractMesh.js.map
  10378. var BABYLON;
  10379. (function (BABYLON) {
  10380. var _InstancesBatch = (function () {
  10381. function _InstancesBatch() {
  10382. this.mustReturn = false;
  10383. this.visibleInstances = new Array();
  10384. this.renderSelf = new Array();
  10385. }
  10386. return _InstancesBatch;
  10387. })();
  10388. BABYLON._InstancesBatch = _InstancesBatch;
  10389. var Mesh = (function (_super) {
  10390. __extends(Mesh, _super);
  10391. /**
  10392. * @constructor
  10393. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10394. * @param {Scene} scene - The scene to add this mesh to.
  10395. * @param {Node} parent - The parent of this mesh, if it has one
  10396. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10397. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10398. * When false, achieved by calling a clone(), also passing False.
  10399. * This will make creation of children, recursive.
  10400. */
  10401. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10402. if (parent === void 0) { parent = null; }
  10403. _super.call(this, name, scene);
  10404. // Members
  10405. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10406. this.instances = new Array();
  10407. this._LODLevels = new Array();
  10408. this._onBeforeRenderCallbacks = new Array();
  10409. this._onAfterRenderCallbacks = new Array();
  10410. this._visibleInstances = {};
  10411. this._renderIdForInstances = new Array();
  10412. this._batchCache = new _InstancesBatch();
  10413. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10414. if (source) {
  10415. // Geometry
  10416. if (source._geometry) {
  10417. source._geometry.applyToMesh(this);
  10418. }
  10419. // Deep copy
  10420. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10421. // Material
  10422. this.material = source.material;
  10423. if (!doNotCloneChildren) {
  10424. for (var index = 0; index < scene.meshes.length; index++) {
  10425. var mesh = scene.meshes[index];
  10426. if (mesh.parent === source) {
  10427. // doNotCloneChildren is always going to be False
  10428. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10429. }
  10430. }
  10431. }
  10432. for (index = 0; index < scene.particleSystems.length; index++) {
  10433. var system = scene.particleSystems[index];
  10434. if (system.emitter === source) {
  10435. system.clone(system.name, this);
  10436. }
  10437. }
  10438. this.computeWorldMatrix(true);
  10439. }
  10440. // Parent
  10441. if (parent !== null) {
  10442. this.parent = parent;
  10443. }
  10444. }
  10445. Object.defineProperty(Mesh, "FRONTSIDE", {
  10446. get: function () {
  10447. return Mesh._FRONTSIDE;
  10448. },
  10449. enumerable: true,
  10450. configurable: true
  10451. });
  10452. Object.defineProperty(Mesh, "BACKSIDE", {
  10453. get: function () {
  10454. return Mesh._BACKSIDE;
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10460. get: function () {
  10461. return Mesh._DOUBLESIDE;
  10462. },
  10463. enumerable: true,
  10464. configurable: true
  10465. });
  10466. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10467. get: function () {
  10468. return Mesh._DEFAULTSIDE;
  10469. },
  10470. enumerable: true,
  10471. configurable: true
  10472. });
  10473. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10474. // Methods
  10475. get: function () {
  10476. return this._LODLevels.length > 0;
  10477. },
  10478. enumerable: true,
  10479. configurable: true
  10480. });
  10481. Mesh.prototype._sortLODLevels = function () {
  10482. this._LODLevels.sort(function (a, b) {
  10483. if (a.distance < b.distance) {
  10484. return 1;
  10485. }
  10486. if (a.distance > b.distance) {
  10487. return -1;
  10488. }
  10489. return 0;
  10490. });
  10491. };
  10492. /**
  10493. * Add a mesh as LOD level triggered at the given distance.
  10494. * @param {number} distance - the distance from the center of the object to show this level
  10495. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10496. * @return {BABYLON.Mesh} this mesh (for chaining)
  10497. */
  10498. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10499. if (mesh && mesh._masterMesh) {
  10500. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10501. return this;
  10502. }
  10503. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10504. this._LODLevels.push(level);
  10505. if (mesh) {
  10506. mesh._masterMesh = this;
  10507. }
  10508. this._sortLODLevels();
  10509. return this;
  10510. };
  10511. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10512. for (var index = 0; index < this._LODLevels.length; index++) {
  10513. var level = this._LODLevels[index];
  10514. if (level.distance === distance) {
  10515. return level.mesh;
  10516. }
  10517. }
  10518. return null;
  10519. };
  10520. /**
  10521. * Remove a mesh from the LOD array
  10522. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10523. * @return {BABYLON.Mesh} this mesh (for chaining)
  10524. */
  10525. Mesh.prototype.removeLODLevel = function (mesh) {
  10526. for (var index = 0; index < this._LODLevels.length; index++) {
  10527. if (this._LODLevels[index].mesh === mesh) {
  10528. this._LODLevels.splice(index, 1);
  10529. if (mesh) {
  10530. mesh._masterMesh = null;
  10531. }
  10532. }
  10533. }
  10534. this._sortLODLevels();
  10535. return this;
  10536. };
  10537. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10538. if (!this._LODLevels || this._LODLevels.length === 0) {
  10539. return this;
  10540. }
  10541. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10542. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10543. return this;
  10544. }
  10545. for (var index = 0; index < this._LODLevels.length; index++) {
  10546. var level = this._LODLevels[index];
  10547. if (level.distance < distanceToCamera) {
  10548. if (level.mesh) {
  10549. level.mesh._preActivate();
  10550. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10551. }
  10552. return level.mesh;
  10553. }
  10554. }
  10555. return this;
  10556. };
  10557. Object.defineProperty(Mesh.prototype, "geometry", {
  10558. get: function () {
  10559. return this._geometry;
  10560. },
  10561. enumerable: true,
  10562. configurable: true
  10563. });
  10564. Mesh.prototype.getTotalVertices = function () {
  10565. if (!this._geometry) {
  10566. return 0;
  10567. }
  10568. return this._geometry.getTotalVertices();
  10569. };
  10570. Mesh.prototype.getVerticesData = function (kind) {
  10571. if (!this._geometry) {
  10572. return null;
  10573. }
  10574. return this._geometry.getVerticesData(kind);
  10575. };
  10576. Mesh.prototype.getVertexBuffer = function (kind) {
  10577. if (!this._geometry) {
  10578. return undefined;
  10579. }
  10580. return this._geometry.getVertexBuffer(kind);
  10581. };
  10582. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10583. if (!this._geometry) {
  10584. if (this._delayInfo) {
  10585. return this._delayInfo.indexOf(kind) !== -1;
  10586. }
  10587. return false;
  10588. }
  10589. return this._geometry.isVerticesDataPresent(kind);
  10590. };
  10591. Mesh.prototype.getVerticesDataKinds = function () {
  10592. if (!this._geometry) {
  10593. var result = [];
  10594. if (this._delayInfo) {
  10595. for (var kind in this._delayInfo) {
  10596. result.push(kind);
  10597. }
  10598. }
  10599. return result;
  10600. }
  10601. return this._geometry.getVerticesDataKinds();
  10602. };
  10603. Mesh.prototype.getTotalIndices = function () {
  10604. if (!this._geometry) {
  10605. return 0;
  10606. }
  10607. return this._geometry.getTotalIndices();
  10608. };
  10609. Mesh.prototype.getIndices = function () {
  10610. if (!this._geometry) {
  10611. return [];
  10612. }
  10613. return this._geometry.getIndices();
  10614. };
  10615. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10616. get: function () {
  10617. return this._masterMesh !== null && this._masterMesh !== undefined;
  10618. },
  10619. enumerable: true,
  10620. configurable: true
  10621. });
  10622. Mesh.prototype.isReady = function () {
  10623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10624. return false;
  10625. }
  10626. return _super.prototype.isReady.call(this);
  10627. };
  10628. Mesh.prototype.isDisposed = function () {
  10629. return this._isDisposed;
  10630. };
  10631. // Methods
  10632. Mesh.prototype._preActivate = function () {
  10633. var sceneRenderId = this.getScene().getRenderId();
  10634. if (this._preActivateId === sceneRenderId) {
  10635. return;
  10636. }
  10637. this._preActivateId = sceneRenderId;
  10638. this._visibleInstances = null;
  10639. };
  10640. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10641. if (!this._visibleInstances) {
  10642. this._visibleInstances = {};
  10643. this._visibleInstances.defaultRenderId = renderId;
  10644. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10645. }
  10646. if (!this._visibleInstances[renderId]) {
  10647. this._visibleInstances[renderId] = new Array();
  10648. }
  10649. this._visibleInstances[renderId].push(instance);
  10650. };
  10651. Mesh.prototype.refreshBoundingInfo = function () {
  10652. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10653. if (data) {
  10654. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10655. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10656. }
  10657. if (this.subMeshes) {
  10658. for (var index = 0; index < this.subMeshes.length; index++) {
  10659. this.subMeshes[index].refreshBoundingInfo();
  10660. }
  10661. }
  10662. this._updateBoundingInfo();
  10663. };
  10664. Mesh.prototype._createGlobalSubMesh = function () {
  10665. var totalVertices = this.getTotalVertices();
  10666. if (!totalVertices || !this.getIndices()) {
  10667. return null;
  10668. }
  10669. this.releaseSubMeshes();
  10670. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10671. };
  10672. Mesh.prototype.subdivide = function (count) {
  10673. if (count < 1) {
  10674. return;
  10675. }
  10676. var totalIndices = this.getTotalIndices();
  10677. var subdivisionSize = (totalIndices / count) | 0;
  10678. var offset = 0;
  10679. while (subdivisionSize % 3 !== 0) {
  10680. subdivisionSize++;
  10681. }
  10682. this.releaseSubMeshes();
  10683. for (var index = 0; index < count; index++) {
  10684. if (offset >= totalIndices) {
  10685. break;
  10686. }
  10687. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10688. offset += subdivisionSize;
  10689. }
  10690. this.synchronizeInstances();
  10691. };
  10692. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10693. if (kind instanceof Array) {
  10694. var temp = data;
  10695. data = kind;
  10696. kind = temp;
  10697. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10698. }
  10699. if (!this._geometry) {
  10700. var vertexData = new BABYLON.VertexData();
  10701. vertexData.set(data, kind);
  10702. var scene = this.getScene();
  10703. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10704. }
  10705. else {
  10706. this._geometry.setVerticesData(kind, data, updatable, stride);
  10707. }
  10708. };
  10709. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10710. if (!this._geometry) {
  10711. return;
  10712. }
  10713. if (!makeItUnique) {
  10714. this._geometry.updateVerticesData(kind, data, updateExtends);
  10715. }
  10716. else {
  10717. this.makeGeometryUnique();
  10718. this.updateVerticesData(kind, data, updateExtends, false);
  10719. }
  10720. };
  10721. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10722. if (!this._geometry) {
  10723. return;
  10724. }
  10725. if (!makeItUnique) {
  10726. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10727. }
  10728. else {
  10729. this.makeGeometryUnique();
  10730. this.updateVerticesDataDirectly(kind, data, offset, false);
  10731. }
  10732. };
  10733. Mesh.prototype.makeGeometryUnique = function () {
  10734. if (!this._geometry) {
  10735. return;
  10736. }
  10737. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10738. geometry.applyToMesh(this);
  10739. };
  10740. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10741. if (!this._geometry) {
  10742. var vertexData = new BABYLON.VertexData();
  10743. vertexData.indices = indices;
  10744. var scene = this.getScene();
  10745. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10746. }
  10747. else {
  10748. this._geometry.setIndices(indices, totalVertices);
  10749. }
  10750. };
  10751. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10752. var engine = this.getScene().getEngine();
  10753. // Wireframe
  10754. var indexToBind;
  10755. switch (fillMode) {
  10756. case BABYLON.Material.PointFillMode:
  10757. indexToBind = null;
  10758. break;
  10759. case BABYLON.Material.WireFrameFillMode:
  10760. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10761. break;
  10762. default:
  10763. case BABYLON.Material.TriangleFillMode:
  10764. indexToBind = this._geometry.getIndexBuffer();
  10765. break;
  10766. }
  10767. // VBOs
  10768. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10769. };
  10770. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10771. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10772. return;
  10773. }
  10774. var engine = this.getScene().getEngine();
  10775. switch (fillMode) {
  10776. case BABYLON.Material.PointFillMode:
  10777. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10778. break;
  10779. case BABYLON.Material.WireFrameFillMode:
  10780. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10781. break;
  10782. default:
  10783. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10784. }
  10785. };
  10786. Mesh.prototype.registerBeforeRender = function (func) {
  10787. this._onBeforeRenderCallbacks.push(func);
  10788. };
  10789. Mesh.prototype.unregisterBeforeRender = function (func) {
  10790. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10791. if (index > -1) {
  10792. this._onBeforeRenderCallbacks.splice(index, 1);
  10793. }
  10794. };
  10795. Mesh.prototype.registerAfterRender = function (func) {
  10796. this._onAfterRenderCallbacks.push(func);
  10797. };
  10798. Mesh.prototype.unregisterAfterRender = function (func) {
  10799. var index = this._onAfterRenderCallbacks.indexOf(func);
  10800. if (index > -1) {
  10801. this._onAfterRenderCallbacks.splice(index, 1);
  10802. }
  10803. };
  10804. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10805. var scene = this.getScene();
  10806. this._batchCache.mustReturn = false;
  10807. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10808. this._batchCache.visibleInstances[subMeshId] = null;
  10809. if (this._visibleInstances) {
  10810. var currentRenderId = scene.getRenderId();
  10811. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10812. var selfRenderId = this._renderId;
  10813. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10814. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10815. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10816. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10817. }
  10818. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10819. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10820. this._batchCache.mustReturn = true;
  10821. return this._batchCache;
  10822. }
  10823. if (currentRenderId !== selfRenderId) {
  10824. this._batchCache.renderSelf[subMeshId] = false;
  10825. }
  10826. }
  10827. this._renderIdForInstances[subMeshId] = currentRenderId;
  10828. }
  10829. return this._batchCache;
  10830. };
  10831. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10832. var visibleInstances = batch.visibleInstances[subMesh._id];
  10833. var matricesCount = visibleInstances.length + 1;
  10834. var bufferSize = matricesCount * 16 * 4;
  10835. while (this._instancesBufferSize < bufferSize) {
  10836. this._instancesBufferSize *= 2;
  10837. }
  10838. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10839. if (this._worldMatricesInstancesBuffer) {
  10840. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10841. }
  10842. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10843. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10844. }
  10845. var offset = 0;
  10846. var instancesCount = 0;
  10847. var world = this.getWorldMatrix();
  10848. if (batch.renderSelf[subMesh._id]) {
  10849. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10850. offset += 16;
  10851. instancesCount++;
  10852. }
  10853. if (visibleInstances) {
  10854. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10855. var instance = visibleInstances[instanceIndex];
  10856. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10857. offset += 16;
  10858. instancesCount++;
  10859. }
  10860. }
  10861. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10862. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10863. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10864. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10865. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10866. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10867. this._draw(subMesh, fillMode, instancesCount);
  10868. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10869. };
  10870. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10871. var scene = this.getScene();
  10872. var engine = scene.getEngine();
  10873. if (hardwareInstancedRendering) {
  10874. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10875. }
  10876. else {
  10877. if (batch.renderSelf[subMesh._id]) {
  10878. // Draw
  10879. if (onBeforeDraw) {
  10880. onBeforeDraw(false, this.getWorldMatrix());
  10881. }
  10882. this._draw(subMesh, fillMode);
  10883. }
  10884. if (batch.visibleInstances[subMesh._id]) {
  10885. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10886. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10887. // World
  10888. var world = instance.getWorldMatrix();
  10889. if (onBeforeDraw) {
  10890. onBeforeDraw(true, world);
  10891. }
  10892. // Draw
  10893. this._draw(subMesh, fillMode);
  10894. }
  10895. }
  10896. }
  10897. };
  10898. Mesh.prototype.render = function (subMesh) {
  10899. var scene = this.getScene();
  10900. // Managing instances
  10901. var batch = this._getInstancesRenderList(subMesh._id);
  10902. if (batch.mustReturn) {
  10903. return;
  10904. }
  10905. // Checking geometry state
  10906. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10907. return;
  10908. }
  10909. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10910. this._onBeforeRenderCallbacks[callbackIndex](this);
  10911. }
  10912. var engine = scene.getEngine();
  10913. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10914. // Material
  10915. var effectiveMaterial = subMesh.getMaterial();
  10916. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10917. return;
  10918. }
  10919. // Outline - step 1
  10920. var savedDepthWrite = engine.getDepthWrite();
  10921. if (this.renderOutline) {
  10922. engine.setDepthWrite(false);
  10923. scene.getOutlineRenderer().render(subMesh, batch);
  10924. engine.setDepthWrite(savedDepthWrite);
  10925. }
  10926. effectiveMaterial._preBind();
  10927. var effect = effectiveMaterial.getEffect();
  10928. // Bind
  10929. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10930. this._bind(subMesh, effect, fillMode);
  10931. var world = this.getWorldMatrix();
  10932. effectiveMaterial.bind(world, this);
  10933. // Draw
  10934. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10935. if (isInstance) {
  10936. effectiveMaterial.bindOnlyWorldMatrix(world);
  10937. }
  10938. });
  10939. // Unbind
  10940. effectiveMaterial.unbind();
  10941. // Outline - step 2
  10942. if (this.renderOutline && savedDepthWrite) {
  10943. engine.setDepthWrite(true);
  10944. engine.setColorWrite(false);
  10945. scene.getOutlineRenderer().render(subMesh, batch);
  10946. engine.setColorWrite(true);
  10947. }
  10948. // Overlay
  10949. if (this.renderOverlay) {
  10950. var currentMode = engine.getAlphaMode();
  10951. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10952. scene.getOutlineRenderer().render(subMesh, batch, true);
  10953. engine.setAlphaMode(currentMode);
  10954. }
  10955. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10956. this._onAfterRenderCallbacks[callbackIndex](this);
  10957. }
  10958. };
  10959. Mesh.prototype.getEmittedParticleSystems = function () {
  10960. var results = new Array();
  10961. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10962. var particleSystem = this.getScene().particleSystems[index];
  10963. if (particleSystem.emitter === this) {
  10964. results.push(particleSystem);
  10965. }
  10966. }
  10967. return results;
  10968. };
  10969. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10970. var results = new Array();
  10971. var descendants = this.getDescendants();
  10972. descendants.push(this);
  10973. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10974. var particleSystem = this.getScene().particleSystems[index];
  10975. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10976. results.push(particleSystem);
  10977. }
  10978. }
  10979. return results;
  10980. };
  10981. Mesh.prototype.getChildren = function () {
  10982. var results = [];
  10983. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10984. var mesh = this.getScene().meshes[index];
  10985. if (mesh.parent === this) {
  10986. results.push(mesh);
  10987. }
  10988. }
  10989. return results;
  10990. };
  10991. Mesh.prototype._checkDelayState = function () {
  10992. var _this = this;
  10993. var that = this;
  10994. var scene = this.getScene();
  10995. if (this._geometry) {
  10996. this._geometry.load(scene);
  10997. }
  10998. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10999. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11000. scene._addPendingData(that);
  11001. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11002. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11003. if (data instanceof ArrayBuffer) {
  11004. _this._delayLoadingFunction(data, _this);
  11005. }
  11006. else {
  11007. _this._delayLoadingFunction(JSON.parse(data), _this);
  11008. }
  11009. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11010. scene._removePendingData(_this);
  11011. }, function () {
  11012. }, scene.database, getBinaryData);
  11013. }
  11014. };
  11015. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11016. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11017. return false;
  11018. }
  11019. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11020. return false;
  11021. }
  11022. this._checkDelayState();
  11023. return true;
  11024. };
  11025. Mesh.prototype.setMaterialByID = function (id) {
  11026. var materials = this.getScene().materials;
  11027. for (var index = 0; index < materials.length; index++) {
  11028. if (materials[index].id === id) {
  11029. this.material = materials[index];
  11030. return;
  11031. }
  11032. }
  11033. // Multi
  11034. var multiMaterials = this.getScene().multiMaterials;
  11035. for (index = 0; index < multiMaterials.length; index++) {
  11036. if (multiMaterials[index].id === id) {
  11037. this.material = multiMaterials[index];
  11038. return;
  11039. }
  11040. }
  11041. };
  11042. Mesh.prototype.getAnimatables = function () {
  11043. var results = [];
  11044. if (this.material) {
  11045. results.push(this.material);
  11046. }
  11047. if (this.skeleton) {
  11048. results.push(this.skeleton);
  11049. }
  11050. return results;
  11051. };
  11052. // Geometry
  11053. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11054. // Position
  11055. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11056. return;
  11057. }
  11058. this._resetPointsArrayCache();
  11059. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11060. var temp = [];
  11061. for (var index = 0; index < data.length; index += 3) {
  11062. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11063. }
  11064. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11065. // Normals
  11066. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11067. return;
  11068. }
  11069. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11070. for (index = 0; index < data.length; index += 3) {
  11071. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11072. }
  11073. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11074. };
  11075. // Cache
  11076. Mesh.prototype._resetPointsArrayCache = function () {
  11077. this._positions = null;
  11078. };
  11079. Mesh.prototype._generatePointsArray = function () {
  11080. if (this._positions)
  11081. return true;
  11082. this._positions = [];
  11083. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11084. if (!data) {
  11085. return false;
  11086. }
  11087. for (var index = 0; index < data.length; index += 3) {
  11088. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11089. }
  11090. return true;
  11091. };
  11092. // Clone
  11093. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11094. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11095. };
  11096. // Dispose
  11097. Mesh.prototype.dispose = function (doNotRecurse) {
  11098. if (this._geometry) {
  11099. this._geometry.releaseForMesh(this, true);
  11100. }
  11101. // Instances
  11102. if (this._worldMatricesInstancesBuffer) {
  11103. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11104. this._worldMatricesInstancesBuffer = null;
  11105. }
  11106. while (this.instances.length) {
  11107. this.instances[0].dispose();
  11108. }
  11109. _super.prototype.dispose.call(this, doNotRecurse);
  11110. };
  11111. // Geometric tools
  11112. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11113. var _this = this;
  11114. var scene = this.getScene();
  11115. var onload = function (img) {
  11116. // Getting height map data
  11117. var canvas = document.createElement("canvas");
  11118. var context = canvas.getContext("2d");
  11119. var heightMapWidth = img.width;
  11120. var heightMapHeight = img.height;
  11121. canvas.width = heightMapWidth;
  11122. canvas.height = heightMapHeight;
  11123. context.drawImage(img, 0, 0);
  11124. // Create VertexData from map data
  11125. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11126. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11127. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11128. //execute success callback, if set
  11129. if (onSuccess) {
  11130. onSuccess(_this);
  11131. }
  11132. };
  11133. BABYLON.Tools.LoadImage(url, onload, function () {
  11134. }, scene.database);
  11135. };
  11136. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11137. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11138. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11139. return;
  11140. }
  11141. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11142. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11143. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11144. var position = BABYLON.Vector3.Zero();
  11145. var normal = BABYLON.Vector3.Zero();
  11146. var uv = BABYLON.Vector2.Zero();
  11147. for (var index = 0; index < positions.length; index += 3) {
  11148. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11149. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11150. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11151. // Compute height
  11152. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11153. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11154. var pos = (u + v * heightMapWidth) * 4;
  11155. var r = buffer[pos] / 255.0;
  11156. var g = buffer[pos + 1] / 255.0;
  11157. var b = buffer[pos + 2] / 255.0;
  11158. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11159. normal.normalize();
  11160. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11161. position = position.add(normal);
  11162. position.toArray(positions, index);
  11163. }
  11164. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11165. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11166. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11167. };
  11168. Mesh.prototype.convertToFlatShadedMesh = function () {
  11169. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11170. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11171. var kinds = this.getVerticesDataKinds();
  11172. var vbs = [];
  11173. var data = [];
  11174. var newdata = [];
  11175. var updatableNormals = false;
  11176. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11177. var kind = kinds[kindIndex];
  11178. var vertexBuffer = this.getVertexBuffer(kind);
  11179. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11180. updatableNormals = vertexBuffer.isUpdatable();
  11181. kinds.splice(kindIndex, 1);
  11182. kindIndex--;
  11183. continue;
  11184. }
  11185. vbs[kind] = vertexBuffer;
  11186. data[kind] = vbs[kind].getData();
  11187. newdata[kind] = [];
  11188. }
  11189. // Save previous submeshes
  11190. var previousSubmeshes = this.subMeshes.slice(0);
  11191. var indices = this.getIndices();
  11192. var totalIndices = this.getTotalIndices();
  11193. for (var index = 0; index < totalIndices; index++) {
  11194. var vertexIndex = indices[index];
  11195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11196. kind = kinds[kindIndex];
  11197. var stride = vbs[kind].getStrideSize();
  11198. for (var offset = 0; offset < stride; offset++) {
  11199. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11200. }
  11201. }
  11202. }
  11203. // Updating faces & normal
  11204. var normals = [];
  11205. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11206. for (index = 0; index < totalIndices; index += 3) {
  11207. indices[index] = index;
  11208. indices[index + 1] = index + 1;
  11209. indices[index + 2] = index + 2;
  11210. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11211. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11212. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11213. var p1p2 = p1.subtract(p2);
  11214. var p3p2 = p3.subtract(p2);
  11215. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11216. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11217. normals.push(normal.x);
  11218. normals.push(normal.y);
  11219. normals.push(normal.z);
  11220. }
  11221. }
  11222. this.setIndices(indices);
  11223. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11224. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11225. kind = kinds[kindIndex];
  11226. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11227. }
  11228. // Updating submeshes
  11229. this.releaseSubMeshes();
  11230. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11231. var previousOne = previousSubmeshes[submeshIndex];
  11232. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11233. }
  11234. this.synchronizeInstances();
  11235. };
  11236. // Instances
  11237. Mesh.prototype.createInstance = function (name) {
  11238. return new BABYLON.InstancedMesh(name, this);
  11239. };
  11240. Mesh.prototype.synchronizeInstances = function () {
  11241. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11242. var instance = this.instances[instanceIndex];
  11243. instance._syncSubMeshes();
  11244. }
  11245. };
  11246. /**
  11247. * Simplify the mesh according to the given array of settings.
  11248. * Function will return immediately and will simplify async.
  11249. * @param settings a collection of simplification settings.
  11250. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11251. * @param type the type of simplification to run.
  11252. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11253. */
  11254. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11255. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11256. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11257. this.getScene().simplificationQueue.addTask({
  11258. settings: settings,
  11259. parallelProcessing: parallelProcessing,
  11260. mesh: this,
  11261. simplificationType: simplificationType,
  11262. successCallback: successCallback
  11263. });
  11264. };
  11265. // Statics
  11266. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11267. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11268. var ribbon = new Mesh(name, scene);
  11269. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11270. vertexData.applyToMesh(ribbon, updatable);
  11271. return ribbon;
  11272. };
  11273. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11274. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11275. var box = new Mesh(name, scene);
  11276. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11277. vertexData.applyToMesh(box, updatable);
  11278. return box;
  11279. };
  11280. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11281. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11282. var sphere = new Mesh(name, scene);
  11283. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11284. vertexData.applyToMesh(sphere, updatable);
  11285. return sphere;
  11286. };
  11287. // Cylinder and cone (Code inspired by SharpDX.org)
  11288. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11289. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11290. // subdivisions is a new parameter, we need to support old signature
  11291. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11292. if (scene !== undefined) {
  11293. updatable = scene;
  11294. }
  11295. scene = subdivisions;
  11296. subdivisions = 1;
  11297. }
  11298. var cylinder = new Mesh(name, scene);
  11299. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11300. vertexData.applyToMesh(cylinder, updatable);
  11301. return cylinder;
  11302. };
  11303. // Torus (Code from SharpDX.org)
  11304. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11305. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11306. var torus = new Mesh(name, scene);
  11307. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11308. vertexData.applyToMesh(torus, updatable);
  11309. return torus;
  11310. };
  11311. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11312. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11313. var torusKnot = new Mesh(name, scene);
  11314. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11315. vertexData.applyToMesh(torusKnot, updatable);
  11316. return torusKnot;
  11317. };
  11318. // Lines
  11319. Mesh.CreateLines = function (name, points, scene, updatable) {
  11320. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11321. var vertexData = BABYLON.VertexData.CreateLines(points);
  11322. vertexData.applyToMesh(lines, updatable);
  11323. return lines;
  11324. };
  11325. // Extrusion
  11326. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11327. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11328. scale = scale || 1;
  11329. rotation = rotation || 0;
  11330. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11331. return extruded;
  11332. };
  11333. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotateFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11334. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11335. ribbonCloseArray = ribbonCloseArray || false;
  11336. ribbonClosePath = ribbonClosePath || false;
  11337. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotateFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11338. return extrudedCustom;
  11339. };
  11340. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11341. var path3D = new BABYLON.Path3D(curve);
  11342. var tangents = path3D.getTangents();
  11343. var normals = path3D.getNormals();
  11344. var binormals = path3D.getBinormals();
  11345. var distances = path3D.getDistances();
  11346. var shapePaths = new Array();
  11347. var angle = 0;
  11348. var returnScale = function (i, distance) {
  11349. return scale;
  11350. };
  11351. var returnRotation = function (i, distance) {
  11352. return rotation;
  11353. };
  11354. var rotate = custom ? rotateFunction : returnRotation;
  11355. var scl = custom ? scaleFunction : returnScale;
  11356. for (var i = 0; i < curve.length; i++) {
  11357. var shapePath = new Array();
  11358. var angleStep = rotate(i, distances[i]);
  11359. var scaleRatio = scl(i, distances[i]);
  11360. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11361. for (var p = 0; p < shape.length; p++) {
  11362. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11363. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11364. shapePath.push(rotated);
  11365. }
  11366. shapePaths.push(shapePath);
  11367. angle += angleStep;
  11368. }
  11369. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11370. return extrudedGeneric;
  11371. };
  11372. // Plane & ground
  11373. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11374. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11375. var plane = new Mesh(name, scene);
  11376. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11377. vertexData.applyToMesh(plane, updatable);
  11378. return plane;
  11379. };
  11380. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11381. var ground = new BABYLON.GroundMesh(name, scene);
  11382. ground._setReady(false);
  11383. ground._subdivisions = subdivisions;
  11384. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11385. vertexData.applyToMesh(ground, updatable);
  11386. ground._setReady(true);
  11387. return ground;
  11388. };
  11389. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11390. var tiledGround = new Mesh(name, scene);
  11391. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11392. vertexData.applyToMesh(tiledGround, updatable);
  11393. return tiledGround;
  11394. };
  11395. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11396. var ground = new BABYLON.GroundMesh(name, scene);
  11397. ground._subdivisions = subdivisions;
  11398. ground._setReady(false);
  11399. var onload = function (img) {
  11400. // Getting height map data
  11401. var canvas = document.createElement("canvas");
  11402. var context = canvas.getContext("2d");
  11403. var heightMapWidth = img.width;
  11404. var heightMapHeight = img.height;
  11405. canvas.width = heightMapWidth;
  11406. canvas.height = heightMapHeight;
  11407. context.drawImage(img, 0, 0);
  11408. // Create VertexData from map data
  11409. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11410. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11411. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11412. vertexData.applyToMesh(ground, updatable);
  11413. ground._setReady(true);
  11414. //execute ready callback, if set
  11415. if (onReady) {
  11416. onReady(ground);
  11417. }
  11418. };
  11419. BABYLON.Tools.LoadImage(url, onload, function () {
  11420. }, scene.database);
  11421. return ground;
  11422. };
  11423. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11424. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11425. var path3D = new BABYLON.Path3D(path);
  11426. var tangents = path3D.getTangents();
  11427. var normals = path3D.getNormals();
  11428. var distances = path3D.getDistances();
  11429. var pi2 = Math.PI * 2;
  11430. var step = pi2 / tesselation;
  11431. var returnRadius = function (i, distance) { return radius; };
  11432. var radiusFunctionFinal = radiusFunction || returnRadius;
  11433. var circlePaths = [];
  11434. var circlePath;
  11435. var rad;
  11436. var normal;
  11437. var rotated;
  11438. var rotationMatrix;
  11439. for (var i = 0; i < path.length; i++) {
  11440. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11441. circlePath = []; // current circle array
  11442. normal = normals[i]; // current normal
  11443. for (var ang = 0; ang < pi2; ang += step) {
  11444. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11445. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11446. circlePath.push(rotated);
  11447. }
  11448. circlePaths.push(circlePath);
  11449. }
  11450. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11451. return tube;
  11452. };
  11453. // Tools
  11454. Mesh.MinMax = function (meshes) {
  11455. var minVector = null;
  11456. var maxVector = null;
  11457. for (var i in meshes) {
  11458. var mesh = meshes[i];
  11459. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11460. if (!minVector) {
  11461. minVector = boundingBox.minimumWorld;
  11462. maxVector = boundingBox.maximumWorld;
  11463. continue;
  11464. }
  11465. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11466. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11467. }
  11468. return {
  11469. min: minVector,
  11470. max: maxVector
  11471. };
  11472. };
  11473. Mesh.Center = function (meshesOrMinMaxVector) {
  11474. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11475. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11476. };
  11477. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11478. if (disposeSource === void 0) { disposeSource = true; }
  11479. var source = meshes[0];
  11480. var material = source.material;
  11481. var scene = source.getScene();
  11482. if (!allow32BitsIndices) {
  11483. var totalVertices = 0;
  11484. for (var index = 0; index < meshes.length; index++) {
  11485. totalVertices += meshes[index].getTotalVertices();
  11486. if (totalVertices > 65536) {
  11487. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11488. return null;
  11489. }
  11490. }
  11491. }
  11492. // Merge
  11493. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11494. vertexData.transform(source.getWorldMatrix());
  11495. for (index = 1; index < meshes.length; index++) {
  11496. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11497. otherVertexData.transform(meshes[index].getWorldMatrix());
  11498. vertexData.merge(otherVertexData);
  11499. }
  11500. var newMesh = new Mesh(source.name + "_merged", scene);
  11501. vertexData.applyToMesh(newMesh);
  11502. // Setting properties
  11503. newMesh.material = material;
  11504. newMesh.checkCollisions = source.checkCollisions;
  11505. // Cleaning
  11506. if (disposeSource) {
  11507. for (index = 0; index < meshes.length; index++) {
  11508. meshes[index].dispose();
  11509. }
  11510. }
  11511. return newMesh;
  11512. };
  11513. // Consts
  11514. Mesh._FRONTSIDE = 0;
  11515. Mesh._BACKSIDE = 1;
  11516. Mesh._DOUBLESIDE = 2;
  11517. Mesh._DEFAULTSIDE = 0;
  11518. return Mesh;
  11519. })(BABYLON.AbstractMesh);
  11520. BABYLON.Mesh = Mesh;
  11521. })(BABYLON || (BABYLON = {}));
  11522. //# sourceMappingURL=babylon.mesh.js.map
  11523. var BABYLON;
  11524. (function (BABYLON) {
  11525. var GroundMesh = (function (_super) {
  11526. __extends(GroundMesh, _super);
  11527. function GroundMesh(name, scene) {
  11528. _super.call(this, name, scene);
  11529. this.generateOctree = false;
  11530. this._worldInverse = new BABYLON.Matrix();
  11531. }
  11532. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11533. get: function () {
  11534. return this._subdivisions;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. GroundMesh.prototype.optimize = function (chunksCount) {
  11540. this.subdivide(this._subdivisions);
  11541. this.createOrUpdateSubmeshesOctree(32);
  11542. };
  11543. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11544. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11545. this.getWorldMatrix().invertToRef(this._worldInverse);
  11546. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11547. var pickInfo = this.intersects(ray);
  11548. if (pickInfo.hit) {
  11549. return pickInfo.pickedPoint.y;
  11550. }
  11551. return 0;
  11552. };
  11553. return GroundMesh;
  11554. })(BABYLON.Mesh);
  11555. BABYLON.GroundMesh = GroundMesh;
  11556. })(BABYLON || (BABYLON = {}));
  11557. //# sourceMappingURL=babylon.groundMesh.js.map
  11558. var BABYLON;
  11559. (function (BABYLON) {
  11560. /**
  11561. * Creates an instance based on a source mesh.
  11562. */
  11563. var InstancedMesh = (function (_super) {
  11564. __extends(InstancedMesh, _super);
  11565. function InstancedMesh(name, source) {
  11566. _super.call(this, name, source.getScene());
  11567. source.instances.push(this);
  11568. this._sourceMesh = source;
  11569. this.position.copyFrom(source.position);
  11570. this.rotation.copyFrom(source.rotation);
  11571. this.scaling.copyFrom(source.scaling);
  11572. if (source.rotationQuaternion) {
  11573. this.rotationQuaternion = source.rotationQuaternion.clone();
  11574. }
  11575. this.infiniteDistance = source.infiniteDistance;
  11576. this.setPivotMatrix(source.getPivotMatrix());
  11577. this.refreshBoundingInfo();
  11578. this._syncSubMeshes();
  11579. }
  11580. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11581. // Methods
  11582. get: function () {
  11583. return this._sourceMesh.receiveShadows;
  11584. },
  11585. enumerable: true,
  11586. configurable: true
  11587. });
  11588. Object.defineProperty(InstancedMesh.prototype, "material", {
  11589. get: function () {
  11590. return this._sourceMesh.material;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11596. get: function () {
  11597. return this._sourceMesh.visibility;
  11598. },
  11599. enumerable: true,
  11600. configurable: true
  11601. });
  11602. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11603. get: function () {
  11604. return this._sourceMesh.skeleton;
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. InstancedMesh.prototype.getTotalVertices = function () {
  11610. return this._sourceMesh.getTotalVertices();
  11611. };
  11612. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11613. get: function () {
  11614. return this._sourceMesh;
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. InstancedMesh.prototype.getVerticesData = function (kind) {
  11620. return this._sourceMesh.getVerticesData(kind);
  11621. };
  11622. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11623. return this._sourceMesh.isVerticesDataPresent(kind);
  11624. };
  11625. InstancedMesh.prototype.getIndices = function () {
  11626. return this._sourceMesh.getIndices();
  11627. };
  11628. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11629. get: function () {
  11630. return this._sourceMesh._positions;
  11631. },
  11632. enumerable: true,
  11633. configurable: true
  11634. });
  11635. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11636. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11637. if (data) {
  11638. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11639. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11640. }
  11641. this._updateBoundingInfo();
  11642. };
  11643. InstancedMesh.prototype._preActivate = function () {
  11644. if (this._currentLOD) {
  11645. this._currentLOD._preActivate();
  11646. }
  11647. };
  11648. InstancedMesh.prototype._activate = function (renderId) {
  11649. if (this._currentLOD) {
  11650. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11651. }
  11652. };
  11653. InstancedMesh.prototype.getLOD = function (camera) {
  11654. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11655. if (this._currentLOD === this.sourceMesh) {
  11656. return this;
  11657. }
  11658. return this._currentLOD;
  11659. };
  11660. InstancedMesh.prototype._syncSubMeshes = function () {
  11661. this.releaseSubMeshes();
  11662. if (this._sourceMesh.subMeshes) {
  11663. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11664. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11665. }
  11666. }
  11667. };
  11668. InstancedMesh.prototype._generatePointsArray = function () {
  11669. return this._sourceMesh._generatePointsArray();
  11670. };
  11671. // Clone
  11672. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11673. var result = this._sourceMesh.createInstance(name);
  11674. // Deep copy
  11675. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11676. // Bounding info
  11677. this.refreshBoundingInfo();
  11678. // Parent
  11679. if (newParent) {
  11680. result.parent = newParent;
  11681. }
  11682. if (!doNotCloneChildren) {
  11683. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11684. var mesh = this.getScene().meshes[index];
  11685. if (mesh.parent === this) {
  11686. mesh.clone(mesh.name, result);
  11687. }
  11688. }
  11689. }
  11690. result.computeWorldMatrix(true);
  11691. return result;
  11692. };
  11693. // Dispoe
  11694. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11695. // Remove from mesh
  11696. var index = this._sourceMesh.instances.indexOf(this);
  11697. this._sourceMesh.instances.splice(index, 1);
  11698. _super.prototype.dispose.call(this, doNotRecurse);
  11699. };
  11700. return InstancedMesh;
  11701. })(BABYLON.AbstractMesh);
  11702. BABYLON.InstancedMesh = InstancedMesh;
  11703. })(BABYLON || (BABYLON = {}));
  11704. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11705. (function (BABYLON) {
  11706. var SubMesh = (function () {
  11707. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11708. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11709. this.materialIndex = materialIndex;
  11710. this.verticesStart = verticesStart;
  11711. this.verticesCount = verticesCount;
  11712. this.indexStart = indexStart;
  11713. this.indexCount = indexCount;
  11714. this._renderId = 0;
  11715. this._mesh = mesh;
  11716. this._renderingMesh = renderingMesh || mesh;
  11717. mesh.subMeshes.push(this);
  11718. this._id = mesh.subMeshes.length - 1;
  11719. if (createBoundingBox) {
  11720. this.refreshBoundingInfo();
  11721. }
  11722. }
  11723. SubMesh.prototype.getBoundingInfo = function () {
  11724. return this._boundingInfo;
  11725. };
  11726. SubMesh.prototype.getMesh = function () {
  11727. return this._mesh;
  11728. };
  11729. SubMesh.prototype.getRenderingMesh = function () {
  11730. return this._renderingMesh;
  11731. };
  11732. SubMesh.prototype.getMaterial = function () {
  11733. var rootMaterial = this._renderingMesh.material;
  11734. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11735. var multiMaterial = rootMaterial;
  11736. return multiMaterial.getSubMaterial(this.materialIndex);
  11737. }
  11738. if (!rootMaterial) {
  11739. return this._mesh.getScene().defaultMaterial;
  11740. }
  11741. return rootMaterial;
  11742. };
  11743. // Methods
  11744. SubMesh.prototype.refreshBoundingInfo = function () {
  11745. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11746. if (!data) {
  11747. this._boundingInfo = this._mesh._boundingInfo;
  11748. return;
  11749. }
  11750. var indices = this._renderingMesh.getIndices();
  11751. var extend;
  11752. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11753. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11754. }
  11755. else {
  11756. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11757. }
  11758. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11759. };
  11760. SubMesh.prototype._checkCollision = function (collider) {
  11761. return this._boundingInfo._checkCollision(collider);
  11762. };
  11763. SubMesh.prototype.updateBoundingInfo = function (world) {
  11764. if (!this._boundingInfo) {
  11765. this.refreshBoundingInfo();
  11766. }
  11767. this._boundingInfo._update(world);
  11768. };
  11769. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11770. return this._boundingInfo.isInFrustum(frustumPlanes);
  11771. };
  11772. SubMesh.prototype.render = function () {
  11773. this._renderingMesh.render(this);
  11774. };
  11775. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11776. if (!this._linesIndexBuffer) {
  11777. var linesIndices = [];
  11778. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11779. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11780. }
  11781. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11782. this.linesIndexCount = linesIndices.length;
  11783. }
  11784. return this._linesIndexBuffer;
  11785. };
  11786. SubMesh.prototype.canIntersects = function (ray) {
  11787. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11788. };
  11789. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11790. var intersectInfo = null;
  11791. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11792. var p0 = positions[indices[index]];
  11793. var p1 = positions[indices[index + 1]];
  11794. var p2 = positions[indices[index + 2]];
  11795. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11796. if (currentIntersectInfo) {
  11797. if (currentIntersectInfo.distance < 0) {
  11798. continue;
  11799. }
  11800. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11801. intersectInfo = currentIntersectInfo;
  11802. intersectInfo.faceId = index / 3;
  11803. if (fastCheck) {
  11804. break;
  11805. }
  11806. }
  11807. }
  11808. }
  11809. return intersectInfo;
  11810. };
  11811. // Clone
  11812. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11813. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11814. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11815. return result;
  11816. };
  11817. // Dispose
  11818. SubMesh.prototype.dispose = function () {
  11819. if (this._linesIndexBuffer) {
  11820. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11821. this._linesIndexBuffer = null;
  11822. }
  11823. // Remove from mesh
  11824. var index = this._mesh.subMeshes.indexOf(this);
  11825. this._mesh.subMeshes.splice(index, 1);
  11826. };
  11827. // Statics
  11828. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11829. var minVertexIndex = Number.MAX_VALUE;
  11830. var maxVertexIndex = -Number.MAX_VALUE;
  11831. renderingMesh = renderingMesh || mesh;
  11832. var indices = renderingMesh.getIndices();
  11833. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11834. var vertexIndex = indices[index];
  11835. if (vertexIndex < minVertexIndex)
  11836. minVertexIndex = vertexIndex;
  11837. if (vertexIndex > maxVertexIndex)
  11838. maxVertexIndex = vertexIndex;
  11839. }
  11840. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11841. };
  11842. return SubMesh;
  11843. })();
  11844. BABYLON.SubMesh = SubMesh;
  11845. })(BABYLON || (BABYLON = {}));
  11846. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11847. (function (BABYLON) {
  11848. var BaseTexture = (function () {
  11849. function BaseTexture(scene) {
  11850. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11851. this.hasAlpha = false;
  11852. this.getAlphaFromRGB = false;
  11853. this.level = 1;
  11854. this.isCube = false;
  11855. this.isRenderTarget = false;
  11856. this.animations = new Array();
  11857. this.coordinatesIndex = 0;
  11858. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11859. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11860. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11861. this.anisotropicFilteringLevel = 4;
  11862. this._scene = scene;
  11863. this._scene.textures.push(this);
  11864. }
  11865. BaseTexture.prototype.getScene = function () {
  11866. return this._scene;
  11867. };
  11868. BaseTexture.prototype.getTextureMatrix = function () {
  11869. return null;
  11870. };
  11871. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11872. return null;
  11873. };
  11874. BaseTexture.prototype.getInternalTexture = function () {
  11875. return this._texture;
  11876. };
  11877. BaseTexture.prototype.isReady = function () {
  11878. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11879. return true;
  11880. }
  11881. if (this._texture) {
  11882. return this._texture.isReady;
  11883. }
  11884. return false;
  11885. };
  11886. BaseTexture.prototype.getSize = function () {
  11887. if (this._texture._width) {
  11888. return { width: this._texture._width, height: this._texture._height };
  11889. }
  11890. if (this._texture._size) {
  11891. return { width: this._texture._size, height: this._texture._size };
  11892. }
  11893. return { width: 0, height: 0 };
  11894. };
  11895. BaseTexture.prototype.getBaseSize = function () {
  11896. if (!this.isReady())
  11897. return { width: 0, height: 0 };
  11898. if (this._texture._size) {
  11899. return { width: this._texture._size, height: this._texture._size };
  11900. }
  11901. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11902. };
  11903. BaseTexture.prototype.scale = function (ratio) {
  11904. };
  11905. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11906. get: function () {
  11907. return false;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11913. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11914. for (var index = 0; index < texturesCache.length; index++) {
  11915. var texturesCacheEntry = texturesCache[index];
  11916. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11917. texturesCache.splice(index, 1);
  11918. return;
  11919. }
  11920. }
  11921. };
  11922. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11923. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11924. for (var index = 0; index < texturesCache.length; index++) {
  11925. var texturesCacheEntry = texturesCache[index];
  11926. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11927. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11928. texturesCacheEntry.references++;
  11929. return texturesCacheEntry;
  11930. }
  11931. }
  11932. }
  11933. return null;
  11934. };
  11935. BaseTexture.prototype.delayLoad = function () {
  11936. };
  11937. BaseTexture.prototype.releaseInternalTexture = function () {
  11938. if (!this._texture) {
  11939. return;
  11940. }
  11941. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11942. this._texture.references--;
  11943. // Final reference ?
  11944. if (this._texture.references === 0) {
  11945. var index = texturesCache.indexOf(this._texture);
  11946. texturesCache.splice(index, 1);
  11947. this._scene.getEngine()._releaseTexture(this._texture);
  11948. delete this._texture;
  11949. }
  11950. };
  11951. BaseTexture.prototype.clone = function () {
  11952. return null;
  11953. };
  11954. BaseTexture.prototype.dispose = function () {
  11955. // Remove from scene
  11956. var index = this._scene.textures.indexOf(this);
  11957. if (index >= 0) {
  11958. this._scene.textures.splice(index, 1);
  11959. }
  11960. if (this._texture === undefined) {
  11961. return;
  11962. }
  11963. this.releaseInternalTexture();
  11964. // Callback
  11965. if (this.onDispose) {
  11966. this.onDispose();
  11967. }
  11968. };
  11969. return BaseTexture;
  11970. })();
  11971. BABYLON.BaseTexture = BaseTexture;
  11972. })(BABYLON || (BABYLON = {}));
  11973. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11974. (function (BABYLON) {
  11975. var RenderingGroup = (function () {
  11976. function RenderingGroup(index, scene) {
  11977. this.index = index;
  11978. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11979. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11980. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11981. this._scene = scene;
  11982. }
  11983. RenderingGroup.prototype.render = function (customRenderFunction) {
  11984. if (customRenderFunction) {
  11985. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11986. return true;
  11987. }
  11988. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11989. return false;
  11990. }
  11991. var engine = this._scene.getEngine();
  11992. // Opaque
  11993. var subIndex;
  11994. var submesh;
  11995. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11996. submesh = this._opaqueSubMeshes.data[subIndex];
  11997. submesh.render();
  11998. }
  11999. // Alpha test
  12000. engine.setAlphaTesting(true);
  12001. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12002. submesh = this._alphaTestSubMeshes.data[subIndex];
  12003. submesh.render();
  12004. }
  12005. engine.setAlphaTesting(false);
  12006. // Transparent
  12007. if (this._transparentSubMeshes.length) {
  12008. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12009. submesh = this._transparentSubMeshes.data[subIndex];
  12010. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12011. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12012. }
  12013. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12014. sortedArray.sort(function (a, b) {
  12015. // Alpha index first
  12016. if (a._alphaIndex > b._alphaIndex) {
  12017. return 1;
  12018. }
  12019. if (a._alphaIndex < b._alphaIndex) {
  12020. return -1;
  12021. }
  12022. // Then distance to camera
  12023. if (a._distanceToCamera < b._distanceToCamera) {
  12024. return 1;
  12025. }
  12026. if (a._distanceToCamera > b._distanceToCamera) {
  12027. return -1;
  12028. }
  12029. return 0;
  12030. });
  12031. // Rendering
  12032. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12033. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12034. submesh = sortedArray[subIndex];
  12035. submesh.render();
  12036. }
  12037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12038. }
  12039. return true;
  12040. };
  12041. RenderingGroup.prototype.prepare = function () {
  12042. this._opaqueSubMeshes.reset();
  12043. this._transparentSubMeshes.reset();
  12044. this._alphaTestSubMeshes.reset();
  12045. };
  12046. RenderingGroup.prototype.dispatch = function (subMesh) {
  12047. var material = subMesh.getMaterial();
  12048. var mesh = subMesh.getMesh();
  12049. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12050. this._transparentSubMeshes.push(subMesh);
  12051. }
  12052. else if (material.needAlphaTesting()) {
  12053. this._alphaTestSubMeshes.push(subMesh);
  12054. }
  12055. else {
  12056. this._opaqueSubMeshes.push(subMesh); // Opaque
  12057. }
  12058. };
  12059. return RenderingGroup;
  12060. })();
  12061. BABYLON.RenderingGroup = RenderingGroup;
  12062. })(BABYLON || (BABYLON = {}));
  12063. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12064. (function (BABYLON) {
  12065. var RenderingManager = (function () {
  12066. function RenderingManager(scene) {
  12067. this._renderingGroups = new Array();
  12068. this._scene = scene;
  12069. }
  12070. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12071. if (this._scene._activeParticleSystems.length === 0) {
  12072. return;
  12073. }
  12074. // Particles
  12075. var beforeParticlesDate = BABYLON.Tools.Now;
  12076. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12077. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12078. if (particleSystem.renderingGroupId !== index) {
  12079. continue;
  12080. }
  12081. this._clearDepthBuffer();
  12082. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12083. this._scene._activeParticles += particleSystem.render();
  12084. }
  12085. }
  12086. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12087. };
  12088. RenderingManager.prototype._renderSprites = function (index) {
  12089. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12090. return;
  12091. }
  12092. // Sprites
  12093. var beforeSpritessDate = BABYLON.Tools.Now;
  12094. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12095. var spriteManager = this._scene.spriteManagers[id];
  12096. if (spriteManager.renderingGroupId === index) {
  12097. this._clearDepthBuffer();
  12098. spriteManager.render();
  12099. }
  12100. }
  12101. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12102. };
  12103. RenderingManager.prototype._clearDepthBuffer = function () {
  12104. if (this._depthBufferAlreadyCleaned) {
  12105. return;
  12106. }
  12107. this._scene.getEngine().clear(0, false, true);
  12108. this._depthBufferAlreadyCleaned = true;
  12109. };
  12110. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12111. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12112. this._depthBufferAlreadyCleaned = false;
  12113. var renderingGroup = this._renderingGroups[index];
  12114. var needToStepBack = false;
  12115. if (renderingGroup) {
  12116. this._clearDepthBuffer();
  12117. if (!renderingGroup.render(customRenderFunction)) {
  12118. this._renderingGroups.splice(index, 1);
  12119. needToStepBack = true;
  12120. }
  12121. }
  12122. if (renderSprites) {
  12123. this._renderSprites(index);
  12124. }
  12125. if (renderParticles) {
  12126. this._renderParticles(index, activeMeshes);
  12127. }
  12128. if (needToStepBack) {
  12129. index--;
  12130. }
  12131. }
  12132. };
  12133. RenderingManager.prototype.reset = function () {
  12134. for (var index in this._renderingGroups) {
  12135. var renderingGroup = this._renderingGroups[index];
  12136. renderingGroup.prepare();
  12137. }
  12138. };
  12139. RenderingManager.prototype.dispatch = function (subMesh) {
  12140. var mesh = subMesh.getMesh();
  12141. var renderingGroupId = mesh.renderingGroupId || 0;
  12142. if (!this._renderingGroups[renderingGroupId]) {
  12143. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12144. }
  12145. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12146. };
  12147. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12148. return RenderingManager;
  12149. })();
  12150. BABYLON.RenderingManager = RenderingManager;
  12151. })(BABYLON || (BABYLON = {}));
  12152. //# sourceMappingURL=babylon.renderingManager.js.map
  12153. var BABYLON;
  12154. (function (BABYLON) {
  12155. var Texture = (function (_super) {
  12156. __extends(Texture, _super);
  12157. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12158. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12159. if (onLoad === void 0) { onLoad = null; }
  12160. if (onError === void 0) { onError = null; }
  12161. if (buffer === void 0) { buffer = null; }
  12162. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12163. _super.call(this, scene);
  12164. this.uOffset = 0;
  12165. this.vOffset = 0;
  12166. this.uScale = 1.0;
  12167. this.vScale = 1.0;
  12168. this.uAng = 0;
  12169. this.vAng = 0;
  12170. this.wAng = 0;
  12171. this.name = url;
  12172. this.url = url;
  12173. this._noMipmap = noMipmap;
  12174. this._invertY = invertY;
  12175. this._samplingMode = samplingMode;
  12176. this._buffer = buffer;
  12177. this._deleteBuffer = deleteBuffer;
  12178. if (!url) {
  12179. return;
  12180. }
  12181. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12182. if (!this._texture) {
  12183. if (!scene.useDelayedTextureLoading) {
  12184. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12185. if (deleteBuffer) {
  12186. delete this._buffer;
  12187. }
  12188. }
  12189. else {
  12190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12191. }
  12192. }
  12193. }
  12194. Texture.prototype.delayLoad = function () {
  12195. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12196. return;
  12197. }
  12198. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12199. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12200. if (!this._texture) {
  12201. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12202. if (this._deleteBuffer) {
  12203. delete this._buffer;
  12204. }
  12205. }
  12206. };
  12207. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12208. x -= this.uOffset + 0.5;
  12209. y -= this.vOffset + 0.5;
  12210. z -= 0.5;
  12211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12212. t.x *= this.uScale;
  12213. t.y *= this.vScale;
  12214. t.x += 0.5;
  12215. t.y += 0.5;
  12216. t.z += 0.5;
  12217. };
  12218. Texture.prototype.getTextureMatrix = function () {
  12219. 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) {
  12220. return this._cachedTextureMatrix;
  12221. }
  12222. this._cachedUOffset = this.uOffset;
  12223. this._cachedVOffset = this.vOffset;
  12224. this._cachedUScale = this.uScale;
  12225. this._cachedVScale = this.vScale;
  12226. this._cachedUAng = this.uAng;
  12227. this._cachedVAng = this.vAng;
  12228. this._cachedWAng = this.wAng;
  12229. if (!this._cachedTextureMatrix) {
  12230. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12231. this._rowGenerationMatrix = new BABYLON.Matrix();
  12232. this._t0 = BABYLON.Vector3.Zero();
  12233. this._t1 = BABYLON.Vector3.Zero();
  12234. this._t2 = BABYLON.Vector3.Zero();
  12235. }
  12236. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12237. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12238. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12239. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12240. this._t1.subtractInPlace(this._t0);
  12241. this._t2.subtractInPlace(this._t0);
  12242. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12243. this._cachedTextureMatrix.m[0] = this._t1.x;
  12244. this._cachedTextureMatrix.m[1] = this._t1.y;
  12245. this._cachedTextureMatrix.m[2] = this._t1.z;
  12246. this._cachedTextureMatrix.m[4] = this._t2.x;
  12247. this._cachedTextureMatrix.m[5] = this._t2.y;
  12248. this._cachedTextureMatrix.m[6] = this._t2.z;
  12249. this._cachedTextureMatrix.m[8] = this._t0.x;
  12250. this._cachedTextureMatrix.m[9] = this._t0.y;
  12251. this._cachedTextureMatrix.m[10] = this._t0.z;
  12252. return this._cachedTextureMatrix;
  12253. };
  12254. Texture.prototype.getReflectionTextureMatrix = function () {
  12255. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12256. return this._cachedTextureMatrix;
  12257. }
  12258. if (!this._cachedTextureMatrix) {
  12259. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12260. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12261. }
  12262. this._cachedCoordinatesMode = this.coordinatesMode;
  12263. switch (this.coordinatesMode) {
  12264. case BABYLON.Texture.SPHERICAL_MODE:
  12265. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12266. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12267. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12268. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12269. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12270. break;
  12271. case BABYLON.Texture.PLANAR_MODE:
  12272. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12273. this._cachedTextureMatrix[0] = this.uScale;
  12274. this._cachedTextureMatrix[5] = this.vScale;
  12275. this._cachedTextureMatrix[12] = this.uOffset;
  12276. this._cachedTextureMatrix[13] = this.vOffset;
  12277. break;
  12278. case BABYLON.Texture.PROJECTION_MODE:
  12279. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12280. this._projectionModeMatrix.m[0] = 0.5;
  12281. this._projectionModeMatrix.m[5] = -0.5;
  12282. this._projectionModeMatrix.m[10] = 0.0;
  12283. this._projectionModeMatrix.m[12] = 0.5;
  12284. this._projectionModeMatrix.m[13] = 0.5;
  12285. this._projectionModeMatrix.m[14] = 1.0;
  12286. this._projectionModeMatrix.m[15] = 1.0;
  12287. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12288. break;
  12289. default:
  12290. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12291. break;
  12292. }
  12293. return this._cachedTextureMatrix;
  12294. };
  12295. Texture.prototype.clone = function () {
  12296. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12297. // Base texture
  12298. newTexture.hasAlpha = this.hasAlpha;
  12299. newTexture.level = this.level;
  12300. newTexture.wrapU = this.wrapU;
  12301. newTexture.wrapV = this.wrapV;
  12302. newTexture.coordinatesIndex = this.coordinatesIndex;
  12303. newTexture.coordinatesMode = this.coordinatesMode;
  12304. // Texture
  12305. newTexture.uOffset = this.uOffset;
  12306. newTexture.vOffset = this.vOffset;
  12307. newTexture.uScale = this.uScale;
  12308. newTexture.vScale = this.vScale;
  12309. newTexture.uAng = this.uAng;
  12310. newTexture.vAng = this.vAng;
  12311. newTexture.wAng = this.wAng;
  12312. return newTexture;
  12313. };
  12314. // Statics
  12315. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12316. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12317. if (onLoad === void 0) { onLoad = null; }
  12318. if (onError === void 0) { onError = null; }
  12319. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12320. };
  12321. // Constants
  12322. Texture.NEAREST_SAMPLINGMODE = 1;
  12323. Texture.BILINEAR_SAMPLINGMODE = 2;
  12324. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12325. Texture.EXPLICIT_MODE = 0;
  12326. Texture.SPHERICAL_MODE = 1;
  12327. Texture.PLANAR_MODE = 2;
  12328. Texture.CUBIC_MODE = 3;
  12329. Texture.PROJECTION_MODE = 4;
  12330. Texture.SKYBOX_MODE = 5;
  12331. Texture.CLAMP_ADDRESSMODE = 0;
  12332. Texture.WRAP_ADDRESSMODE = 1;
  12333. Texture.MIRROR_ADDRESSMODE = 2;
  12334. return Texture;
  12335. })(BABYLON.BaseTexture);
  12336. BABYLON.Texture = Texture;
  12337. })(BABYLON || (BABYLON = {}));
  12338. //# sourceMappingURL=babylon.texture.js.map
  12339. var BABYLON;
  12340. (function (BABYLON) {
  12341. var CubeTexture = (function (_super) {
  12342. __extends(CubeTexture, _super);
  12343. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12344. _super.call(this, scene);
  12345. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12346. this.name = rootUrl;
  12347. this.url = rootUrl;
  12348. this._noMipmap = noMipmap;
  12349. this.hasAlpha = false;
  12350. this._texture = this._getFromCache(rootUrl, noMipmap);
  12351. if (!extensions) {
  12352. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12353. }
  12354. this._extensions = extensions;
  12355. if (!this._texture) {
  12356. if (!scene.useDelayedTextureLoading) {
  12357. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12358. }
  12359. else {
  12360. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12361. }
  12362. }
  12363. this.isCube = true;
  12364. this._textureMatrix = BABYLON.Matrix.Identity();
  12365. }
  12366. CubeTexture.prototype.clone = function () {
  12367. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12368. // Base texture
  12369. newTexture.level = this.level;
  12370. newTexture.wrapU = this.wrapU;
  12371. newTexture.wrapV = this.wrapV;
  12372. newTexture.coordinatesIndex = this.coordinatesIndex;
  12373. newTexture.coordinatesMode = this.coordinatesMode;
  12374. return newTexture;
  12375. };
  12376. // Methods
  12377. CubeTexture.prototype.delayLoad = function () {
  12378. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12379. return;
  12380. }
  12381. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12382. this._texture = this._getFromCache(this.url, this._noMipmap);
  12383. if (!this._texture) {
  12384. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12385. }
  12386. };
  12387. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12388. return this._textureMatrix;
  12389. };
  12390. return CubeTexture;
  12391. })(BABYLON.BaseTexture);
  12392. BABYLON.CubeTexture = CubeTexture;
  12393. })(BABYLON || (BABYLON = {}));
  12394. //# sourceMappingURL=babylon.cubeTexture.js.map
  12395. var BABYLON;
  12396. (function (BABYLON) {
  12397. var RenderTargetTexture = (function (_super) {
  12398. __extends(RenderTargetTexture, _super);
  12399. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12400. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12401. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12402. _super.call(this, null, scene, !generateMipMaps);
  12403. this.renderList = new Array();
  12404. this.renderParticles = true;
  12405. this.renderSprites = false;
  12406. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12407. this._currentRefreshId = -1;
  12408. this._refreshRate = 1;
  12409. this.name = name;
  12410. this.isRenderTarget = true;
  12411. this._size = size;
  12412. this._generateMipMaps = generateMipMaps;
  12413. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12414. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12415. // Rendering groups
  12416. this._renderingManager = new BABYLON.RenderingManager(scene);
  12417. }
  12418. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12419. this._currentRefreshId = -1;
  12420. };
  12421. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12422. get: function () {
  12423. return this._refreshRate;
  12424. },
  12425. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12426. set: function (value) {
  12427. this._refreshRate = value;
  12428. this.resetRefreshCounter();
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. RenderTargetTexture.prototype._shouldRender = function () {
  12434. if (this._currentRefreshId === -1) {
  12435. this._currentRefreshId = 1;
  12436. return true;
  12437. }
  12438. if (this.refreshRate === this._currentRefreshId) {
  12439. this._currentRefreshId = 1;
  12440. return true;
  12441. }
  12442. this._currentRefreshId++;
  12443. return false;
  12444. };
  12445. RenderTargetTexture.prototype.isReady = function () {
  12446. if (!this.getScene().renderTargetsEnabled) {
  12447. return false;
  12448. }
  12449. return _super.prototype.isReady.call(this);
  12450. };
  12451. RenderTargetTexture.prototype.getRenderSize = function () {
  12452. return this._size;
  12453. };
  12454. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12455. get: function () {
  12456. return true;
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. RenderTargetTexture.prototype.scale = function (ratio) {
  12462. var newSize = this._size * ratio;
  12463. this.resize(newSize, this._generateMipMaps);
  12464. };
  12465. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12466. this.releaseInternalTexture();
  12467. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12468. };
  12469. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12470. var scene = this.getScene();
  12471. var engine = scene.getEngine();
  12472. if (this._waitingRenderList) {
  12473. this.renderList = [];
  12474. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12475. var id = this._waitingRenderList[index];
  12476. this.renderList.push(scene.getMeshByID(id));
  12477. }
  12478. delete this._waitingRenderList;
  12479. }
  12480. if (this.renderList && this.renderList.length === 0) {
  12481. return;
  12482. }
  12483. // Bind
  12484. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12485. engine.bindFramebuffer(this._texture);
  12486. }
  12487. this._renderingManager.reset();
  12488. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12489. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12490. var mesh = currentRenderList[meshIndex];
  12491. if (mesh) {
  12492. if (!mesh.isReady()) {
  12493. // Reset _currentRefreshId
  12494. this.resetRefreshCounter();
  12495. continue;
  12496. }
  12497. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12498. mesh._activate(scene.getRenderId());
  12499. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12500. var subMesh = mesh.subMeshes[subIndex];
  12501. scene._activeVertices += subMesh.indexCount;
  12502. this._renderingManager.dispatch(subMesh);
  12503. }
  12504. }
  12505. }
  12506. }
  12507. if (this.onBeforeRender) {
  12508. this.onBeforeRender();
  12509. }
  12510. // Clear
  12511. if (this.onClear) {
  12512. this.onClear(engine);
  12513. }
  12514. else {
  12515. engine.clear(scene.clearColor, true, true);
  12516. }
  12517. if (!this._doNotChangeAspectRatio) {
  12518. scene.updateTransformMatrix(true);
  12519. }
  12520. // Render
  12521. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12522. if (useCameraPostProcess) {
  12523. scene.postProcessManager._finalizeFrame(false, this._texture);
  12524. }
  12525. if (!this._doNotChangeAspectRatio) {
  12526. scene.updateTransformMatrix(true);
  12527. }
  12528. if (this.onAfterRender) {
  12529. this.onAfterRender();
  12530. }
  12531. // Dump ?
  12532. if (dumpForDebug) {
  12533. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12534. }
  12535. // Unbind
  12536. engine.unBindFramebuffer(this._texture);
  12537. if (this.onAfterUnbind) {
  12538. this.onAfterUnbind();
  12539. }
  12540. };
  12541. RenderTargetTexture.prototype.clone = function () {
  12542. var textureSize = this.getSize();
  12543. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12544. // Base texture
  12545. newTexture.hasAlpha = this.hasAlpha;
  12546. newTexture.level = this.level;
  12547. // RenderTarget Texture
  12548. newTexture.coordinatesMode = this.coordinatesMode;
  12549. newTexture.renderList = this.renderList.slice(0);
  12550. return newTexture;
  12551. };
  12552. return RenderTargetTexture;
  12553. })(BABYLON.Texture);
  12554. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12555. })(BABYLON || (BABYLON = {}));
  12556. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12557. var BABYLON;
  12558. (function (BABYLON) {
  12559. var ProceduralTexture = (function (_super) {
  12560. __extends(ProceduralTexture, _super);
  12561. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12562. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12563. _super.call(this, null, scene, !generateMipMaps);
  12564. this._currentRefreshId = -1;
  12565. this._refreshRate = 1;
  12566. this._vertexDeclaration = [2];
  12567. this._vertexStrideSize = 2 * 4;
  12568. this._uniforms = new Array();
  12569. this._samplers = new Array();
  12570. this._textures = new Array();
  12571. this._floats = new Array();
  12572. this._floatsArrays = {};
  12573. this._colors3 = new Array();
  12574. this._colors4 = new Array();
  12575. this._vectors2 = new Array();
  12576. this._vectors3 = new Array();
  12577. this._matrices = new Array();
  12578. this._fallbackTextureUsed = false;
  12579. scene._proceduralTextures.push(this);
  12580. this.name = name;
  12581. this.isRenderTarget = true;
  12582. this._size = size;
  12583. this._generateMipMaps = generateMipMaps;
  12584. this.setFragment(fragment);
  12585. this._fallbackTexture = fallbackTexture;
  12586. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12587. // VBO
  12588. var vertices = [];
  12589. vertices.push(1, 1);
  12590. vertices.push(-1, 1);
  12591. vertices.push(-1, -1);
  12592. vertices.push(1, -1);
  12593. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12594. // Indices
  12595. var indices = [];
  12596. indices.push(0);
  12597. indices.push(1);
  12598. indices.push(2);
  12599. indices.push(0);
  12600. indices.push(2);
  12601. indices.push(3);
  12602. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12603. }
  12604. ProceduralTexture.prototype.reset = function () {
  12605. if (this._effect === undefined) {
  12606. return;
  12607. }
  12608. var engine = this.getScene().getEngine();
  12609. engine._releaseEffect(this._effect);
  12610. };
  12611. ProceduralTexture.prototype.isReady = function () {
  12612. var _this = this;
  12613. var engine = this.getScene().getEngine();
  12614. var shaders;
  12615. if (!this._fragment) {
  12616. return false;
  12617. }
  12618. if (this._fallbackTextureUsed) {
  12619. return true;
  12620. }
  12621. if (this._fragment.fragmentElement !== undefined) {
  12622. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12623. }
  12624. else {
  12625. shaders = { vertex: "procedural", fragment: this._fragment };
  12626. }
  12627. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12628. _this.releaseInternalTexture();
  12629. if (_this._fallbackTexture) {
  12630. _this._texture = _this._fallbackTexture._texture;
  12631. _this._texture.references++;
  12632. }
  12633. _this._fallbackTextureUsed = true;
  12634. });
  12635. return this._effect.isReady();
  12636. };
  12637. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12638. this._currentRefreshId = -1;
  12639. };
  12640. ProceduralTexture.prototype.setFragment = function (fragment) {
  12641. this._fragment = fragment;
  12642. };
  12643. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12644. get: function () {
  12645. return this._refreshRate;
  12646. },
  12647. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12648. set: function (value) {
  12649. this._refreshRate = value;
  12650. this.resetRefreshCounter();
  12651. },
  12652. enumerable: true,
  12653. configurable: true
  12654. });
  12655. ProceduralTexture.prototype._shouldRender = function () {
  12656. if (!this.isReady() || !this._texture) {
  12657. return false;
  12658. }
  12659. if (this._fallbackTextureUsed) {
  12660. return false;
  12661. }
  12662. if (this._currentRefreshId === -1) {
  12663. this._currentRefreshId = 1;
  12664. return true;
  12665. }
  12666. if (this.refreshRate === this._currentRefreshId) {
  12667. this._currentRefreshId = 1;
  12668. return true;
  12669. }
  12670. this._currentRefreshId++;
  12671. return false;
  12672. };
  12673. ProceduralTexture.prototype.getRenderSize = function () {
  12674. return this._size;
  12675. };
  12676. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12677. if (this._fallbackTextureUsed) {
  12678. return;
  12679. }
  12680. this.releaseInternalTexture();
  12681. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12682. };
  12683. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12684. if (this._uniforms.indexOf(uniformName) === -1) {
  12685. this._uniforms.push(uniformName);
  12686. }
  12687. };
  12688. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12689. if (this._samplers.indexOf(name) === -1) {
  12690. this._samplers.push(name);
  12691. }
  12692. this._textures[name] = texture;
  12693. return this;
  12694. };
  12695. ProceduralTexture.prototype.setFloat = function (name, value) {
  12696. this._checkUniform(name);
  12697. this._floats[name] = value;
  12698. return this;
  12699. };
  12700. ProceduralTexture.prototype.setFloats = function (name, value) {
  12701. this._checkUniform(name);
  12702. this._floatsArrays[name] = value;
  12703. return this;
  12704. };
  12705. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12706. this._checkUniform(name);
  12707. this._colors3[name] = value;
  12708. return this;
  12709. };
  12710. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12711. this._checkUniform(name);
  12712. this._colors4[name] = value;
  12713. return this;
  12714. };
  12715. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12716. this._checkUniform(name);
  12717. this._vectors2[name] = value;
  12718. return this;
  12719. };
  12720. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12721. this._checkUniform(name);
  12722. this._vectors3[name] = value;
  12723. return this;
  12724. };
  12725. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12726. this._checkUniform(name);
  12727. this._matrices[name] = value;
  12728. return this;
  12729. };
  12730. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12731. var scene = this.getScene();
  12732. var engine = scene.getEngine();
  12733. engine.bindFramebuffer(this._texture);
  12734. // Clear
  12735. engine.clear(scene.clearColor, true, true);
  12736. // Render
  12737. engine.enableEffect(this._effect);
  12738. engine.setState(false);
  12739. for (var name in this._textures) {
  12740. this._effect.setTexture(name, this._textures[name]);
  12741. }
  12742. for (name in this._floats) {
  12743. this._effect.setFloat(name, this._floats[name]);
  12744. }
  12745. for (name in this._floatsArrays) {
  12746. this._effect.setArray(name, this._floatsArrays[name]);
  12747. }
  12748. for (name in this._colors3) {
  12749. this._effect.setColor3(name, this._colors3[name]);
  12750. }
  12751. for (name in this._colors4) {
  12752. var color = this._colors4[name];
  12753. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12754. }
  12755. for (name in this._vectors2) {
  12756. this._effect.setVector2(name, this._vectors2[name]);
  12757. }
  12758. for (name in this._vectors3) {
  12759. this._effect.setVector3(name, this._vectors3[name]);
  12760. }
  12761. for (name in this._matrices) {
  12762. this._effect.setMatrix(name, this._matrices[name]);
  12763. }
  12764. // VBOs
  12765. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12766. // Draw order
  12767. engine.draw(true, 0, 6);
  12768. // Unbind
  12769. engine.unBindFramebuffer(this._texture);
  12770. };
  12771. ProceduralTexture.prototype.clone = function () {
  12772. var textureSize = this.getSize();
  12773. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12774. // Base texture
  12775. newTexture.hasAlpha = this.hasAlpha;
  12776. newTexture.level = this.level;
  12777. // RenderTarget Texture
  12778. newTexture.coordinatesMode = this.coordinatesMode;
  12779. return newTexture;
  12780. };
  12781. ProceduralTexture.prototype.dispose = function () {
  12782. var index = this.getScene()._proceduralTextures.indexOf(this);
  12783. if (index >= 0) {
  12784. this.getScene()._proceduralTextures.splice(index, 1);
  12785. }
  12786. _super.prototype.dispose.call(this);
  12787. };
  12788. return ProceduralTexture;
  12789. })(BABYLON.Texture);
  12790. BABYLON.ProceduralTexture = ProceduralTexture;
  12791. })(BABYLON || (BABYLON = {}));
  12792. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12793. var BABYLON;
  12794. (function (BABYLON) {
  12795. var WoodProceduralTexture = (function (_super) {
  12796. __extends(WoodProceduralTexture, _super);
  12797. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12798. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12799. this._ampScale = 100.0;
  12800. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12801. this.updateShaderUniforms();
  12802. this.refreshRate = 0;
  12803. }
  12804. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12805. this.setFloat("ampScale", this._ampScale);
  12806. this.setColor3("woodColor", this._woodColor);
  12807. };
  12808. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12809. get: function () {
  12810. return this._ampScale;
  12811. },
  12812. set: function (value) {
  12813. this._ampScale = value;
  12814. this.updateShaderUniforms();
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12820. get: function () {
  12821. return this._woodColor;
  12822. },
  12823. set: function (value) {
  12824. this._woodColor = value;
  12825. this.updateShaderUniforms();
  12826. },
  12827. enumerable: true,
  12828. configurable: true
  12829. });
  12830. return WoodProceduralTexture;
  12831. })(BABYLON.ProceduralTexture);
  12832. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12833. var FireProceduralTexture = (function (_super) {
  12834. __extends(FireProceduralTexture, _super);
  12835. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12836. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12837. this._time = 0.0;
  12838. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12839. this._shift = 1.6;
  12840. this._autoGenerateTime = true;
  12841. this._alphaThreshold = 0.5;
  12842. this._fireColors = FireProceduralTexture.RedFireColors;
  12843. this.updateShaderUniforms();
  12844. this.refreshRate = 1;
  12845. }
  12846. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12847. this.setFloat("time", this._time);
  12848. this.setVector2("speed", this._speed);
  12849. this.setFloat("shift", this._shift);
  12850. this.setColor3("c1", this._fireColors[0]);
  12851. this.setColor3("c2", this._fireColors[1]);
  12852. this.setColor3("c3", this._fireColors[2]);
  12853. this.setColor3("c4", this._fireColors[3]);
  12854. this.setColor3("c5", this._fireColors[4]);
  12855. this.setColor3("c6", this._fireColors[5]);
  12856. this.setFloat("alphaThreshold", this._alphaThreshold);
  12857. };
  12858. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12859. if (this._autoGenerateTime) {
  12860. this._time += this.getScene().getAnimationRatio() * 0.03;
  12861. this.updateShaderUniforms();
  12862. }
  12863. _super.prototype.render.call(this, useCameraPostProcess);
  12864. };
  12865. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12866. get: function () {
  12867. return [
  12868. new BABYLON.Color3(0.5, 0.0, 1.0),
  12869. new BABYLON.Color3(0.9, 0.0, 1.0),
  12870. new BABYLON.Color3(0.2, 0.0, 1.0),
  12871. new BABYLON.Color3(1.0, 0.9, 1.0),
  12872. new BABYLON.Color3(0.1, 0.1, 1.0),
  12873. new BABYLON.Color3(0.9, 0.9, 1.0)
  12874. ];
  12875. },
  12876. enumerable: true,
  12877. configurable: true
  12878. });
  12879. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12880. get: function () {
  12881. return [
  12882. new BABYLON.Color3(0.5, 1.0, 0.0),
  12883. new BABYLON.Color3(0.5, 1.0, 0.0),
  12884. new BABYLON.Color3(0.3, 0.4, 0.0),
  12885. new BABYLON.Color3(0.5, 1.0, 0.0),
  12886. new BABYLON.Color3(0.2, 0.0, 0.0),
  12887. new BABYLON.Color3(0.5, 1.0, 0.0)
  12888. ];
  12889. },
  12890. enumerable: true,
  12891. configurable: true
  12892. });
  12893. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12894. get: function () {
  12895. return [
  12896. new BABYLON.Color3(0.5, 0.0, 0.1),
  12897. new BABYLON.Color3(0.9, 0.0, 0.0),
  12898. new BABYLON.Color3(0.2, 0.0, 0.0),
  12899. new BABYLON.Color3(1.0, 0.9, 0.0),
  12900. new BABYLON.Color3(0.1, 0.1, 0.1),
  12901. new BABYLON.Color3(0.9, 0.9, 0.9)
  12902. ];
  12903. },
  12904. enumerable: true,
  12905. configurable: true
  12906. });
  12907. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12908. get: function () {
  12909. return [
  12910. new BABYLON.Color3(0.1, 0.0, 0.5),
  12911. new BABYLON.Color3(0.0, 0.0, 0.5),
  12912. new BABYLON.Color3(0.1, 0.0, 0.2),
  12913. new BABYLON.Color3(0.0, 0.0, 1.0),
  12914. new BABYLON.Color3(0.1, 0.2, 0.3),
  12915. new BABYLON.Color3(0.0, 0.2, 0.9)
  12916. ];
  12917. },
  12918. enumerable: true,
  12919. configurable: true
  12920. });
  12921. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12922. get: function () {
  12923. return this._fireColors;
  12924. },
  12925. set: function (value) {
  12926. this._fireColors = value;
  12927. this.updateShaderUniforms();
  12928. },
  12929. enumerable: true,
  12930. configurable: true
  12931. });
  12932. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12933. get: function () {
  12934. return this._time;
  12935. },
  12936. set: function (value) {
  12937. this._time = value;
  12938. this.updateShaderUniforms();
  12939. },
  12940. enumerable: true,
  12941. configurable: true
  12942. });
  12943. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12944. get: function () {
  12945. return this._speed;
  12946. },
  12947. set: function (value) {
  12948. this._speed = value;
  12949. this.updateShaderUniforms();
  12950. },
  12951. enumerable: true,
  12952. configurable: true
  12953. });
  12954. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12955. get: function () {
  12956. return this._shift;
  12957. },
  12958. set: function (value) {
  12959. this._shift = value;
  12960. this.updateShaderUniforms();
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12966. get: function () {
  12967. return this._alphaThreshold;
  12968. },
  12969. set: function (value) {
  12970. this._alphaThreshold = value;
  12971. this.updateShaderUniforms();
  12972. },
  12973. enumerable: true,
  12974. configurable: true
  12975. });
  12976. return FireProceduralTexture;
  12977. })(BABYLON.ProceduralTexture);
  12978. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12979. var CloudProceduralTexture = (function (_super) {
  12980. __extends(CloudProceduralTexture, _super);
  12981. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12982. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12983. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12984. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12985. this.updateShaderUniforms();
  12986. this.refreshRate = 0;
  12987. }
  12988. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12989. this.setColor3("skyColor", this._skyColor);
  12990. this.setColor3("cloudColor", this._cloudColor);
  12991. };
  12992. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12993. get: function () {
  12994. return this._skyColor;
  12995. },
  12996. set: function (value) {
  12997. this._skyColor = value;
  12998. this.updateShaderUniforms();
  12999. },
  13000. enumerable: true,
  13001. configurable: true
  13002. });
  13003. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13004. get: function () {
  13005. return this._cloudColor;
  13006. },
  13007. set: function (value) {
  13008. this._cloudColor = value;
  13009. this.updateShaderUniforms();
  13010. },
  13011. enumerable: true,
  13012. configurable: true
  13013. });
  13014. return CloudProceduralTexture;
  13015. })(BABYLON.ProceduralTexture);
  13016. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13017. var GrassProceduralTexture = (function (_super) {
  13018. __extends(GrassProceduralTexture, _super);
  13019. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13020. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13021. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13022. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13023. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13024. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13025. this._grassColors = [
  13026. new BABYLON.Color3(0.29, 0.38, 0.02),
  13027. new BABYLON.Color3(0.36, 0.49, 0.09),
  13028. new BABYLON.Color3(0.51, 0.6, 0.28)
  13029. ];
  13030. this.updateShaderUniforms();
  13031. this.refreshRate = 0;
  13032. }
  13033. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13034. this.setColor3("herb1Color", this._grassColors[0]);
  13035. this.setColor3("herb2Color", this._grassColors[1]);
  13036. this.setColor3("herb3Color", this._grassColors[2]);
  13037. this.setColor3("groundColor", this._groundColor);
  13038. };
  13039. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13040. get: function () {
  13041. return this._grassColors;
  13042. },
  13043. set: function (value) {
  13044. this._grassColors = value;
  13045. this.updateShaderUniforms();
  13046. },
  13047. enumerable: true,
  13048. configurable: true
  13049. });
  13050. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13051. get: function () {
  13052. return this._groundColor;
  13053. },
  13054. set: function (value) {
  13055. this.groundColor = value;
  13056. this.updateShaderUniforms();
  13057. },
  13058. enumerable: true,
  13059. configurable: true
  13060. });
  13061. return GrassProceduralTexture;
  13062. })(BABYLON.ProceduralTexture);
  13063. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13064. var RoadProceduralTexture = (function (_super) {
  13065. __extends(RoadProceduralTexture, _super);
  13066. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13067. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13068. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13069. this.updateShaderUniforms();
  13070. this.refreshRate = 0;
  13071. }
  13072. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13073. this.setColor3("roadColor", this._roadColor);
  13074. };
  13075. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13076. get: function () {
  13077. return this._roadColor;
  13078. },
  13079. set: function (value) {
  13080. this._roadColor = value;
  13081. this.updateShaderUniforms();
  13082. },
  13083. enumerable: true,
  13084. configurable: true
  13085. });
  13086. return RoadProceduralTexture;
  13087. })(BABYLON.ProceduralTexture);
  13088. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13089. var BrickProceduralTexture = (function (_super) {
  13090. __extends(BrickProceduralTexture, _super);
  13091. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13092. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13093. this._numberOfBricksHeight = 15;
  13094. this._numberOfBricksWidth = 5;
  13095. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13096. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13097. this.updateShaderUniforms();
  13098. this.refreshRate = 0;
  13099. }
  13100. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13101. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13102. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13103. this.setColor3("brickColor", this._brickColor);
  13104. this.setColor3("jointColor", this._jointColor);
  13105. };
  13106. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13107. get: function () {
  13108. return this._numberOfBricksHeight;
  13109. },
  13110. enumerable: true,
  13111. configurable: true
  13112. });
  13113. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13114. set: function (value) {
  13115. this._numberOfBricksHeight = value;
  13116. this.updateShaderUniforms();
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13122. get: function () {
  13123. return this._numberOfBricksWidth;
  13124. },
  13125. set: function (value) {
  13126. this._numberOfBricksHeight = value;
  13127. this.updateShaderUniforms();
  13128. },
  13129. enumerable: true,
  13130. configurable: true
  13131. });
  13132. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13133. get: function () {
  13134. return this._jointColor;
  13135. },
  13136. set: function (value) {
  13137. this._jointColor = value;
  13138. this.updateShaderUniforms();
  13139. },
  13140. enumerable: true,
  13141. configurable: true
  13142. });
  13143. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13144. get: function () {
  13145. return this._brickColor;
  13146. },
  13147. set: function (value) {
  13148. this._brickColor = value;
  13149. this.updateShaderUniforms();
  13150. },
  13151. enumerable: true,
  13152. configurable: true
  13153. });
  13154. return BrickProceduralTexture;
  13155. })(BABYLON.ProceduralTexture);
  13156. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13157. var MarbleProceduralTexture = (function (_super) {
  13158. __extends(MarbleProceduralTexture, _super);
  13159. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13160. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13161. this._numberOfTilesHeight = 3;
  13162. this._numberOfTilesWidth = 3;
  13163. this._amplitude = 9.0;
  13164. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13165. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13166. this.updateShaderUniforms();
  13167. this.refreshRate = 0;
  13168. }
  13169. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13170. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13171. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13172. this.setFloat("amplitude", this._amplitude);
  13173. this.setColor3("marbleColor", this._marbleColor);
  13174. this.setColor3("jointColor", this._jointColor);
  13175. };
  13176. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13177. get: function () {
  13178. return this._numberOfTilesHeight;
  13179. },
  13180. set: function (value) {
  13181. this._numberOfTilesHeight = value;
  13182. this.updateShaderUniforms();
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13188. get: function () {
  13189. return this._numberOfTilesWidth;
  13190. },
  13191. set: function (value) {
  13192. this._numberOfTilesWidth = value;
  13193. this.updateShaderUniforms();
  13194. },
  13195. enumerable: true,
  13196. configurable: true
  13197. });
  13198. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13199. get: function () {
  13200. return this._jointColor;
  13201. },
  13202. set: function (value) {
  13203. this._jointColor = value;
  13204. this.updateShaderUniforms();
  13205. },
  13206. enumerable: true,
  13207. configurable: true
  13208. });
  13209. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13210. get: function () {
  13211. return this._marbleColor;
  13212. },
  13213. set: function (value) {
  13214. this._marbleColor = value;
  13215. this.updateShaderUniforms();
  13216. },
  13217. enumerable: true,
  13218. configurable: true
  13219. });
  13220. return MarbleProceduralTexture;
  13221. })(BABYLON.ProceduralTexture);
  13222. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13223. })(BABYLON || (BABYLON = {}));
  13224. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13225. var BABYLON;
  13226. (function (BABYLON) {
  13227. var CustomProceduralTexture = (function (_super) {
  13228. __extends(CustomProceduralTexture, _super);
  13229. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13230. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13231. this._animate = true;
  13232. this._time = 0;
  13233. this._texturePath = texturePath;
  13234. //Try to load json
  13235. this.loadJson(texturePath);
  13236. this.refreshRate = 1;
  13237. }
  13238. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13239. var _this = this;
  13240. var that = this;
  13241. function noConfigFile() {
  13242. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13243. try {
  13244. that.setFragment(that._texturePath);
  13245. }
  13246. catch (ex) {
  13247. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13248. }
  13249. }
  13250. var configFileUrl = jsonUrl + "/config.json";
  13251. var xhr = new XMLHttpRequest();
  13252. xhr.open("GET", configFileUrl, true);
  13253. xhr.addEventListener("load", function () {
  13254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13255. try {
  13256. _this._config = JSON.parse(xhr.response);
  13257. _this.updateShaderUniforms();
  13258. _this.updateTextures();
  13259. _this.setFragment(_this._texturePath + "/custom");
  13260. _this._animate = _this._config.animate;
  13261. _this.refreshRate = _this._config.refreshrate;
  13262. }
  13263. catch (ex) {
  13264. noConfigFile();
  13265. }
  13266. }
  13267. else {
  13268. noConfigFile();
  13269. }
  13270. }, false);
  13271. xhr.addEventListener("error", function () {
  13272. noConfigFile();
  13273. }, false);
  13274. try {
  13275. xhr.send();
  13276. }
  13277. catch (ex) {
  13278. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13279. }
  13280. };
  13281. CustomProceduralTexture.prototype.isReady = function () {
  13282. if (!_super.prototype.isReady.call(this)) {
  13283. return false;
  13284. }
  13285. for (var name in this._textures) {
  13286. var texture = this._textures[name];
  13287. if (!texture.isReady()) {
  13288. return false;
  13289. }
  13290. }
  13291. return true;
  13292. };
  13293. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13294. if (this._animate) {
  13295. this._time += this.getScene().getAnimationRatio() * 0.03;
  13296. this.updateShaderUniforms();
  13297. }
  13298. _super.prototype.render.call(this, useCameraPostProcess);
  13299. };
  13300. CustomProceduralTexture.prototype.updateTextures = function () {
  13301. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13302. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13303. }
  13304. };
  13305. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13306. if (this._config) {
  13307. for (var j = 0; j < this._config.uniforms.length; j++) {
  13308. var uniform = this._config.uniforms[j];
  13309. switch (uniform.type) {
  13310. case "float":
  13311. this.setFloat(uniform.name, uniform.value);
  13312. break;
  13313. case "color3":
  13314. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13315. break;
  13316. case "color4":
  13317. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13318. break;
  13319. case "vector2":
  13320. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13321. break;
  13322. case "vector3":
  13323. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13324. break;
  13325. }
  13326. }
  13327. }
  13328. this.setFloat("time", this._time);
  13329. };
  13330. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13331. get: function () {
  13332. return this._animate;
  13333. },
  13334. set: function (value) {
  13335. this._animate = value;
  13336. },
  13337. enumerable: true,
  13338. configurable: true
  13339. });
  13340. return CustomProceduralTexture;
  13341. })(BABYLON.ProceduralTexture);
  13342. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13343. })(BABYLON || (BABYLON = {}));
  13344. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13345. var BABYLON;
  13346. (function (BABYLON) {
  13347. var MirrorTexture = (function (_super) {
  13348. __extends(MirrorTexture, _super);
  13349. function MirrorTexture(name, size, scene, generateMipMaps) {
  13350. var _this = this;
  13351. _super.call(this, name, size, scene, generateMipMaps, true);
  13352. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13353. this._transformMatrix = BABYLON.Matrix.Zero();
  13354. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13355. this.onBeforeRender = function () {
  13356. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13357. _this._savedViewMatrix = scene.getViewMatrix();
  13358. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13359. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13360. scene.clipPlane = _this.mirrorPlane;
  13361. scene.getEngine().cullBackFaces = false;
  13362. };
  13363. this.onAfterRender = function () {
  13364. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13365. scene.getEngine().cullBackFaces = true;
  13366. delete scene.clipPlane;
  13367. };
  13368. }
  13369. MirrorTexture.prototype.clone = function () {
  13370. var textureSize = this.getSize();
  13371. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13372. // Base texture
  13373. newTexture.hasAlpha = this.hasAlpha;
  13374. newTexture.level = this.level;
  13375. // Mirror Texture
  13376. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13377. newTexture.renderList = this.renderList.slice(0);
  13378. return newTexture;
  13379. };
  13380. return MirrorTexture;
  13381. })(BABYLON.RenderTargetTexture);
  13382. BABYLON.MirrorTexture = MirrorTexture;
  13383. })(BABYLON || (BABYLON = {}));
  13384. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13385. var BABYLON;
  13386. (function (BABYLON) {
  13387. var DynamicTexture = (function (_super) {
  13388. __extends(DynamicTexture, _super);
  13389. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13391. _super.call(this, null, scene, !generateMipMaps);
  13392. this.name = name;
  13393. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13394. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13395. this._generateMipMaps = generateMipMaps;
  13396. if (options.getContext) {
  13397. this._canvas = options;
  13398. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13399. }
  13400. else {
  13401. this._canvas = document.createElement("canvas");
  13402. if (options.width) {
  13403. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13404. }
  13405. else {
  13406. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13407. }
  13408. }
  13409. var textureSize = this.getSize();
  13410. this._canvas.width = textureSize.width;
  13411. this._canvas.height = textureSize.height;
  13412. this._context = this._canvas.getContext("2d");
  13413. }
  13414. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13415. get: function () {
  13416. return true;
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. DynamicTexture.prototype.scale = function (ratio) {
  13422. var textureSize = this.getSize();
  13423. textureSize.width *= ratio;
  13424. textureSize.height *= ratio;
  13425. this._canvas.width = textureSize.width;
  13426. this._canvas.height = textureSize.height;
  13427. this.releaseInternalTexture();
  13428. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13429. };
  13430. DynamicTexture.prototype.getContext = function () {
  13431. return this._context;
  13432. };
  13433. DynamicTexture.prototype.clear = function () {
  13434. var size = this.getSize();
  13435. this._context.fillRect(0, 0, size.width, size.height);
  13436. };
  13437. DynamicTexture.prototype.update = function (invertY) {
  13438. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13439. };
  13440. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13441. if (update === void 0) { update = true; }
  13442. var size = this.getSize();
  13443. if (clearColor) {
  13444. this._context.fillStyle = clearColor;
  13445. this._context.fillRect(0, 0, size.width, size.height);
  13446. }
  13447. this._context.font = font;
  13448. if (x === null) {
  13449. var textSize = this._context.measureText(text);
  13450. x = (size.width - textSize.width) / 2;
  13451. }
  13452. this._context.fillStyle = color;
  13453. this._context.fillText(text, x, y);
  13454. if (update) {
  13455. this.update(invertY);
  13456. }
  13457. };
  13458. DynamicTexture.prototype.clone = function () {
  13459. var textureSize = this.getSize();
  13460. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13461. // Base texture
  13462. newTexture.hasAlpha = this.hasAlpha;
  13463. newTexture.level = this.level;
  13464. // Dynamic Texture
  13465. newTexture.wrapU = this.wrapU;
  13466. newTexture.wrapV = this.wrapV;
  13467. return newTexture;
  13468. };
  13469. return DynamicTexture;
  13470. })(BABYLON.Texture);
  13471. BABYLON.DynamicTexture = DynamicTexture;
  13472. })(BABYLON || (BABYLON = {}));
  13473. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13474. var BABYLON;
  13475. (function (BABYLON) {
  13476. var VideoTexture = (function (_super) {
  13477. __extends(VideoTexture, _super);
  13478. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13479. var _this = this;
  13480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13481. _super.call(this, null, scene, !generateMipMaps, invertY);
  13482. this._autoLaunch = true;
  13483. this.name = name;
  13484. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13485. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13486. var requiredWidth = size.width || size;
  13487. var requiredHeight = size.height || size;
  13488. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13489. var textureSize = this.getSize();
  13490. this.video = document.createElement("video");
  13491. this.video.width = textureSize.width;
  13492. this.video.height = textureSize.height;
  13493. this.video.autoplay = false;
  13494. this.video.loop = true;
  13495. this.video.addEventListener("canplaythrough", function () {
  13496. if (_this._texture) {
  13497. _this._texture.isReady = true;
  13498. }
  13499. });
  13500. urls.forEach(function (url) {
  13501. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13502. var source = document.createElement("source");
  13503. source.src = url;
  13504. _this.video.appendChild(source);
  13505. });
  13506. this._lastUpdate = BABYLON.Tools.Now;
  13507. }
  13508. VideoTexture.prototype.update = function () {
  13509. if (this._autoLaunch) {
  13510. this._autoLaunch = false;
  13511. this.video.play();
  13512. }
  13513. var now = BABYLON.Tools.Now;
  13514. if (now - this._lastUpdate < 15) {
  13515. return false;
  13516. }
  13517. this._lastUpdate = now;
  13518. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13519. return true;
  13520. };
  13521. return VideoTexture;
  13522. })(BABYLON.Texture);
  13523. BABYLON.VideoTexture = VideoTexture;
  13524. })(BABYLON || (BABYLON = {}));
  13525. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13526. (function (BABYLON) {
  13527. var EffectFallbacks = (function () {
  13528. function EffectFallbacks() {
  13529. this._defines = {};
  13530. this._currentRank = 32;
  13531. this._maxRank = -1;
  13532. }
  13533. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13534. if (!this._defines[rank]) {
  13535. if (rank < this._currentRank) {
  13536. this._currentRank = rank;
  13537. }
  13538. if (rank > this._maxRank) {
  13539. this._maxRank = rank;
  13540. }
  13541. this._defines[rank] = new Array();
  13542. }
  13543. this._defines[rank].push(define);
  13544. };
  13545. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13546. get: function () {
  13547. return this._currentRank <= this._maxRank;
  13548. },
  13549. enumerable: true,
  13550. configurable: true
  13551. });
  13552. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13553. var currentFallbacks = this._defines[this._currentRank];
  13554. for (var index = 0; index < currentFallbacks.length; index++) {
  13555. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13556. }
  13557. this._currentRank++;
  13558. return currentDefines;
  13559. };
  13560. return EffectFallbacks;
  13561. })();
  13562. BABYLON.EffectFallbacks = EffectFallbacks;
  13563. var Effect = (function () {
  13564. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13565. var _this = this;
  13566. this._isReady = false;
  13567. this._compilationError = "";
  13568. this._valueCache = [];
  13569. this._engine = engine;
  13570. this.name = baseName;
  13571. this.defines = defines;
  13572. this._uniformsNames = uniformsNames.concat(samplers);
  13573. this._samplers = samplers;
  13574. this._attributesNames = attributesNames;
  13575. this.onError = onError;
  13576. this.onCompiled = onCompiled;
  13577. var vertexSource;
  13578. var fragmentSource;
  13579. if (baseName.vertexElement) {
  13580. vertexSource = document.getElementById(baseName.vertexElement);
  13581. if (!vertexSource) {
  13582. vertexSource = baseName.vertexElement;
  13583. }
  13584. }
  13585. else {
  13586. vertexSource = baseName.vertex || baseName;
  13587. }
  13588. if (baseName.fragmentElement) {
  13589. fragmentSource = document.getElementById(baseName.fragmentElement);
  13590. if (!fragmentSource) {
  13591. fragmentSource = baseName.fragmentElement;
  13592. }
  13593. }
  13594. else {
  13595. fragmentSource = baseName.fragment || baseName;
  13596. }
  13597. this._loadVertexShader(vertexSource, function (vertexCode) {
  13598. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13599. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13600. });
  13601. });
  13602. }
  13603. // Properties
  13604. Effect.prototype.isReady = function () {
  13605. return this._isReady;
  13606. };
  13607. Effect.prototype.getProgram = function () {
  13608. return this._program;
  13609. };
  13610. Effect.prototype.getAttributesNames = function () {
  13611. return this._attributesNames;
  13612. };
  13613. Effect.prototype.getAttributeLocation = function (index) {
  13614. return this._attributes[index];
  13615. };
  13616. Effect.prototype.getAttributeLocationByName = function (name) {
  13617. var index = this._attributesNames.indexOf(name);
  13618. return this._attributes[index];
  13619. };
  13620. Effect.prototype.getAttributesCount = function () {
  13621. return this._attributes.length;
  13622. };
  13623. Effect.prototype.getUniformIndex = function (uniformName) {
  13624. return this._uniformsNames.indexOf(uniformName);
  13625. };
  13626. Effect.prototype.getUniform = function (uniformName) {
  13627. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13628. };
  13629. Effect.prototype.getSamplers = function () {
  13630. return this._samplers;
  13631. };
  13632. Effect.prototype.getCompilationError = function () {
  13633. return this._compilationError;
  13634. };
  13635. // Methods
  13636. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13637. // DOM element ?
  13638. if (vertex instanceof HTMLElement) {
  13639. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13640. callback(vertexCode);
  13641. return;
  13642. }
  13643. // Is in local store ?
  13644. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13645. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13646. return;
  13647. }
  13648. var vertexShaderUrl;
  13649. if (vertex[0] === ".") {
  13650. vertexShaderUrl = vertex;
  13651. }
  13652. else {
  13653. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13654. }
  13655. // Vertex shader
  13656. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13657. };
  13658. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13659. // DOM element ?
  13660. if (fragment instanceof HTMLElement) {
  13661. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13662. callback(fragmentCode);
  13663. return;
  13664. }
  13665. // Is in local store ?
  13666. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13667. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13668. return;
  13669. }
  13670. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13671. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13672. return;
  13673. }
  13674. var fragmentShaderUrl;
  13675. if (fragment[0] === ".") {
  13676. fragmentShaderUrl = fragment;
  13677. }
  13678. else {
  13679. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13680. }
  13681. // Fragment shader
  13682. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13683. };
  13684. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13685. try {
  13686. var engine = this._engine;
  13687. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13688. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13689. this._attributes = engine.getAttributes(this._program, attributesNames);
  13690. for (var index = 0; index < this._samplers.length; index++) {
  13691. var sampler = this.getUniform(this._samplers[index]);
  13692. if (sampler == null) {
  13693. this._samplers.splice(index, 1);
  13694. index--;
  13695. }
  13696. }
  13697. engine.bindSamplers(this);
  13698. this._isReady = true;
  13699. if (this.onCompiled) {
  13700. this.onCompiled(this);
  13701. }
  13702. }
  13703. catch (e) {
  13704. // Is it a problem with precision?
  13705. if (e.message.indexOf("highp") !== -1) {
  13706. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13707. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13708. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13709. return;
  13710. }
  13711. // Let's go through fallbacks then
  13712. if (fallbacks && fallbacks.isMoreFallbacks) {
  13713. defines = fallbacks.reduce(defines);
  13714. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13715. }
  13716. else {
  13717. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13718. BABYLON.Tools.Error("Defines: " + defines);
  13719. BABYLON.Tools.Error("Error: " + e.message);
  13720. this._compilationError = e.message;
  13721. if (this.onError) {
  13722. this.onError(this, this._compilationError);
  13723. }
  13724. }
  13725. }
  13726. };
  13727. Effect.prototype._bindTexture = function (channel, texture) {
  13728. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13729. };
  13730. Effect.prototype.setTexture = function (channel, texture) {
  13731. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13732. };
  13733. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13734. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13735. };
  13736. //public _cacheMatrix(uniformName, matrix) {
  13737. // if (!this._valueCache[uniformName]) {
  13738. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13739. // }
  13740. // for (var index = 0; index < 16; index++) {
  13741. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13742. // }
  13743. //};
  13744. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13745. if (!this._valueCache[uniformName]) {
  13746. this._valueCache[uniformName] = [x, y];
  13747. return;
  13748. }
  13749. this._valueCache[uniformName][0] = x;
  13750. this._valueCache[uniformName][1] = y;
  13751. };
  13752. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13753. if (!this._valueCache[uniformName]) {
  13754. this._valueCache[uniformName] = [x, y, z];
  13755. return;
  13756. }
  13757. this._valueCache[uniformName][0] = x;
  13758. this._valueCache[uniformName][1] = y;
  13759. this._valueCache[uniformName][2] = z;
  13760. };
  13761. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13762. if (!this._valueCache[uniformName]) {
  13763. this._valueCache[uniformName] = [x, y, z, w];
  13764. return;
  13765. }
  13766. this._valueCache[uniformName][0] = x;
  13767. this._valueCache[uniformName][1] = y;
  13768. this._valueCache[uniformName][2] = z;
  13769. this._valueCache[uniformName][3] = w;
  13770. };
  13771. Effect.prototype.setArray = function (uniformName, array) {
  13772. this._engine.setArray(this.getUniform(uniformName), array);
  13773. return this;
  13774. };
  13775. Effect.prototype.setArray2 = function (uniformName, array) {
  13776. this._engine.setArray2(this.getUniform(uniformName), array);
  13777. return this;
  13778. };
  13779. Effect.prototype.setArray3 = function (uniformName, array) {
  13780. this._engine.setArray3(this.getUniform(uniformName), array);
  13781. return this;
  13782. };
  13783. Effect.prototype.setArray4 = function (uniformName, array) {
  13784. this._engine.setArray4(this.getUniform(uniformName), array);
  13785. return this;
  13786. };
  13787. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13788. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13789. return this;
  13790. };
  13791. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13792. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13793. // return;
  13794. //this._cacheMatrix(uniformName, matrix);
  13795. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13796. return this;
  13797. };
  13798. Effect.prototype.setFloat = function (uniformName, value) {
  13799. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13800. return this;
  13801. this._valueCache[uniformName] = value;
  13802. this._engine.setFloat(this.getUniform(uniformName), value);
  13803. return this;
  13804. };
  13805. Effect.prototype.setBool = function (uniformName, bool) {
  13806. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13807. return this;
  13808. this._valueCache[uniformName] = bool;
  13809. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13810. return this;
  13811. };
  13812. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13813. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13814. return this;
  13815. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13816. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13817. return this;
  13818. };
  13819. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13820. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13821. return this;
  13822. this._cacheFloat2(uniformName, x, y);
  13823. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13824. return this;
  13825. };
  13826. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13827. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13828. return this;
  13829. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13830. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13831. return this;
  13832. };
  13833. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13834. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13835. return this;
  13836. this._cacheFloat3(uniformName, x, y, z);
  13837. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13838. return this;
  13839. };
  13840. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13841. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13842. return this;
  13843. this._cacheFloat4(uniformName, x, y, z, w);
  13844. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13845. return this;
  13846. };
  13847. Effect.prototype.setColor3 = function (uniformName, color3) {
  13848. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13849. return this;
  13850. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13851. this._engine.setColor3(this.getUniform(uniformName), color3);
  13852. return this;
  13853. };
  13854. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13855. 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)
  13856. return this;
  13857. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13858. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13859. return this;
  13860. };
  13861. // Statics
  13862. 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}",
  13863. 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}",
  13864. 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}",
  13865. 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}",
  13866. chromaticAberrationPixelShader:"/*\n BABYLON.JS Chromatic Aberration GLSL Shader\n Author: Olivier Guyot\n Separates very slightly R, G and B colors on the edges of the screen\n Inspired by Francois Tarlier & Martins Upitis \n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // original color\n\n// uniforms\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\n// varyings\nvarying vec2 vUV;\n\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n\n vec4 original = texture2D(textureSampler, vUV);\n\n if(chromatic_aberration > 0.0) {\n //index of refraction of each color channel, causing chromatic dispersion\n vec3 ref_indices = vec3(0.6, 0.3, 0.0);\n float ref_shiftX = chromatic_aberration * radius * 12.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 12.0 / screen_height;\n\n // shifts for red, green & blue\n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n\n gl_FragColor = original;\n}",
  13867. 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}",
  13868. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13869. 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}",
  13870. 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}",
  13871. 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;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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 vec3 shadowsInfo0;\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 vec3 shadowsInfo1;\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 vec3 shadowsInfo2;\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 vec3 shadowsInfo3;\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 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\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, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n bias = 0.02 + bias;\n if (t <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, bias);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05 - bias, 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z > 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 1.0 - ChebychevInequality(moments, depth.z, bias);\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 = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\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#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\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, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\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, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\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, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\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, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\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}",
  13872. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#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;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\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}",
  13873. 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}",
  13874. 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}",
  13875. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  13876. depthOfFieldPixelShader:"/*\n BABYLON.JS Depth-of-field GLSL Shader\n Author: Olivier Guyot\n Does depth-of-field blur, edge blur, highlights enhancing\n Inspired by Francois Tarlier & Martins Upitis\n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\n// samplers\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\n// uniforms\nuniform float grain_amount;\nuniform bool pentagon;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float gain;\nuniform float threshold;\nuniform float edge_blur;\n\n// varyings\nvarying vec2 vUV;\n\n// constants\n#define PI 3.14159265\nconst int RING_1_SAMPLES = 4;\nconst int RING_2_SAMPLES = 6;\nconst int RING_3_SAMPLES = 9;\nconst int RING_4_SAMPLES = 12;\nconst int RING_5_SAMPLES = 16;\n//const int RING_6_SAMPLES = 15;\nconst float RING_STEP_DIST = 0.4; // a new blur ring is added each time this distance is passed\nconst float PENTAGON_ANGLE_SUB = 1.2566; // 2PI / 5\nconst float PENTAGON_ANGLE_SUB_HALF = 0.6283; // 2PI / 10\n\n// common calculations\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\n// applies edge distortion on texture coords\nvec2 getDistortedCoords(vec2 coords) {\n\n if(distortion == 0.0) { return coords; }\n\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\n dist_coords = mix(coords, dist_coords, dist_amount);\n\n return dist_coords;\n}\n\n// picks either original screen color or highlights only\nvec4 getColor(vec2 coords, bool highlight) {\n\n vec4 color = texture2D(textureSampler, coords);\n\n if(highlight) {\n float luminance = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if(threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n if(luminance < lum_threshold) {\n color.rgb = vec3(0.0, 0.0, 0.0);\n color.a = 1.0;\n }\n }\n\n return color;\n}\n\n// returns a modifier to be applied on the radius, in order to simulate a pentagon\nfloat pentagonShape(float angle) {\n float a1 = mod(angle, PENTAGON_ANGLE_SUB) / PENTAGON_ANGLE_SUB - 0.5;\n float a2 = 0.5 - a1 * a1;\n return 1.35 - 0.94 * a2;\n}\n\n// returns original screen color after blur\nvec4 getBlurColor(vec2 coords, float size, bool highlight) {\n\n float w = (size/screen_width);\n float h = (size/screen_height);\n\n vec4 col = getColor(coords, highlight);\n if(size == 0.0) { return col; }\n\n float s = 1.0;\n float pw; // sample x relative coord\n float ph; // sample y relative coord\n float bias = 0.65; // inner/outer ring bias\n if(highlight) { bias = 0.95; }\n float sample_angle;\n float ratio_rings;\n float ring_radius;\n float penta; // pentagon shape modifier\n\n int ring_count;\n if(size >= 6.0 * RING_STEP_DIST) { ring_count = 6; }\n else if(size >= 5.0 * RING_STEP_DIST) { ring_count = 5; }\n else if(size >= 4.0 * RING_STEP_DIST) { ring_count = 4; }\n else if(size >= 3.0 * RING_STEP_DIST) { ring_count = 3; }\n else if(size >= 2.0 * RING_STEP_DIST) { ring_count = 2; }\n else { ring_count = 1; }\n \n // RING 1\n if(size > RING_STEP_DIST) {\n ring_radius = size / float(ring_count);\n ratio_rings = 1.0 / float(ring_count);\n for(int i = 0; i < RING_1_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_1_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias);\n }\n } \n\n // RING 2\n if(size > RING_STEP_DIST * 2.0) {\n ring_radius = 2.0 * size / float(ring_count);\n ratio_rings = 2.0 / float(ring_count);\n for(int i = 0; i < RING_2_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_2_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 3\n if(size > RING_STEP_DIST * 3.0) {\n ring_radius = 3.0 * size / float(ring_count);\n ratio_rings = 3.0 / float(ring_count);\n for(int i = 0; i < RING_3_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_3_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 4\n if(size > RING_STEP_DIST * 4.0) {\n ring_radius = 4.0 * size / float(ring_count);\n ratio_rings = 4.0 / float(ring_count);\n for(int i = 0; i < RING_4_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_4_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 5\n if(size > RING_STEP_DIST * 5.0) {\n ring_radius = 5.0 * size / float(ring_count);\n ratio_rings = 5.0 / float(ring_count);\n for(int i = 0; i < RING_5_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_5_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n col /= s; // scales color according to samples taken\n col.a = 1.0;\n\n return col;\n}\n\n// on-the-fly constant noise\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co ,vec2(12.9898,78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvoid main(void)\n{\n\n // Common calc\n centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n\n vec4 final_color;\n vec2 distorted_coords = getDistortedCoords(vUV);\n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\n // blur from depth of field effect\n float dof_blur_amount = 0.0;\n if(focus_depth != -1.0) {\n vec4 depth_sample = texture2D(depthSampler, distorted_coords);\n float depth = depth_sample.r;\n dof_blur_amount = abs(depth - focus_depth) * aperture * 3.5;\n if(dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n else if( depth - focus_depth < 0.0 ) { dof_blur_amount *= 2.0; } // blur more when close to camera\n dof_blur_amount = clamp(dof_blur_amount, 0.0, 1.0);\n }\n\n // blur from edge blur effect\n float edge_blur_amount = 0.0;\n if(edge_blur > 0.0) {\n edge_blur_amount = clamp( ( radius*2.0 - 1.0 + 0.15*edge_blur ) * 1.5 , 0.0 , 1.0 ) * 1.3;\n }\n\n // total blur amount\n float blur_amount = max(edge_blur_amount, dof_blur_amount);\n\n // apply blur if necessary\n if(blur_amount == 0.0) {\n gl_FragColor = getColor(distorted_coords, false);\n } else {\n gl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7, false)\n + gain * blur_amount*getBlurColor(distorted_coords, blur_amount * 2.75, true);\n\n if(blur_noise) {\n // we put a slight amount of noise in the blurred color\n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * getColor(blurred_coord, false) + 0.96 * gl_FragColor;\n }\n }\n\n if(grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += ( -0.5 + grain_color.rgb ) * 0.20;\n }\n}",
  13877. 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}",
  13878. 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}",
  13879. 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}",
  13880. 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}",
  13881. 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}",
  13882. 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}",
  13883. 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}",
  13884. 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}",
  13885. 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}",
  13886. 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}",
  13887. 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}",
  13888. 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}",
  13889. 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}",
  13890. 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}",
  13891. 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}",
  13892. 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}",
  13893. 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}",
  13894. 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}",
  13895. 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}",
  13896. 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}",
  13897. 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}",
  13898. 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}",
  13899. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\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\nvarying vec4 vPosition;\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 float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  13900. 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\nvarying vec4 vPosition;\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#endif\n\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\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}",
  13901. 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}",
  13902. 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}",
  13903. 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}",
  13904. 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}",
  13905. 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}",
  13906. 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}",
  13907. 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}",
  13908. };
  13909. return Effect;
  13910. })();
  13911. BABYLON.Effect = Effect;
  13912. })(BABYLON || (BABYLON = {}));
  13913. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13914. (function (BABYLON) {
  13915. var Material = (function () {
  13916. function Material(name, scene, doNotAdd) {
  13917. this.name = name;
  13918. this.checkReadyOnEveryCall = true;
  13919. this.checkReadyOnlyOnce = false;
  13920. this.state = "";
  13921. this.alpha = 1.0;
  13922. this.backFaceCulling = true;
  13923. this._wasPreviouslyReady = false;
  13924. this._fillMode = Material.TriangleFillMode;
  13925. this.pointSize = 1.0;
  13926. this.id = name;
  13927. this._scene = scene;
  13928. if (!doNotAdd) {
  13929. scene.materials.push(this);
  13930. }
  13931. }
  13932. Object.defineProperty(Material, "TriangleFillMode", {
  13933. get: function () {
  13934. return Material._TriangleFillMode;
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Object.defineProperty(Material, "WireFrameFillMode", {
  13940. get: function () {
  13941. return Material._WireFrameFillMode;
  13942. },
  13943. enumerable: true,
  13944. configurable: true
  13945. });
  13946. Object.defineProperty(Material, "PointFillMode", {
  13947. get: function () {
  13948. return Material._PointFillMode;
  13949. },
  13950. enumerable: true,
  13951. configurable: true
  13952. });
  13953. Object.defineProperty(Material.prototype, "wireframe", {
  13954. get: function () {
  13955. return this._fillMode === Material.WireFrameFillMode;
  13956. },
  13957. set: function (value) {
  13958. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13959. },
  13960. enumerable: true,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(Material.prototype, "pointsCloud", {
  13964. get: function () {
  13965. return this._fillMode === Material.PointFillMode;
  13966. },
  13967. set: function (value) {
  13968. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13969. },
  13970. enumerable: true,
  13971. configurable: true
  13972. });
  13973. Object.defineProperty(Material.prototype, "fillMode", {
  13974. get: function () {
  13975. return this._fillMode;
  13976. },
  13977. set: function (value) {
  13978. this._fillMode = value;
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. Material.prototype.isReady = function (mesh, useInstances) {
  13984. return true;
  13985. };
  13986. Material.prototype.getEffect = function () {
  13987. return this._effect;
  13988. };
  13989. Material.prototype.getScene = function () {
  13990. return this._scene;
  13991. };
  13992. Material.prototype.needAlphaBlending = function () {
  13993. return (this.alpha < 1.0);
  13994. };
  13995. Material.prototype.needAlphaTesting = function () {
  13996. return false;
  13997. };
  13998. Material.prototype.getAlphaTestTexture = function () {
  13999. return null;
  14000. };
  14001. Material.prototype.trackCreation = function (onCompiled, onError) {
  14002. };
  14003. Material.prototype._preBind = function () {
  14004. var engine = this._scene.getEngine();
  14005. engine.enableEffect(this._effect);
  14006. engine.setState(this.backFaceCulling);
  14007. };
  14008. Material.prototype.bind = function (world, mesh) {
  14009. this._scene._cachedMaterial = this;
  14010. if (this.onBind) {
  14011. this.onBind(this);
  14012. }
  14013. };
  14014. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14015. };
  14016. Material.prototype.unbind = function () {
  14017. };
  14018. Material.prototype.dispose = function (forceDisposeEffect) {
  14019. // Remove from scene
  14020. var index = this._scene.materials.indexOf(this);
  14021. this._scene.materials.splice(index, 1);
  14022. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14023. if (forceDisposeEffect && this._effect) {
  14024. this._scene.getEngine()._releaseEffect(this._effect);
  14025. this._effect = null;
  14026. }
  14027. // Callback
  14028. if (this.onDispose) {
  14029. this.onDispose();
  14030. }
  14031. };
  14032. Material._TriangleFillMode = 0;
  14033. Material._WireFrameFillMode = 1;
  14034. Material._PointFillMode = 2;
  14035. return Material;
  14036. })();
  14037. BABYLON.Material = Material;
  14038. })(BABYLON || (BABYLON = {}));
  14039. //# sourceMappingURL=babylon.material.js.map
  14040. var BABYLON;
  14041. (function (BABYLON) {
  14042. var maxSimultaneousLights = 4;
  14043. var FresnelParameters = (function () {
  14044. function FresnelParameters() {
  14045. this.isEnabled = true;
  14046. this.leftColor = BABYLON.Color3.White();
  14047. this.rightColor = BABYLON.Color3.Black();
  14048. this.bias = 0;
  14049. this.power = 1;
  14050. }
  14051. return FresnelParameters;
  14052. })();
  14053. BABYLON.FresnelParameters = FresnelParameters;
  14054. var StandardMaterial = (function (_super) {
  14055. __extends(StandardMaterial, _super);
  14056. function StandardMaterial(name, scene) {
  14057. var _this = this;
  14058. _super.call(this, name, scene);
  14059. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14060. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14061. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14062. this.specularPower = 64;
  14063. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14064. this.useAlphaFromDiffuseTexture = false;
  14065. this.useSpecularOverAlpha = true;
  14066. this.fogEnabled = true;
  14067. this._cachedDefines = null;
  14068. this._renderTargets = new BABYLON.SmartArray(16);
  14069. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14070. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14071. this._scaledDiffuse = new BABYLON.Color3();
  14072. this._scaledSpecular = new BABYLON.Color3();
  14073. this.getRenderTargetTextures = function () {
  14074. _this._renderTargets.reset();
  14075. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14076. _this._renderTargets.push(_this.reflectionTexture);
  14077. }
  14078. return _this._renderTargets;
  14079. };
  14080. }
  14081. StandardMaterial.prototype.needAlphaBlending = function () {
  14082. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14083. };
  14084. StandardMaterial.prototype.needAlphaTesting = function () {
  14085. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14086. };
  14087. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14088. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14089. };
  14090. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14091. return this.diffuseTexture;
  14092. };
  14093. // Methods
  14094. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14095. if (this.checkReadyOnlyOnce) {
  14096. if (this._wasPreviouslyReady) {
  14097. return true;
  14098. }
  14099. }
  14100. var scene = this.getScene();
  14101. if (!this.checkReadyOnEveryCall) {
  14102. if (this._renderId === scene.getRenderId()) {
  14103. return true;
  14104. }
  14105. }
  14106. var engine = scene.getEngine();
  14107. var defines = [];
  14108. var fallbacks = new BABYLON.EffectFallbacks();
  14109. var needNormals = false;
  14110. var needUVs = false;
  14111. // Textures
  14112. if (scene.texturesEnabled) {
  14113. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14114. if (!this.diffuseTexture.isReady()) {
  14115. return false;
  14116. }
  14117. else {
  14118. needUVs = true;
  14119. defines.push("#define DIFFUSE");
  14120. }
  14121. }
  14122. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14123. if (!this.ambientTexture.isReady()) {
  14124. return false;
  14125. }
  14126. else {
  14127. needUVs = true;
  14128. defines.push("#define AMBIENT");
  14129. }
  14130. }
  14131. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14132. if (!this.opacityTexture.isReady()) {
  14133. return false;
  14134. }
  14135. else {
  14136. needUVs = true;
  14137. defines.push("#define OPACITY");
  14138. if (this.opacityTexture.getAlphaFromRGB) {
  14139. defines.push("#define OPACITYRGB");
  14140. }
  14141. }
  14142. }
  14143. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14144. if (!this.reflectionTexture.isReady()) {
  14145. return false;
  14146. }
  14147. else {
  14148. needNormals = true;
  14149. needUVs = true;
  14150. defines.push("#define REFLECTION");
  14151. fallbacks.addFallback(0, "REFLECTION");
  14152. }
  14153. }
  14154. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14155. if (!this.emissiveTexture.isReady()) {
  14156. return false;
  14157. }
  14158. else {
  14159. needUVs = true;
  14160. defines.push("#define EMISSIVE");
  14161. }
  14162. }
  14163. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14164. if (!this.specularTexture.isReady()) {
  14165. return false;
  14166. }
  14167. else {
  14168. needUVs = true;
  14169. defines.push("#define SPECULAR");
  14170. fallbacks.addFallback(0, "SPECULAR");
  14171. }
  14172. }
  14173. }
  14174. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14175. if (!this.bumpTexture.isReady()) {
  14176. return false;
  14177. }
  14178. else {
  14179. needUVs = true;
  14180. defines.push("#define BUMP");
  14181. fallbacks.addFallback(0, "BUMP");
  14182. }
  14183. }
  14184. // Effect
  14185. if (this.useSpecularOverAlpha) {
  14186. defines.push("#define SPECULAROVERALPHA");
  14187. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14188. }
  14189. if (scene.clipPlane) {
  14190. defines.push("#define CLIPPLANE");
  14191. }
  14192. if (engine.getAlphaTesting()) {
  14193. defines.push("#define ALPHATEST");
  14194. }
  14195. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14196. defines.push("#define ALPHAFROMDIFFUSE");
  14197. }
  14198. // Point size
  14199. if (this.pointsCloud || scene.forcePointsCloud) {
  14200. defines.push("#define POINTSIZE");
  14201. }
  14202. // Fog
  14203. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14204. defines.push("#define FOG");
  14205. fallbacks.addFallback(1, "FOG");
  14206. }
  14207. var shadowsActivated = false;
  14208. var lightIndex = 0;
  14209. if (scene.lightsEnabled) {
  14210. for (var index = 0; index < scene.lights.length; index++) {
  14211. var light = scene.lights[index];
  14212. if (!light.isEnabled()) {
  14213. continue;
  14214. }
  14215. // Excluded check
  14216. if (light._excludedMeshesIds.length > 0) {
  14217. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14218. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14219. if (excludedMesh) {
  14220. light.excludedMeshes.push(excludedMesh);
  14221. }
  14222. }
  14223. light._excludedMeshesIds = [];
  14224. }
  14225. // Included check
  14226. if (light._includedOnlyMeshesIds.length > 0) {
  14227. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14228. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14229. if (includedOnlyMesh) {
  14230. light.includedOnlyMeshes.push(includedOnlyMesh);
  14231. }
  14232. }
  14233. light._includedOnlyMeshesIds = [];
  14234. }
  14235. if (!light.canAffectMesh(mesh)) {
  14236. continue;
  14237. }
  14238. needNormals = true;
  14239. defines.push("#define LIGHT" + lightIndex);
  14240. if (lightIndex > 0) {
  14241. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14242. }
  14243. var type;
  14244. if (light instanceof BABYLON.SpotLight) {
  14245. type = "#define SPOTLIGHT" + lightIndex;
  14246. }
  14247. else if (light instanceof BABYLON.HemisphericLight) {
  14248. type = "#define HEMILIGHT" + lightIndex;
  14249. }
  14250. else {
  14251. type = "#define POINTDIRLIGHT" + lightIndex;
  14252. }
  14253. defines.push(type);
  14254. if (lightIndex > 0) {
  14255. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14256. }
  14257. // Shadows
  14258. if (scene.shadowsEnabled) {
  14259. var shadowGenerator = light.getShadowGenerator();
  14260. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14261. defines.push("#define SHADOW" + lightIndex);
  14262. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14263. if (!shadowsActivated) {
  14264. defines.push("#define SHADOWS");
  14265. shadowsActivated = true;
  14266. }
  14267. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14268. defines.push("#define SHADOWVSM" + lightIndex);
  14269. if (lightIndex > 0) {
  14270. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14271. }
  14272. }
  14273. if (shadowGenerator.usePoissonSampling) {
  14274. defines.push("#define SHADOWPCF" + lightIndex);
  14275. if (lightIndex > 0) {
  14276. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14277. }
  14278. }
  14279. }
  14280. }
  14281. lightIndex++;
  14282. if (lightIndex === maxSimultaneousLights)
  14283. break;
  14284. }
  14285. }
  14286. if (StandardMaterial.FresnelEnabled) {
  14287. // Fresnel
  14288. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14289. var fresnelRank = 1;
  14290. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14291. defines.push("#define DIFFUSEFRESNEL");
  14292. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14293. fresnelRank++;
  14294. }
  14295. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14296. defines.push("#define OPACITYFRESNEL");
  14297. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14298. fresnelRank++;
  14299. }
  14300. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14301. defines.push("#define REFLECTIONFRESNEL");
  14302. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14303. fresnelRank++;
  14304. }
  14305. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14306. defines.push("#define EMISSIVEFRESNEL");
  14307. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14308. fresnelRank++;
  14309. }
  14310. needNormals = true;
  14311. defines.push("#define FRESNEL");
  14312. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14313. }
  14314. }
  14315. // Attribs
  14316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14317. if (mesh) {
  14318. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14319. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14320. defines.push("#define NORMAL");
  14321. }
  14322. if (needUVs) {
  14323. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14324. attribs.push(BABYLON.VertexBuffer.UVKind);
  14325. defines.push("#define UV1");
  14326. }
  14327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14328. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14329. defines.push("#define UV2");
  14330. }
  14331. }
  14332. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14333. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14334. defines.push("#define VERTEXCOLOR");
  14335. if (mesh.hasVertexAlpha) {
  14336. defines.push("#define VERTEXALPHA");
  14337. }
  14338. }
  14339. if (mesh.useBones) {
  14340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14342. defines.push("#define BONES");
  14343. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14344. defines.push("#define BONES4");
  14345. fallbacks.addFallback(0, "BONES4");
  14346. }
  14347. // Instances
  14348. if (useInstances) {
  14349. defines.push("#define INSTANCES");
  14350. attribs.push("world0");
  14351. attribs.push("world1");
  14352. attribs.push("world2");
  14353. attribs.push("world3");
  14354. }
  14355. }
  14356. // Get correct effect
  14357. var join = defines.join("\n");
  14358. if (this._cachedDefines !== join) {
  14359. this._cachedDefines = join;
  14360. scene.resetCachedMaterial();
  14361. // Legacy browser patch
  14362. var shaderName = "default";
  14363. if (!scene.getEngine().getCaps().standardDerivatives) {
  14364. shaderName = "legacydefault";
  14365. }
  14366. 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", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "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);
  14367. }
  14368. if (!this._effect.isReady()) {
  14369. return false;
  14370. }
  14371. this._renderId = scene.getRenderId();
  14372. this._wasPreviouslyReady = true;
  14373. return true;
  14374. };
  14375. StandardMaterial.prototype.unbind = function () {
  14376. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14377. this._effect.setTexture("reflection2DSampler", null);
  14378. }
  14379. };
  14380. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14381. this._effect.setMatrix("world", world);
  14382. };
  14383. StandardMaterial.prototype.bind = function (world, mesh) {
  14384. var scene = this.getScene();
  14385. // Matrices
  14386. this.bindOnlyWorldMatrix(world);
  14387. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14388. // Bones
  14389. if (mesh.useBones) {
  14390. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14391. }
  14392. if (scene.getCachedMaterial() !== this) {
  14393. if (StandardMaterial.FresnelEnabled) {
  14394. // Fresnel
  14395. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14396. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14397. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14398. }
  14399. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14400. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14401. }
  14402. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14403. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14404. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14405. }
  14406. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14407. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14408. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14409. }
  14410. }
  14411. // Textures
  14412. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14413. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14414. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14415. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14416. }
  14417. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14418. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14419. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14420. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14421. }
  14422. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14423. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14424. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14425. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14426. }
  14427. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14428. if (this.reflectionTexture.isCube) {
  14429. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14430. }
  14431. else {
  14432. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14433. }
  14434. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14435. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14436. }
  14437. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14438. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14439. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14440. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14441. }
  14442. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14443. this._effect.setTexture("specularSampler", this.specularTexture);
  14444. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14445. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14446. }
  14447. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14448. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14449. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14450. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14451. }
  14452. // Clip plane
  14453. if (scene.clipPlane) {
  14454. var clipPlane = scene.clipPlane;
  14455. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14456. }
  14457. // Point size
  14458. if (this.pointsCloud) {
  14459. this._effect.setFloat("pointSize", this.pointSize);
  14460. }
  14461. // Colors
  14462. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14463. // Scaling down color according to emissive
  14464. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14465. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14466. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14467. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14468. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14469. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14470. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14471. }
  14472. // Scaling down color according to emissive
  14473. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14474. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14475. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14476. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14477. if (scene.lightsEnabled) {
  14478. var lightIndex = 0;
  14479. for (var index = 0; index < scene.lights.length; index++) {
  14480. var light = scene.lights[index];
  14481. if (!light.isEnabled()) {
  14482. continue;
  14483. }
  14484. if (!light.canAffectMesh(mesh)) {
  14485. continue;
  14486. }
  14487. if (light instanceof BABYLON.PointLight) {
  14488. // Point Light
  14489. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14490. }
  14491. else if (light instanceof BABYLON.DirectionalLight) {
  14492. // Directional Light
  14493. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14494. }
  14495. else if (light instanceof BABYLON.SpotLight) {
  14496. // Spot Light
  14497. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14498. }
  14499. else if (light instanceof BABYLON.HemisphericLight) {
  14500. // Hemispheric Light
  14501. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14502. }
  14503. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14504. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14505. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14506. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14507. // Shadows
  14508. if (scene.shadowsEnabled) {
  14509. var shadowGenerator = light.getShadowGenerator();
  14510. if (mesh.receiveShadows && shadowGenerator) {
  14511. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14512. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14513. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14514. }
  14515. }
  14516. lightIndex++;
  14517. if (lightIndex === maxSimultaneousLights)
  14518. break;
  14519. }
  14520. }
  14521. // View
  14522. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14523. this._effect.setMatrix("view", scene.getViewMatrix());
  14524. }
  14525. // Fog
  14526. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14527. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14528. this._effect.setColor3("vFogColor", scene.fogColor);
  14529. }
  14530. _super.prototype.bind.call(this, world, mesh);
  14531. };
  14532. StandardMaterial.prototype.getAnimatables = function () {
  14533. var results = [];
  14534. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14535. results.push(this.diffuseTexture);
  14536. }
  14537. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14538. results.push(this.ambientTexture);
  14539. }
  14540. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14541. results.push(this.opacityTexture);
  14542. }
  14543. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14544. results.push(this.reflectionTexture);
  14545. }
  14546. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14547. results.push(this.emissiveTexture);
  14548. }
  14549. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14550. results.push(this.specularTexture);
  14551. }
  14552. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14553. results.push(this.bumpTexture);
  14554. }
  14555. return results;
  14556. };
  14557. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14558. if (this.diffuseTexture) {
  14559. this.diffuseTexture.dispose();
  14560. }
  14561. if (this.ambientTexture) {
  14562. this.ambientTexture.dispose();
  14563. }
  14564. if (this.opacityTexture) {
  14565. this.opacityTexture.dispose();
  14566. }
  14567. if (this.reflectionTexture) {
  14568. this.reflectionTexture.dispose();
  14569. }
  14570. if (this.emissiveTexture) {
  14571. this.emissiveTexture.dispose();
  14572. }
  14573. if (this.specularTexture) {
  14574. this.specularTexture.dispose();
  14575. }
  14576. if (this.bumpTexture) {
  14577. this.bumpTexture.dispose();
  14578. }
  14579. _super.prototype.dispose.call(this, forceDisposeEffect);
  14580. };
  14581. StandardMaterial.prototype.clone = function (name) {
  14582. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14583. // Base material
  14584. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14585. newStandardMaterial.alpha = this.alpha;
  14586. newStandardMaterial.fillMode = this.fillMode;
  14587. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14588. // Standard material
  14589. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14590. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14591. }
  14592. if (this.ambientTexture && this.ambientTexture.clone) {
  14593. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14594. }
  14595. if (this.opacityTexture && this.opacityTexture.clone) {
  14596. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14597. }
  14598. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14599. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14600. }
  14601. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14602. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14603. }
  14604. if (this.specularTexture && this.specularTexture.clone) {
  14605. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14606. }
  14607. if (this.bumpTexture && this.bumpTexture.clone) {
  14608. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14609. }
  14610. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14611. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14612. newStandardMaterial.specularColor = this.specularColor.clone();
  14613. newStandardMaterial.specularPower = this.specularPower;
  14614. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14615. return newStandardMaterial;
  14616. };
  14617. // Statics
  14618. // Flags used to enable or disable a type of texture for all Standard Materials
  14619. StandardMaterial.DiffuseTextureEnabled = true;
  14620. StandardMaterial.AmbientTextureEnabled = true;
  14621. StandardMaterial.OpacityTextureEnabled = true;
  14622. StandardMaterial.ReflectionTextureEnabled = true;
  14623. StandardMaterial.EmissiveTextureEnabled = true;
  14624. StandardMaterial.SpecularTextureEnabled = true;
  14625. StandardMaterial.BumpTextureEnabled = true;
  14626. StandardMaterial.FresnelEnabled = true;
  14627. return StandardMaterial;
  14628. })(BABYLON.Material);
  14629. BABYLON.StandardMaterial = StandardMaterial;
  14630. })(BABYLON || (BABYLON = {}));
  14631. //# sourceMappingURL=babylon.standardMaterial.js.map
  14632. var BABYLON;
  14633. (function (BABYLON) {
  14634. var MultiMaterial = (function (_super) {
  14635. __extends(MultiMaterial, _super);
  14636. function MultiMaterial(name, scene) {
  14637. _super.call(this, name, scene, true);
  14638. this.subMaterials = new Array();
  14639. scene.multiMaterials.push(this);
  14640. }
  14641. // Properties
  14642. MultiMaterial.prototype.getSubMaterial = function (index) {
  14643. if (index < 0 || index >= this.subMaterials.length) {
  14644. return this.getScene().defaultMaterial;
  14645. }
  14646. return this.subMaterials[index];
  14647. };
  14648. // Methods
  14649. MultiMaterial.prototype.isReady = function (mesh) {
  14650. for (var index = 0; index < this.subMaterials.length; index++) {
  14651. var subMaterial = this.subMaterials[index];
  14652. if (subMaterial) {
  14653. if (!this.subMaterials[index].isReady(mesh)) {
  14654. return false;
  14655. }
  14656. }
  14657. }
  14658. return true;
  14659. };
  14660. return MultiMaterial;
  14661. })(BABYLON.Material);
  14662. BABYLON.MultiMaterial = MultiMaterial;
  14663. })(BABYLON || (BABYLON = {}));
  14664. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14665. (function (BABYLON) {
  14666. var Database = (function () {
  14667. function Database(urlToScene, callbackManifestChecked) {
  14668. // Handling various flavors of prefixed version of IndexedDB
  14669. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14670. this.callbackManifestChecked = callbackManifestChecked;
  14671. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14672. this.db = null;
  14673. this.enableSceneOffline = false;
  14674. this.enableTexturesOffline = false;
  14675. this.manifestVersionFound = 0;
  14676. this.mustUpdateRessources = false;
  14677. this.hasReachedQuota = false;
  14678. this.checkManifestFile();
  14679. }
  14680. Database.prototype.checkManifestFile = function () {
  14681. var _this = this;
  14682. function noManifestFile() {
  14683. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14684. that.enableSceneOffline = false;
  14685. that.enableTexturesOffline = false;
  14686. that.callbackManifestChecked(false);
  14687. }
  14688. var that = this;
  14689. var manifestURL = this.currentSceneUrl + ".manifest";
  14690. var xhr = new XMLHttpRequest();
  14691. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14692. xhr.open("GET", manifestURLTimeStamped, true);
  14693. xhr.addEventListener("load", function () {
  14694. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14695. try {
  14696. var manifestFile = JSON.parse(xhr.response);
  14697. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14698. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14699. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14700. _this.manifestVersionFound = manifestFile.version;
  14701. }
  14702. if (_this.callbackManifestChecked) {
  14703. _this.callbackManifestChecked(true);
  14704. }
  14705. }
  14706. catch (ex) {
  14707. noManifestFile();
  14708. }
  14709. }
  14710. else {
  14711. noManifestFile();
  14712. }
  14713. }, false);
  14714. xhr.addEventListener("error", function (event) {
  14715. noManifestFile();
  14716. }, false);
  14717. try {
  14718. xhr.send();
  14719. }
  14720. catch (ex) {
  14721. BABYLON.Tools.Error("Error on XHR send request.");
  14722. that.callbackManifestChecked(false);
  14723. }
  14724. };
  14725. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14726. var _this = this;
  14727. function handleError() {
  14728. that.isSupported = false;
  14729. if (errorCallback)
  14730. errorCallback();
  14731. }
  14732. var that = this;
  14733. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14734. // Your browser doesn't support IndexedDB
  14735. this.isSupported = false;
  14736. if (errorCallback)
  14737. errorCallback();
  14738. }
  14739. else {
  14740. // If the DB hasn't been opened or created yet
  14741. if (!this.db) {
  14742. this.hasReachedQuota = false;
  14743. this.isSupported = true;
  14744. var request = this.idbFactory.open("babylonjs", 1);
  14745. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14746. request.onerror = function (event) {
  14747. handleError();
  14748. };
  14749. // executes when a version change transaction cannot complete due to other active transactions
  14750. request.onblocked = function (event) {
  14751. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14752. handleError();
  14753. };
  14754. // DB has been opened successfully
  14755. request.onsuccess = function (event) {
  14756. _this.db = request.result;
  14757. successCallback();
  14758. };
  14759. // Initialization of the DB. Creating Scenes & Textures stores
  14760. request.onupgradeneeded = function (event) {
  14761. _this.db = (event.target).result;
  14762. try {
  14763. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14764. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14765. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14766. }
  14767. catch (ex) {
  14768. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14769. handleError();
  14770. }
  14771. };
  14772. }
  14773. else {
  14774. if (successCallback)
  14775. successCallback();
  14776. }
  14777. }
  14778. };
  14779. Database.prototype.loadImageFromDB = function (url, image) {
  14780. var _this = this;
  14781. var completeURL = Database.ReturnFullUrlLocation(url);
  14782. var saveAndLoadImage = function () {
  14783. if (!_this.hasReachedQuota && _this.db !== null) {
  14784. // the texture is not yet in the DB, let's try to save it
  14785. _this._saveImageIntoDBAsync(completeURL, image);
  14786. }
  14787. else {
  14788. image.src = url;
  14789. }
  14790. };
  14791. if (!this.mustUpdateRessources) {
  14792. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14793. }
  14794. else {
  14795. saveAndLoadImage();
  14796. }
  14797. };
  14798. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14799. if (this.isSupported && this.db !== null) {
  14800. var texture;
  14801. var transaction = this.db.transaction(["textures"]);
  14802. transaction.onabort = function (event) {
  14803. image.src = url;
  14804. };
  14805. transaction.oncomplete = function (event) {
  14806. var blobTextureURL;
  14807. if (texture) {
  14808. var URL = window.URL || window.webkitURL;
  14809. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14810. image.onerror = function () {
  14811. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14812. image.src = url;
  14813. };
  14814. image.src = blobTextureURL;
  14815. }
  14816. else {
  14817. notInDBCallback();
  14818. }
  14819. };
  14820. var getRequest = transaction.objectStore("textures").get(url);
  14821. getRequest.onsuccess = function (event) {
  14822. texture = (event.target).result;
  14823. };
  14824. getRequest.onerror = function (event) {
  14825. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14826. image.src = url;
  14827. };
  14828. }
  14829. else {
  14830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14831. image.src = url;
  14832. }
  14833. };
  14834. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14835. var _this = this;
  14836. if (this.isSupported) {
  14837. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14838. var generateBlobUrl = function () {
  14839. var blobTextureURL;
  14840. if (blob) {
  14841. var URL = window.URL || window.webkitURL;
  14842. try {
  14843. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14844. }
  14845. catch (ex) {
  14846. blobTextureURL = URL.createObjectURL(blob);
  14847. }
  14848. }
  14849. image.src = blobTextureURL;
  14850. };
  14851. if (Database.isUASupportingBlobStorage) {
  14852. var xhr = new XMLHttpRequest(), blob;
  14853. xhr.open("GET", url, true);
  14854. xhr.responseType = "blob";
  14855. xhr.addEventListener("load", function () {
  14856. if (xhr.status === 200) {
  14857. // Blob as response (XHR2)
  14858. blob = xhr.response;
  14859. var transaction = _this.db.transaction(["textures"], "readwrite");
  14860. // the transaction could abort because of a QuotaExceededError error
  14861. transaction.onabort = function (event) {
  14862. try {
  14863. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14864. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14865. this.hasReachedQuota = true;
  14866. }
  14867. }
  14868. catch (ex) {
  14869. }
  14870. generateBlobUrl();
  14871. };
  14872. transaction.oncomplete = function (event) {
  14873. generateBlobUrl();
  14874. };
  14875. var newTexture = { textureUrl: url, data: blob };
  14876. try {
  14877. // Put the blob into the dabase
  14878. var addRequest = transaction.objectStore("textures").put(newTexture);
  14879. addRequest.onsuccess = function (event) {
  14880. };
  14881. addRequest.onerror = function (event) {
  14882. generateBlobUrl();
  14883. };
  14884. }
  14885. catch (ex) {
  14886. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14887. if (ex.code === 25) {
  14888. Database.isUASupportingBlobStorage = false;
  14889. }
  14890. image.src = url;
  14891. }
  14892. }
  14893. else {
  14894. image.src = url;
  14895. }
  14896. }, false);
  14897. xhr.addEventListener("error", function (event) {
  14898. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14899. image.src = url;
  14900. }, false);
  14901. xhr.send();
  14902. }
  14903. else {
  14904. image.src = url;
  14905. }
  14906. }
  14907. else {
  14908. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14909. image.src = url;
  14910. }
  14911. };
  14912. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14913. var _this = this;
  14914. var updateVersion = function (event) {
  14915. // the version is not yet in the DB or we need to update it
  14916. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14917. };
  14918. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14919. };
  14920. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14921. var _this = this;
  14922. if (this.isSupported) {
  14923. var version;
  14924. try {
  14925. var transaction = this.db.transaction(["versions"]);
  14926. transaction.oncomplete = function (event) {
  14927. if (version) {
  14928. // If the version in the JSON file is > than the version in DB
  14929. if (_this.manifestVersionFound > version.data) {
  14930. _this.mustUpdateRessources = true;
  14931. updateInDBCallback();
  14932. }
  14933. else {
  14934. callback(version.data);
  14935. }
  14936. }
  14937. else {
  14938. _this.mustUpdateRessources = true;
  14939. updateInDBCallback();
  14940. }
  14941. };
  14942. transaction.onabort = function (event) {
  14943. callback(-1);
  14944. };
  14945. var getRequest = transaction.objectStore("versions").get(url);
  14946. getRequest.onsuccess = function (event) {
  14947. version = (event.target).result;
  14948. };
  14949. getRequest.onerror = function (event) {
  14950. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14951. callback(-1);
  14952. };
  14953. }
  14954. catch (ex) {
  14955. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14956. callback(-1);
  14957. }
  14958. }
  14959. else {
  14960. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14961. callback(-1);
  14962. }
  14963. };
  14964. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14965. var _this = this;
  14966. if (this.isSupported && !this.hasReachedQuota) {
  14967. try {
  14968. // Open a transaction to the database
  14969. var transaction = this.db.transaction(["versions"], "readwrite");
  14970. // the transaction could abort because of a QuotaExceededError error
  14971. transaction.onabort = function (event) {
  14972. try {
  14973. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14974. _this.hasReachedQuota = true;
  14975. }
  14976. }
  14977. catch (ex) {
  14978. }
  14979. callback(-1);
  14980. };
  14981. transaction.oncomplete = function (event) {
  14982. callback(_this.manifestVersionFound);
  14983. };
  14984. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14985. // Put the scene into the database
  14986. var addRequest = transaction.objectStore("versions").put(newVersion);
  14987. addRequest.onsuccess = function (event) {
  14988. };
  14989. addRequest.onerror = function (event) {
  14990. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14991. };
  14992. }
  14993. catch (ex) {
  14994. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14995. callback(-1);
  14996. }
  14997. }
  14998. else {
  14999. callback(-1);
  15000. }
  15001. };
  15002. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15003. var _this = this;
  15004. var completeUrl = Database.ReturnFullUrlLocation(url);
  15005. var saveAndLoadFile = function (event) {
  15006. // the scene is not yet in the DB, let's try to save it
  15007. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15008. };
  15009. this._checkVersionFromDB(completeUrl, function (version) {
  15010. if (version !== -1) {
  15011. if (!_this.mustUpdateRessources) {
  15012. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15013. }
  15014. else {
  15015. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15016. }
  15017. }
  15018. else {
  15019. errorCallback();
  15020. }
  15021. });
  15022. };
  15023. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15024. if (this.isSupported) {
  15025. var targetStore;
  15026. if (url.indexOf(".babylon") !== -1) {
  15027. targetStore = "scenes";
  15028. }
  15029. else {
  15030. targetStore = "textures";
  15031. }
  15032. var file;
  15033. var transaction = this.db.transaction([targetStore]);
  15034. transaction.oncomplete = function (event) {
  15035. if (file) {
  15036. callback(file.data);
  15037. }
  15038. else {
  15039. notInDBCallback();
  15040. }
  15041. };
  15042. transaction.onabort = function (event) {
  15043. notInDBCallback();
  15044. };
  15045. var getRequest = transaction.objectStore(targetStore).get(url);
  15046. getRequest.onsuccess = function (event) {
  15047. file = (event.target).result;
  15048. };
  15049. getRequest.onerror = function (event) {
  15050. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15051. notInDBCallback();
  15052. };
  15053. }
  15054. else {
  15055. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15056. callback();
  15057. }
  15058. };
  15059. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15060. var _this = this;
  15061. if (this.isSupported) {
  15062. var targetStore;
  15063. if (url.indexOf(".babylon") !== -1) {
  15064. targetStore = "scenes";
  15065. }
  15066. else {
  15067. targetStore = "textures";
  15068. }
  15069. // Create XHR
  15070. var xhr = new XMLHttpRequest(), fileData;
  15071. xhr.open("GET", url, true);
  15072. if (useArrayBuffer) {
  15073. xhr.responseType = "arraybuffer";
  15074. }
  15075. xhr.onprogress = progressCallback;
  15076. xhr.addEventListener("load", function () {
  15077. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15078. // Blob as response (XHR2)
  15079. //fileData = xhr.responseText;
  15080. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15081. if (!_this.hasReachedQuota) {
  15082. // Open a transaction to the database
  15083. var transaction = _this.db.transaction([targetStore], "readwrite");
  15084. // the transaction could abort because of a QuotaExceededError error
  15085. transaction.onabort = function (event) {
  15086. try {
  15087. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15088. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15089. this.hasReachedQuota = true;
  15090. }
  15091. }
  15092. catch (ex) {
  15093. }
  15094. callback(fileData);
  15095. };
  15096. transaction.oncomplete = function (event) {
  15097. callback(fileData);
  15098. };
  15099. var newFile;
  15100. if (targetStore === "scenes") {
  15101. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15102. }
  15103. else {
  15104. newFile = { textureUrl: url, data: fileData };
  15105. }
  15106. try {
  15107. // Put the scene into the database
  15108. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15109. addRequest.onsuccess = function (event) {
  15110. };
  15111. addRequest.onerror = function (event) {
  15112. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15113. };
  15114. }
  15115. catch (ex) {
  15116. callback(fileData);
  15117. }
  15118. }
  15119. else {
  15120. callback(fileData);
  15121. }
  15122. }
  15123. else {
  15124. callback();
  15125. }
  15126. }, false);
  15127. xhr.addEventListener("error", function (event) {
  15128. BABYLON.Tools.Error("error on XHR request.");
  15129. callback();
  15130. }, false);
  15131. xhr.send();
  15132. }
  15133. else {
  15134. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15135. callback();
  15136. }
  15137. };
  15138. Database.isUASupportingBlobStorage = true;
  15139. Database.parseURL = function (url) {
  15140. var a = document.createElement('a');
  15141. a.href = url;
  15142. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15143. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15144. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15145. return absLocation;
  15146. };
  15147. Database.ReturnFullUrlLocation = function (url) {
  15148. if (url.indexOf("http:/") === -1) {
  15149. return (BABYLON.Database.parseURL(window.location.href) + url);
  15150. }
  15151. else {
  15152. return url;
  15153. }
  15154. };
  15155. return Database;
  15156. })();
  15157. BABYLON.Database = Database;
  15158. })(BABYLON || (BABYLON = {}));
  15159. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15160. (function (BABYLON) {
  15161. var SpriteManager = (function () {
  15162. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  15163. this.name = name;
  15164. this.cellSize = cellSize;
  15165. this.sprites = new Array();
  15166. this.renderingGroupId = 0;
  15167. this.fogEnabled = true;
  15168. this._vertexDeclaration = [3, 4, 4, 4];
  15169. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15170. this._capacity = capacity;
  15171. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  15172. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15173. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15174. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15175. this._scene = scene;
  15176. this._scene.spriteManagers.push(this);
  15177. // VBO
  15178. this._vertexDeclaration = [3, 4, 4, 4];
  15179. this._vertexStrideSize = 15 * 4;
  15180. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15181. var indices = [];
  15182. var index = 0;
  15183. for (var count = 0; count < capacity; count++) {
  15184. indices.push(index);
  15185. indices.push(index + 1);
  15186. indices.push(index + 2);
  15187. indices.push(index);
  15188. indices.push(index + 2);
  15189. indices.push(index + 3);
  15190. index += 4;
  15191. }
  15192. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15193. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15194. // Effects
  15195. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15196. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15197. }
  15198. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15199. var arrayOffset = index * 15;
  15200. if (offsetX == 0)
  15201. offsetX = this._epsilon;
  15202. else if (offsetX == 1)
  15203. offsetX = 1 - this._epsilon;
  15204. if (offsetY == 0)
  15205. offsetY = this._epsilon;
  15206. else if (offsetY == 1)
  15207. offsetY = 1 - this._epsilon;
  15208. this._vertices[arrayOffset] = sprite.position.x;
  15209. this._vertices[arrayOffset + 1] = sprite.position.y;
  15210. this._vertices[arrayOffset + 2] = sprite.position.z;
  15211. this._vertices[arrayOffset + 3] = sprite.angle;
  15212. this._vertices[arrayOffset + 4] = sprite.size;
  15213. this._vertices[arrayOffset + 5] = offsetX;
  15214. this._vertices[arrayOffset + 6] = offsetY;
  15215. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15216. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15217. var offset = (sprite.cellIndex / rowSize) >> 0;
  15218. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15219. this._vertices[arrayOffset + 10] = offset;
  15220. // Color
  15221. this._vertices[arrayOffset + 11] = sprite.color.r;
  15222. this._vertices[arrayOffset + 12] = sprite.color.g;
  15223. this._vertices[arrayOffset + 13] = sprite.color.b;
  15224. this._vertices[arrayOffset + 14] = sprite.color.a;
  15225. };
  15226. SpriteManager.prototype.render = function () {
  15227. // Check
  15228. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15229. return;
  15230. var engine = this._scene.getEngine();
  15231. var baseSize = this._spriteTexture.getBaseSize();
  15232. // Sprites
  15233. var deltaTime = engine.getDeltaTime();
  15234. var max = Math.min(this._capacity, this.sprites.length);
  15235. var rowSize = baseSize.width / this.cellSize;
  15236. var offset = 0;
  15237. for (var index = 0; index < max; index++) {
  15238. var sprite = this.sprites[index];
  15239. if (!sprite) {
  15240. continue;
  15241. }
  15242. sprite._animate(deltaTime);
  15243. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15244. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15245. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15246. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15247. }
  15248. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15249. // Render
  15250. var effect = this._effectBase;
  15251. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15252. effect = this._effectFog;
  15253. }
  15254. engine.enableEffect(effect);
  15255. var viewMatrix = this._scene.getViewMatrix();
  15256. effect.setTexture("diffuseSampler", this._spriteTexture);
  15257. effect.setMatrix("view", viewMatrix);
  15258. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15259. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15260. // Fog
  15261. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15262. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15263. effect.setColor3("vFogColor", this._scene.fogColor);
  15264. }
  15265. // VBOs
  15266. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15267. // Draw order
  15268. effect.setBool("alphaTest", true);
  15269. engine.setColorWrite(false);
  15270. engine.draw(true, 0, max * 6);
  15271. engine.setColorWrite(true);
  15272. effect.setBool("alphaTest", false);
  15273. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15274. engine.draw(true, 0, max * 6);
  15275. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15276. };
  15277. SpriteManager.prototype.dispose = function () {
  15278. if (this._vertexBuffer) {
  15279. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15280. this._vertexBuffer = null;
  15281. }
  15282. if (this._indexBuffer) {
  15283. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15284. this._indexBuffer = null;
  15285. }
  15286. if (this._spriteTexture) {
  15287. this._spriteTexture.dispose();
  15288. this._spriteTexture = null;
  15289. }
  15290. // Remove from scene
  15291. var index = this._scene.spriteManagers.indexOf(this);
  15292. this._scene.spriteManagers.splice(index, 1);
  15293. // Callback
  15294. if (this.onDispose) {
  15295. this.onDispose();
  15296. }
  15297. };
  15298. return SpriteManager;
  15299. })();
  15300. BABYLON.SpriteManager = SpriteManager;
  15301. })(BABYLON || (BABYLON = {}));
  15302. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15303. (function (BABYLON) {
  15304. var Sprite = (function () {
  15305. function Sprite(name, manager) {
  15306. this.name = name;
  15307. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15308. this.size = 1.0;
  15309. this.angle = 0;
  15310. this.cellIndex = 0;
  15311. this.invertU = 0;
  15312. this.invertV = 0;
  15313. this.animations = new Array();
  15314. this._animationStarted = false;
  15315. this._loopAnimation = false;
  15316. this._fromIndex = 0;
  15317. this._toIndex = 0;
  15318. this._delay = 0;
  15319. this._direction = 1;
  15320. this._frameCount = 0;
  15321. this._time = 0;
  15322. this._manager = manager;
  15323. this._manager.sprites.push(this);
  15324. this.position = BABYLON.Vector3.Zero();
  15325. }
  15326. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15327. this._fromIndex = from;
  15328. this._toIndex = to;
  15329. this._loopAnimation = loop;
  15330. this._delay = delay;
  15331. this._animationStarted = true;
  15332. this._direction = from < to ? 1 : -1;
  15333. this.cellIndex = from;
  15334. this._time = 0;
  15335. };
  15336. Sprite.prototype.stopAnimation = function () {
  15337. this._animationStarted = false;
  15338. };
  15339. Sprite.prototype._animate = function (deltaTime) {
  15340. if (!this._animationStarted)
  15341. return;
  15342. this._time += deltaTime;
  15343. if (this._time > this._delay) {
  15344. this._time = this._time % this._delay;
  15345. this.cellIndex += this._direction;
  15346. if (this.cellIndex == this._toIndex) {
  15347. if (this._loopAnimation) {
  15348. this.cellIndex = this._fromIndex;
  15349. }
  15350. else {
  15351. this._animationStarted = false;
  15352. if (this.disposeWhenFinishedAnimating) {
  15353. this.dispose();
  15354. }
  15355. }
  15356. }
  15357. }
  15358. };
  15359. Sprite.prototype.dispose = function () {
  15360. for (var i = 0; i < this._manager.sprites.length; i++) {
  15361. if (this._manager.sprites[i] == this) {
  15362. this._manager.sprites.splice(i, 1);
  15363. }
  15364. }
  15365. };
  15366. return Sprite;
  15367. })();
  15368. BABYLON.Sprite = Sprite;
  15369. })(BABYLON || (BABYLON = {}));
  15370. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15371. (function (BABYLON) {
  15372. var Layer = (function () {
  15373. function Layer(name, imgUrl, scene, isBackground, color) {
  15374. this.name = name;
  15375. this._vertexDeclaration = [2];
  15376. this._vertexStrideSize = 2 * 4;
  15377. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15378. this.isBackground = isBackground === undefined ? true : isBackground;
  15379. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15380. this._scene = scene;
  15381. this._scene.layers.push(this);
  15382. // VBO
  15383. var vertices = [];
  15384. vertices.push(1, 1);
  15385. vertices.push(-1, 1);
  15386. vertices.push(-1, -1);
  15387. vertices.push(1, -1);
  15388. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15389. // Indices
  15390. var indices = [];
  15391. indices.push(0);
  15392. indices.push(1);
  15393. indices.push(2);
  15394. indices.push(0);
  15395. indices.push(2);
  15396. indices.push(3);
  15397. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15398. // Effects
  15399. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15400. }
  15401. Layer.prototype.render = function () {
  15402. // Check
  15403. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15404. return;
  15405. var engine = this._scene.getEngine();
  15406. // Render
  15407. engine.enableEffect(this._effect);
  15408. engine.setState(false);
  15409. // Texture
  15410. this._effect.setTexture("textureSampler", this.texture);
  15411. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15412. // Color
  15413. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15414. // VBOs
  15415. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15416. // Draw order
  15417. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15418. engine.draw(true, 0, 6);
  15419. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15420. };
  15421. Layer.prototype.dispose = function () {
  15422. if (this._vertexBuffer) {
  15423. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15424. this._vertexBuffer = null;
  15425. }
  15426. if (this._indexBuffer) {
  15427. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15428. this._indexBuffer = null;
  15429. }
  15430. if (this.texture) {
  15431. this.texture.dispose();
  15432. this.texture = null;
  15433. }
  15434. // Remove from scene
  15435. var index = this._scene.layers.indexOf(this);
  15436. this._scene.layers.splice(index, 1);
  15437. // Callback
  15438. if (this.onDispose) {
  15439. this.onDispose();
  15440. }
  15441. };
  15442. return Layer;
  15443. })();
  15444. BABYLON.Layer = Layer;
  15445. })(BABYLON || (BABYLON = {}));
  15446. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15447. (function (BABYLON) {
  15448. var Particle = (function () {
  15449. function Particle() {
  15450. this.position = BABYLON.Vector3.Zero();
  15451. this.direction = BABYLON.Vector3.Zero();
  15452. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15453. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15454. this.lifeTime = 1.0;
  15455. this.age = 0;
  15456. this.size = 0;
  15457. this.angle = 0;
  15458. this.angularSpeed = 0;
  15459. }
  15460. Particle.prototype.copyTo = function (other) {
  15461. other.position.copyFrom(this.position);
  15462. other.direction.copyFrom(this.direction);
  15463. other.color.copyFrom(this.color);
  15464. other.colorStep.copyFrom(this.colorStep);
  15465. other.lifeTime = this.lifeTime;
  15466. other.age = this.age;
  15467. other.size = this.size;
  15468. other.angle = this.angle;
  15469. other.angularSpeed = this.angularSpeed;
  15470. };
  15471. return Particle;
  15472. })();
  15473. BABYLON.Particle = Particle;
  15474. })(BABYLON || (BABYLON = {}));
  15475. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15476. (function (BABYLON) {
  15477. var randomNumber = function (min, max) {
  15478. if (min === max) {
  15479. return (min);
  15480. }
  15481. var random = Math.random();
  15482. return ((random * (max - min)) + min);
  15483. };
  15484. var ParticleSystem = (function () {
  15485. function ParticleSystem(name, capacity, scene, customEffect) {
  15486. var _this = this;
  15487. this.name = name;
  15488. this.renderingGroupId = 0;
  15489. this.emitter = null;
  15490. this.emitRate = 10;
  15491. this.manualEmitCount = -1;
  15492. this.updateSpeed = 0.01;
  15493. this.targetStopDuration = 0;
  15494. this.disposeOnStop = false;
  15495. this.minEmitPower = 1;
  15496. this.maxEmitPower = 1;
  15497. this.minLifeTime = 1;
  15498. this.maxLifeTime = 1;
  15499. this.minSize = 1;
  15500. this.maxSize = 1;
  15501. this.minAngularSpeed = 0;
  15502. this.maxAngularSpeed = 0;
  15503. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15504. this.forceDepthWrite = false;
  15505. this.gravity = BABYLON.Vector3.Zero();
  15506. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15507. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15508. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15509. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15510. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15511. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15512. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15513. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15514. this.particles = new Array();
  15515. this._vertexDeclaration = [3, 4, 4];
  15516. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15517. this._stockParticles = new Array();
  15518. this._newPartsExcess = 0;
  15519. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15520. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15521. this._scaledDirection = BABYLON.Vector3.Zero();
  15522. this._scaledGravity = BABYLON.Vector3.Zero();
  15523. this._currentRenderId = -1;
  15524. this._started = false;
  15525. this._stopped = false;
  15526. this._actualFrame = 0;
  15527. this.id = name;
  15528. this._capacity = capacity;
  15529. this._scene = scene;
  15530. this._customEffect = customEffect;
  15531. scene.particleSystems.push(this);
  15532. // VBO
  15533. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15534. var indices = [];
  15535. var index = 0;
  15536. for (var count = 0; count < capacity; count++) {
  15537. indices.push(index);
  15538. indices.push(index + 1);
  15539. indices.push(index + 2);
  15540. indices.push(index);
  15541. indices.push(index + 2);
  15542. indices.push(index + 3);
  15543. index += 4;
  15544. }
  15545. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15546. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15547. // Default behaviors
  15548. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15549. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15550. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15551. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15552. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15553. };
  15554. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15555. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15556. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15557. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15559. };
  15560. this.updateFunction = function (particles) {
  15561. for (var index = 0; index < particles.length; index++) {
  15562. var particle = particles[index];
  15563. particle.age += _this._scaledUpdateSpeed;
  15564. if (particle.age >= particle.lifeTime) {
  15565. _this.recycleParticle(particle);
  15566. index--;
  15567. continue;
  15568. }
  15569. else {
  15570. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15571. particle.color.addInPlace(_this._scaledColorStep);
  15572. if (particle.color.a < 0)
  15573. particle.color.a = 0;
  15574. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15575. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15576. particle.position.addInPlace(_this._scaledDirection);
  15577. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15578. particle.direction.addInPlace(_this._scaledGravity);
  15579. }
  15580. }
  15581. };
  15582. }
  15583. ParticleSystem.prototype.recycleParticle = function (particle) {
  15584. var lastParticle = this.particles.pop();
  15585. if (lastParticle !== particle) {
  15586. lastParticle.copyTo(particle);
  15587. this._stockParticles.push(lastParticle);
  15588. }
  15589. };
  15590. ParticleSystem.prototype.getCapacity = function () {
  15591. return this._capacity;
  15592. };
  15593. ParticleSystem.prototype.isAlive = function () {
  15594. return this._alive;
  15595. };
  15596. ParticleSystem.prototype.isStarted = function () {
  15597. return this._started;
  15598. };
  15599. ParticleSystem.prototype.start = function () {
  15600. this._started = true;
  15601. this._stopped = false;
  15602. this._actualFrame = 0;
  15603. };
  15604. ParticleSystem.prototype.stop = function () {
  15605. this._stopped = true;
  15606. };
  15607. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15608. var offset = index * 11;
  15609. this._vertices[offset] = particle.position.x;
  15610. this._vertices[offset + 1] = particle.position.y;
  15611. this._vertices[offset + 2] = particle.position.z;
  15612. this._vertices[offset + 3] = particle.color.r;
  15613. this._vertices[offset + 4] = particle.color.g;
  15614. this._vertices[offset + 5] = particle.color.b;
  15615. this._vertices[offset + 6] = particle.color.a;
  15616. this._vertices[offset + 7] = particle.angle;
  15617. this._vertices[offset + 8] = particle.size;
  15618. this._vertices[offset + 9] = offsetX;
  15619. this._vertices[offset + 10] = offsetY;
  15620. };
  15621. ParticleSystem.prototype._update = function (newParticles) {
  15622. // Update current
  15623. this._alive = this.particles.length > 0;
  15624. this.updateFunction(this.particles);
  15625. // Add new ones
  15626. var worldMatrix;
  15627. if (this.emitter.position) {
  15628. worldMatrix = this.emitter.getWorldMatrix();
  15629. }
  15630. else {
  15631. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15632. }
  15633. for (var index = 0; index < newParticles; index++) {
  15634. if (this.particles.length === this._capacity) {
  15635. break;
  15636. }
  15637. if (this._stockParticles.length !== 0) {
  15638. var particle = this._stockParticles.pop();
  15639. particle.age = 0;
  15640. }
  15641. else {
  15642. particle = new BABYLON.Particle();
  15643. }
  15644. this.particles.push(particle);
  15645. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15646. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15647. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15648. particle.size = randomNumber(this.minSize, this.maxSize);
  15649. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15650. this.startPositionFunction(worldMatrix, particle.position);
  15651. var step = randomNumber(0, 1.0);
  15652. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15653. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15654. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15655. }
  15656. };
  15657. ParticleSystem.prototype._getEffect = function () {
  15658. if (this._customEffect) {
  15659. return this._customEffect;
  15660. }
  15661. ;
  15662. var defines = [];
  15663. if (this._scene.clipPlane) {
  15664. defines.push("#define CLIPPLANE");
  15665. }
  15666. // Effect
  15667. var join = defines.join("\n");
  15668. if (this._cachedDefines !== join) {
  15669. this._cachedDefines = join;
  15670. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15671. }
  15672. return this._effect;
  15673. };
  15674. ParticleSystem.prototype.animate = function () {
  15675. if (!this._started)
  15676. return;
  15677. var effect = this._getEffect();
  15678. // Check
  15679. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15680. return;
  15681. if (this._currentRenderId === this._scene.getRenderId()) {
  15682. return;
  15683. }
  15684. this._currentRenderId = this._scene.getRenderId();
  15685. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15686. // determine the number of particles we need to create
  15687. var emitCout;
  15688. if (this.manualEmitCount > -1) {
  15689. emitCout = this.manualEmitCount;
  15690. this.manualEmitCount = 0;
  15691. }
  15692. else {
  15693. emitCout = this.emitRate;
  15694. }
  15695. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15696. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15697. if (this._newPartsExcess > 1.0) {
  15698. newParticles += this._newPartsExcess >> 0;
  15699. this._newPartsExcess -= this._newPartsExcess >> 0;
  15700. }
  15701. this._alive = false;
  15702. if (!this._stopped) {
  15703. this._actualFrame += this._scaledUpdateSpeed;
  15704. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15705. this.stop();
  15706. }
  15707. else {
  15708. newParticles = 0;
  15709. }
  15710. this._update(newParticles);
  15711. // Stopped?
  15712. if (this._stopped) {
  15713. if (!this._alive) {
  15714. this._started = false;
  15715. if (this.disposeOnStop) {
  15716. this._scene._toBeDisposed.push(this);
  15717. }
  15718. }
  15719. }
  15720. // Update VBO
  15721. var offset = 0;
  15722. for (var index = 0; index < this.particles.length; index++) {
  15723. var particle = this.particles[index];
  15724. this._appendParticleVertex(offset++, particle, 0, 0);
  15725. this._appendParticleVertex(offset++, particle, 1, 0);
  15726. this._appendParticleVertex(offset++, particle, 1, 1);
  15727. this._appendParticleVertex(offset++, particle, 0, 1);
  15728. }
  15729. var engine = this._scene.getEngine();
  15730. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15731. };
  15732. ParticleSystem.prototype.render = function () {
  15733. var effect = this._getEffect();
  15734. // Check
  15735. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15736. return 0;
  15737. var engine = this._scene.getEngine();
  15738. // Render
  15739. engine.enableEffect(effect);
  15740. engine.setState(false);
  15741. var viewMatrix = this._scene.getViewMatrix();
  15742. effect.setTexture("diffuseSampler", this.particleTexture);
  15743. effect.setMatrix("view", viewMatrix);
  15744. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15745. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15746. if (this._scene.clipPlane) {
  15747. var clipPlane = this._scene.clipPlane;
  15748. var invView = viewMatrix.clone();
  15749. invView.invert();
  15750. effect.setMatrix("invView", invView);
  15751. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15752. }
  15753. // VBOs
  15754. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15755. // Draw order
  15756. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15757. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15758. }
  15759. else {
  15760. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15761. }
  15762. if (this.forceDepthWrite) {
  15763. engine.setDepthWrite(true);
  15764. }
  15765. engine.draw(true, 0, this.particles.length * 6);
  15766. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15767. return this.particles.length;
  15768. };
  15769. ParticleSystem.prototype.dispose = function () {
  15770. if (this._vertexBuffer) {
  15771. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15772. this._vertexBuffer = null;
  15773. }
  15774. if (this._indexBuffer) {
  15775. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15776. this._indexBuffer = null;
  15777. }
  15778. if (this.particleTexture) {
  15779. this.particleTexture.dispose();
  15780. this.particleTexture = null;
  15781. }
  15782. // Remove from scene
  15783. var index = this._scene.particleSystems.indexOf(this);
  15784. this._scene.particleSystems.splice(index, 1);
  15785. // Callback
  15786. if (this.onDispose) {
  15787. this.onDispose();
  15788. }
  15789. };
  15790. // Clone
  15791. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15792. var result = new ParticleSystem(name, this._capacity, this._scene);
  15793. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15794. if (newEmitter === undefined) {
  15795. newEmitter = this.emitter;
  15796. }
  15797. result.emitter = newEmitter;
  15798. if (this.particleTexture) {
  15799. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15800. }
  15801. result.start();
  15802. return result;
  15803. };
  15804. // Statics
  15805. ParticleSystem.BLENDMODE_ONEONE = 0;
  15806. ParticleSystem.BLENDMODE_STANDARD = 1;
  15807. return ParticleSystem;
  15808. })();
  15809. BABYLON.ParticleSystem = ParticleSystem;
  15810. })(BABYLON || (BABYLON = {}));
  15811. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15812. (function (BABYLON) {
  15813. var Animation = (function () {
  15814. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15815. this.name = name;
  15816. this.targetProperty = targetProperty;
  15817. this.framePerSecond = framePerSecond;
  15818. this.dataType = dataType;
  15819. this.loopMode = loopMode;
  15820. this._offsetsCache = {};
  15821. this._highLimitsCache = {};
  15822. this._stopped = false;
  15823. this.targetPropertyPath = targetProperty.split(".");
  15824. this.dataType = dataType;
  15825. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15826. }
  15827. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15828. var dataType = undefined;
  15829. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15830. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15831. }
  15832. else if (from instanceof BABYLON.Quaternion) {
  15833. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15834. }
  15835. else if (from instanceof BABYLON.Vector3) {
  15836. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15837. }
  15838. else if (from instanceof BABYLON.Vector2) {
  15839. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15840. }
  15841. else if (from instanceof BABYLON.Color3) {
  15842. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15843. }
  15844. if (dataType == undefined) {
  15845. return null;
  15846. }
  15847. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15848. var keys = [];
  15849. keys.push({ frame: 0, value: from });
  15850. keys.push({ frame: totalFrame, value: to });
  15851. animation.setKeys(keys);
  15852. mesh.animations.push(animation);
  15853. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15854. };
  15855. // Methods
  15856. Animation.prototype.isStopped = function () {
  15857. return this._stopped;
  15858. };
  15859. Animation.prototype.getKeys = function () {
  15860. return this._keys;
  15861. };
  15862. Animation.prototype.getEasingFunction = function () {
  15863. return this._easingFunction;
  15864. };
  15865. Animation.prototype.setEasingFunction = function (easingFunction) {
  15866. this._easingFunction = easingFunction;
  15867. };
  15868. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15869. return startValue + (endValue - startValue) * gradient;
  15870. };
  15871. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15872. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15873. };
  15874. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15875. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15876. };
  15877. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15878. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15879. };
  15880. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15881. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15882. };
  15883. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15884. var startScale = new BABYLON.Vector3(0, 0, 0);
  15885. var startRotation = new BABYLON.Quaternion();
  15886. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15887. startValue.decompose(startScale, startRotation, startTranslation);
  15888. var endScale = new BABYLON.Vector3(0, 0, 0);
  15889. var endRotation = new BABYLON.Quaternion();
  15890. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15891. endValue.decompose(endScale, endRotation, endTranslation);
  15892. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15893. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15894. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15895. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15896. return result;
  15897. };
  15898. Animation.prototype.clone = function () {
  15899. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15900. clone.setKeys(this._keys);
  15901. return clone;
  15902. };
  15903. Animation.prototype.setKeys = function (values) {
  15904. this._keys = values.slice(0);
  15905. this._offsetsCache = {};
  15906. this._highLimitsCache = {};
  15907. };
  15908. Animation.prototype._getKeyValue = function (value) {
  15909. if (typeof value === "function") {
  15910. return value();
  15911. }
  15912. return value;
  15913. };
  15914. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15915. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15916. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15917. }
  15918. this.currentFrame = currentFrame;
  15919. for (var key = 0; key < this._keys.length; key++) {
  15920. // for each frame, we need the key just before the frame superior
  15921. if (this._keys[key + 1].frame >= currentFrame) {
  15922. var startValue = this._getKeyValue(this._keys[key].value);
  15923. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15924. // gradient : percent of currentFrame between the frame inf and the frame sup
  15925. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15926. // check for easingFunction and correction of gradient
  15927. if (this._easingFunction != null) {
  15928. gradient = this._easingFunction.ease(gradient);
  15929. }
  15930. switch (this.dataType) {
  15931. case Animation.ANIMATIONTYPE_FLOAT:
  15932. switch (loopMode) {
  15933. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15934. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15935. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15936. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15937. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15938. }
  15939. break;
  15940. case Animation.ANIMATIONTYPE_QUATERNION:
  15941. var quaternion = null;
  15942. switch (loopMode) {
  15943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15945. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15946. break;
  15947. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15948. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15949. break;
  15950. }
  15951. return quaternion;
  15952. case Animation.ANIMATIONTYPE_VECTOR3:
  15953. switch (loopMode) {
  15954. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15955. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15956. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15957. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15958. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15959. }
  15960. case Animation.ANIMATIONTYPE_VECTOR2:
  15961. switch (loopMode) {
  15962. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15963. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15964. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15965. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15966. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15967. }
  15968. case Animation.ANIMATIONTYPE_COLOR3:
  15969. switch (loopMode) {
  15970. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15971. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15972. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15973. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15974. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15975. }
  15976. case Animation.ANIMATIONTYPE_MATRIX:
  15977. switch (loopMode) {
  15978. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15979. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15980. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15981. return startValue;
  15982. }
  15983. default:
  15984. break;
  15985. }
  15986. break;
  15987. }
  15988. }
  15989. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15990. };
  15991. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15992. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15993. this._stopped = true;
  15994. return false;
  15995. }
  15996. var returnValue = true;
  15997. // Adding a start key at frame 0 if missing
  15998. if (this._keys[0].frame !== 0) {
  15999. var newKey = { frame: 0, value: this._keys[0].value };
  16000. this._keys.splice(0, 0, newKey);
  16001. }
  16002. // Check limits
  16003. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16004. from = this._keys[0].frame;
  16005. }
  16006. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16007. to = this._keys[this._keys.length - 1].frame;
  16008. }
  16009. // Compute ratio
  16010. var range = to - from;
  16011. var offsetValue;
  16012. // ratio represents the frame delta between from and to
  16013. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16014. var highLimitValue = 0;
  16015. if (ratio > range && !loop) {
  16016. returnValue = false;
  16017. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16018. }
  16019. else {
  16020. // Get max value if required
  16021. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16022. var keyOffset = to.toString() + from.toString();
  16023. if (!this._offsetsCache[keyOffset]) {
  16024. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16025. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16026. switch (this.dataType) {
  16027. case Animation.ANIMATIONTYPE_FLOAT:
  16028. this._offsetsCache[keyOffset] = toValue - fromValue;
  16029. break;
  16030. case Animation.ANIMATIONTYPE_QUATERNION:
  16031. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16032. break;
  16033. case Animation.ANIMATIONTYPE_VECTOR3:
  16034. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16035. case Animation.ANIMATIONTYPE_VECTOR2:
  16036. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16037. case Animation.ANIMATIONTYPE_COLOR3:
  16038. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16039. default:
  16040. break;
  16041. }
  16042. this._highLimitsCache[keyOffset] = toValue;
  16043. }
  16044. highLimitValue = this._highLimitsCache[keyOffset];
  16045. offsetValue = this._offsetsCache[keyOffset];
  16046. }
  16047. }
  16048. if (offsetValue === undefined) {
  16049. switch (this.dataType) {
  16050. case Animation.ANIMATIONTYPE_FLOAT:
  16051. offsetValue = 0;
  16052. break;
  16053. case Animation.ANIMATIONTYPE_QUATERNION:
  16054. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16055. break;
  16056. case Animation.ANIMATIONTYPE_VECTOR3:
  16057. offsetValue = BABYLON.Vector3.Zero();
  16058. break;
  16059. case Animation.ANIMATIONTYPE_VECTOR2:
  16060. offsetValue = BABYLON.Vector2.Zero();
  16061. break;
  16062. case Animation.ANIMATIONTYPE_COLOR3:
  16063. offsetValue = BABYLON.Color3.Black();
  16064. }
  16065. }
  16066. // Compute value
  16067. var repeatCount = (ratio / range) >> 0;
  16068. var currentFrame = returnValue ? from + ratio % range : to;
  16069. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16070. // Set value
  16071. if (this.targetPropertyPath.length > 1) {
  16072. var property = this._target[this.targetPropertyPath[0]];
  16073. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16074. property = property[this.targetPropertyPath[index]];
  16075. }
  16076. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16077. }
  16078. else {
  16079. this._target[this.targetPropertyPath[0]] = currentValue;
  16080. }
  16081. if (this._target.markAsDirty) {
  16082. this._target.markAsDirty(this.targetProperty);
  16083. }
  16084. if (!returnValue) {
  16085. this._stopped = true;
  16086. }
  16087. return returnValue;
  16088. };
  16089. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16090. get: function () {
  16091. return Animation._ANIMATIONTYPE_FLOAT;
  16092. },
  16093. enumerable: true,
  16094. configurable: true
  16095. });
  16096. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16097. get: function () {
  16098. return Animation._ANIMATIONTYPE_VECTOR3;
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16104. get: function () {
  16105. return Animation._ANIMATIONTYPE_VECTOR2;
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16111. get: function () {
  16112. return Animation._ANIMATIONTYPE_QUATERNION;
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16118. get: function () {
  16119. return Animation._ANIMATIONTYPE_MATRIX;
  16120. },
  16121. enumerable: true,
  16122. configurable: true
  16123. });
  16124. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16125. get: function () {
  16126. return Animation._ANIMATIONTYPE_COLOR3;
  16127. },
  16128. enumerable: true,
  16129. configurable: true
  16130. });
  16131. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16132. get: function () {
  16133. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16134. },
  16135. enumerable: true,
  16136. configurable: true
  16137. });
  16138. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16139. get: function () {
  16140. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16141. },
  16142. enumerable: true,
  16143. configurable: true
  16144. });
  16145. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16146. get: function () {
  16147. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. // Statics
  16153. Animation._ANIMATIONTYPE_FLOAT = 0;
  16154. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16155. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16156. Animation._ANIMATIONTYPE_MATRIX = 3;
  16157. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16158. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16159. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16160. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16161. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16162. return Animation;
  16163. })();
  16164. BABYLON.Animation = Animation;
  16165. })(BABYLON || (BABYLON = {}));
  16166. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16167. (function (BABYLON) {
  16168. var Animatable = (function () {
  16169. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16170. if (fromFrame === void 0) { fromFrame = 0; }
  16171. if (toFrame === void 0) { toFrame = 100; }
  16172. if (loopAnimation === void 0) { loopAnimation = false; }
  16173. if (speedRatio === void 0) { speedRatio = 1.0; }
  16174. this.target = target;
  16175. this.fromFrame = fromFrame;
  16176. this.toFrame = toFrame;
  16177. this.loopAnimation = loopAnimation;
  16178. this.speedRatio = speedRatio;
  16179. this.onAnimationEnd = onAnimationEnd;
  16180. this._animations = new Array();
  16181. this._paused = false;
  16182. this.animationStarted = false;
  16183. if (animations) {
  16184. this.appendAnimations(target, animations);
  16185. }
  16186. this._scene = scene;
  16187. scene._activeAnimatables.push(this);
  16188. }
  16189. // Methods
  16190. Animatable.prototype.appendAnimations = function (target, animations) {
  16191. for (var index = 0; index < animations.length; index++) {
  16192. var animation = animations[index];
  16193. animation._target = target;
  16194. this._animations.push(animation);
  16195. }
  16196. };
  16197. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16198. var animations = this._animations;
  16199. for (var index = 0; index < animations.length; index++) {
  16200. if (animations[index].targetProperty === property) {
  16201. return animations[index];
  16202. }
  16203. }
  16204. return null;
  16205. };
  16206. Animatable.prototype.pause = function () {
  16207. if (this._paused) {
  16208. return;
  16209. }
  16210. this._paused = true;
  16211. };
  16212. Animatable.prototype.restart = function () {
  16213. this._paused = false;
  16214. };
  16215. Animatable.prototype.stop = function () {
  16216. var index = this._scene._activeAnimatables.indexOf(this);
  16217. if (index > -1) {
  16218. this._scene._activeAnimatables.splice(index, 1);
  16219. }
  16220. if (this.onAnimationEnd) {
  16221. this.onAnimationEnd();
  16222. }
  16223. };
  16224. Animatable.prototype._animate = function (delay) {
  16225. if (this._paused) {
  16226. if (!this._pausedDelay) {
  16227. this._pausedDelay = delay;
  16228. }
  16229. return true;
  16230. }
  16231. if (!this._localDelayOffset) {
  16232. this._localDelayOffset = delay;
  16233. }
  16234. else if (this._pausedDelay) {
  16235. this._localDelayOffset += delay - this._pausedDelay;
  16236. this._pausedDelay = null;
  16237. }
  16238. // Animating
  16239. var running = false;
  16240. var animations = this._animations;
  16241. for (var index = 0; index < animations.length; index++) {
  16242. var animation = animations[index];
  16243. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16244. running = running || isRunning;
  16245. }
  16246. if (!running && this.onAnimationEnd) {
  16247. this.onAnimationEnd();
  16248. }
  16249. return running;
  16250. };
  16251. return Animatable;
  16252. })();
  16253. BABYLON.Animatable = Animatable;
  16254. })(BABYLON || (BABYLON = {}));
  16255. //# sourceMappingURL=babylon.animatable.js.map
  16256. var BABYLON;
  16257. (function (BABYLON) {
  16258. var EasingFunction = (function () {
  16259. function EasingFunction() {
  16260. // Properties
  16261. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16262. }
  16263. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16264. get: function () {
  16265. return EasingFunction._EASINGMODE_EASEIN;
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16271. get: function () {
  16272. return EasingFunction._EASINGMODE_EASEOUT;
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16278. get: function () {
  16279. return EasingFunction._EASINGMODE_EASEINOUT;
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16285. var n = Math.min(Math.max(easingMode, 0), 2);
  16286. this._easingMode = n;
  16287. };
  16288. EasingFunction.prototype.getEasingMode = function () {
  16289. return this._easingMode;
  16290. };
  16291. EasingFunction.prototype.easeInCore = function (gradient) {
  16292. throw new Error('You must implement this method');
  16293. };
  16294. EasingFunction.prototype.ease = function (gradient) {
  16295. switch (this._easingMode) {
  16296. case EasingFunction.EASINGMODE_EASEIN:
  16297. return this.easeInCore(gradient);
  16298. case EasingFunction.EASINGMODE_EASEOUT:
  16299. return (1 - this.easeInCore(1 - gradient));
  16300. }
  16301. if (gradient >= 0.5) {
  16302. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16303. }
  16304. return (this.easeInCore(gradient * 2) * 0.5);
  16305. };
  16306. //Statics
  16307. EasingFunction._EASINGMODE_EASEIN = 0;
  16308. EasingFunction._EASINGMODE_EASEOUT = 1;
  16309. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16310. return EasingFunction;
  16311. })();
  16312. BABYLON.EasingFunction = EasingFunction;
  16313. var CircleEase = (function (_super) {
  16314. __extends(CircleEase, _super);
  16315. function CircleEase() {
  16316. _super.apply(this, arguments);
  16317. }
  16318. CircleEase.prototype.easeInCore = function (gradient) {
  16319. gradient = Math.max(0, Math.min(1, gradient));
  16320. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16321. };
  16322. return CircleEase;
  16323. })(EasingFunction);
  16324. BABYLON.CircleEase = CircleEase;
  16325. var BackEase = (function (_super) {
  16326. __extends(BackEase, _super);
  16327. function BackEase(amplitude) {
  16328. if (amplitude === void 0) { amplitude = 1; }
  16329. _super.call(this);
  16330. this.amplitude = amplitude;
  16331. }
  16332. BackEase.prototype.easeInCore = function (gradient) {
  16333. var num = Math.max(0, this.amplitude);
  16334. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16335. };
  16336. return BackEase;
  16337. })(EasingFunction);
  16338. BABYLON.BackEase = BackEase;
  16339. var BounceEase = (function (_super) {
  16340. __extends(BounceEase, _super);
  16341. function BounceEase(bounces, bounciness) {
  16342. if (bounces === void 0) { bounces = 3; }
  16343. if (bounciness === void 0) { bounciness = 2; }
  16344. _super.call(this);
  16345. this.bounces = bounces;
  16346. this.bounciness = bounciness;
  16347. }
  16348. BounceEase.prototype.easeInCore = function (gradient) {
  16349. var y = Math.max(0.0, this.bounces);
  16350. var bounciness = this.bounciness;
  16351. if (bounciness <= 1.0) {
  16352. bounciness = 1.001;
  16353. }
  16354. var num9 = Math.pow(bounciness, y);
  16355. var num5 = 1.0 - bounciness;
  16356. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16357. var num15 = gradient * num4;
  16358. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16359. var num3 = Math.floor(num65);
  16360. var num13 = num3 + 1.0;
  16361. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16362. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16363. var num7 = (num8 + num12) * 0.5;
  16364. var num6 = gradient - num7;
  16365. var num2 = num7 - num8;
  16366. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16367. };
  16368. return BounceEase;
  16369. })(EasingFunction);
  16370. BABYLON.BounceEase = BounceEase;
  16371. var CubicEase = (function (_super) {
  16372. __extends(CubicEase, _super);
  16373. function CubicEase() {
  16374. _super.apply(this, arguments);
  16375. }
  16376. CubicEase.prototype.easeInCore = function (gradient) {
  16377. return (gradient * gradient * gradient);
  16378. };
  16379. return CubicEase;
  16380. })(EasingFunction);
  16381. BABYLON.CubicEase = CubicEase;
  16382. var ElasticEase = (function (_super) {
  16383. __extends(ElasticEase, _super);
  16384. function ElasticEase(oscillations, springiness) {
  16385. if (oscillations === void 0) { oscillations = 3; }
  16386. if (springiness === void 0) { springiness = 3; }
  16387. _super.call(this);
  16388. this.oscillations = oscillations;
  16389. this.springiness = springiness;
  16390. }
  16391. ElasticEase.prototype.easeInCore = function (gradient) {
  16392. var num2;
  16393. var num3 = Math.max(0.0, this.oscillations);
  16394. var num = Math.max(0.0, this.springiness);
  16395. if (num == 0) {
  16396. num2 = gradient;
  16397. }
  16398. else {
  16399. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16400. }
  16401. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16402. };
  16403. return ElasticEase;
  16404. })(EasingFunction);
  16405. BABYLON.ElasticEase = ElasticEase;
  16406. var ExponentialEase = (function (_super) {
  16407. __extends(ExponentialEase, _super);
  16408. function ExponentialEase(exponent) {
  16409. if (exponent === void 0) { exponent = 2; }
  16410. _super.call(this);
  16411. this.exponent = exponent;
  16412. }
  16413. ExponentialEase.prototype.easeInCore = function (gradient) {
  16414. if (this.exponent <= 0) {
  16415. return gradient;
  16416. }
  16417. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16418. };
  16419. return ExponentialEase;
  16420. })(EasingFunction);
  16421. BABYLON.ExponentialEase = ExponentialEase;
  16422. var PowerEase = (function (_super) {
  16423. __extends(PowerEase, _super);
  16424. function PowerEase(power) {
  16425. if (power === void 0) { power = 2; }
  16426. _super.call(this);
  16427. this.power = power;
  16428. }
  16429. PowerEase.prototype.easeInCore = function (gradient) {
  16430. var y = Math.max(0.0, this.power);
  16431. return Math.pow(gradient, y);
  16432. };
  16433. return PowerEase;
  16434. })(EasingFunction);
  16435. BABYLON.PowerEase = PowerEase;
  16436. var QuadraticEase = (function (_super) {
  16437. __extends(QuadraticEase, _super);
  16438. function QuadraticEase() {
  16439. _super.apply(this, arguments);
  16440. }
  16441. QuadraticEase.prototype.easeInCore = function (gradient) {
  16442. return (gradient * gradient);
  16443. };
  16444. return QuadraticEase;
  16445. })(EasingFunction);
  16446. BABYLON.QuadraticEase = QuadraticEase;
  16447. var QuarticEase = (function (_super) {
  16448. __extends(QuarticEase, _super);
  16449. function QuarticEase() {
  16450. _super.apply(this, arguments);
  16451. }
  16452. QuarticEase.prototype.easeInCore = function (gradient) {
  16453. return (gradient * gradient * gradient * gradient);
  16454. };
  16455. return QuarticEase;
  16456. })(EasingFunction);
  16457. BABYLON.QuarticEase = QuarticEase;
  16458. var QuinticEase = (function (_super) {
  16459. __extends(QuinticEase, _super);
  16460. function QuinticEase() {
  16461. _super.apply(this, arguments);
  16462. }
  16463. QuinticEase.prototype.easeInCore = function (gradient) {
  16464. return (gradient * gradient * gradient * gradient * gradient);
  16465. };
  16466. return QuinticEase;
  16467. })(EasingFunction);
  16468. BABYLON.QuinticEase = QuinticEase;
  16469. var SineEase = (function (_super) {
  16470. __extends(SineEase, _super);
  16471. function SineEase() {
  16472. _super.apply(this, arguments);
  16473. }
  16474. SineEase.prototype.easeInCore = function (gradient) {
  16475. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16476. };
  16477. return SineEase;
  16478. })(EasingFunction);
  16479. BABYLON.SineEase = SineEase;
  16480. var BezierCurveEase = (function (_super) {
  16481. __extends(BezierCurveEase, _super);
  16482. function BezierCurveEase(x1, y1, x2, y2) {
  16483. if (x1 === void 0) { x1 = 0; }
  16484. if (y1 === void 0) { y1 = 0; }
  16485. if (x2 === void 0) { x2 = 1; }
  16486. if (y2 === void 0) { y2 = 1; }
  16487. _super.call(this);
  16488. this.x1 = x1;
  16489. this.y1 = y1;
  16490. this.x2 = x2;
  16491. this.y2 = y2;
  16492. }
  16493. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16494. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16495. };
  16496. return BezierCurveEase;
  16497. })(EasingFunction);
  16498. BABYLON.BezierCurveEase = BezierCurveEase;
  16499. })(BABYLON || (BABYLON = {}));
  16500. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16501. (function (BABYLON) {
  16502. var Octree = (function () {
  16503. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16504. if (maxDepth === void 0) { maxDepth = 2; }
  16505. this.maxDepth = maxDepth;
  16506. this.dynamicContent = new Array();
  16507. this._maxBlockCapacity = maxBlockCapacity || 64;
  16508. this._selectionContent = new BABYLON.SmartArray(1024);
  16509. this._creationFunc = creationFunc;
  16510. }
  16511. // Methods
  16512. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16513. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16514. };
  16515. Octree.prototype.addMesh = function (entry) {
  16516. for (var index = 0; index < this.blocks.length; index++) {
  16517. var block = this.blocks[index];
  16518. block.addEntry(entry);
  16519. }
  16520. };
  16521. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16522. this._selectionContent.reset();
  16523. for (var index = 0; index < this.blocks.length; index++) {
  16524. var block = this.blocks[index];
  16525. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16526. }
  16527. if (allowDuplicate) {
  16528. this._selectionContent.concat(this.dynamicContent);
  16529. }
  16530. else {
  16531. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16532. }
  16533. return this._selectionContent;
  16534. };
  16535. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16536. this._selectionContent.reset();
  16537. for (var index = 0; index < this.blocks.length; index++) {
  16538. var block = this.blocks[index];
  16539. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16540. }
  16541. if (allowDuplicate) {
  16542. this._selectionContent.concat(this.dynamicContent);
  16543. }
  16544. else {
  16545. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16546. }
  16547. return this._selectionContent;
  16548. };
  16549. Octree.prototype.intersectsRay = function (ray) {
  16550. this._selectionContent.reset();
  16551. for (var index = 0; index < this.blocks.length; index++) {
  16552. var block = this.blocks[index];
  16553. block.intersectsRay(ray, this._selectionContent);
  16554. }
  16555. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16556. return this._selectionContent;
  16557. };
  16558. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16559. target.blocks = new Array();
  16560. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16561. for (var x = 0; x < 2; x++) {
  16562. for (var y = 0; y < 2; y++) {
  16563. for (var z = 0; z < 2; z++) {
  16564. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16565. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16566. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16567. block.addEntries(entries);
  16568. target.blocks.push(block);
  16569. }
  16570. }
  16571. }
  16572. };
  16573. Octree.CreationFuncForMeshes = function (entry, block) {
  16574. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16575. block.entries.push(entry);
  16576. }
  16577. };
  16578. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16579. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16580. block.entries.push(entry);
  16581. }
  16582. };
  16583. return Octree;
  16584. })();
  16585. BABYLON.Octree = Octree;
  16586. })(BABYLON || (BABYLON = {}));
  16587. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16588. (function (BABYLON) {
  16589. var OctreeBlock = (function () {
  16590. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16591. this.entries = new Array();
  16592. this._boundingVectors = new Array();
  16593. this._capacity = capacity;
  16594. this._depth = depth;
  16595. this._maxDepth = maxDepth;
  16596. this._creationFunc = creationFunc;
  16597. this._minPoint = minPoint;
  16598. this._maxPoint = maxPoint;
  16599. this._boundingVectors.push(minPoint.clone());
  16600. this._boundingVectors.push(maxPoint.clone());
  16601. this._boundingVectors.push(minPoint.clone());
  16602. this._boundingVectors[2].x = maxPoint.x;
  16603. this._boundingVectors.push(minPoint.clone());
  16604. this._boundingVectors[3].y = maxPoint.y;
  16605. this._boundingVectors.push(minPoint.clone());
  16606. this._boundingVectors[4].z = maxPoint.z;
  16607. this._boundingVectors.push(maxPoint.clone());
  16608. this._boundingVectors[5].z = minPoint.z;
  16609. this._boundingVectors.push(maxPoint.clone());
  16610. this._boundingVectors[6].x = minPoint.x;
  16611. this._boundingVectors.push(maxPoint.clone());
  16612. this._boundingVectors[7].y = minPoint.y;
  16613. }
  16614. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16615. // Property
  16616. get: function () {
  16617. return this._capacity;
  16618. },
  16619. enumerable: true,
  16620. configurable: true
  16621. });
  16622. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16623. get: function () {
  16624. return this._minPoint;
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16630. get: function () {
  16631. return this._maxPoint;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. // Methods
  16637. OctreeBlock.prototype.addEntry = function (entry) {
  16638. if (this.blocks) {
  16639. for (var index = 0; index < this.blocks.length; index++) {
  16640. var block = this.blocks[index];
  16641. block.addEntry(entry);
  16642. }
  16643. return;
  16644. }
  16645. this._creationFunc(entry, this);
  16646. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16647. this.createInnerBlocks();
  16648. }
  16649. };
  16650. OctreeBlock.prototype.addEntries = function (entries) {
  16651. for (var index = 0; index < entries.length; index++) {
  16652. var mesh = entries[index];
  16653. this.addEntry(mesh);
  16654. }
  16655. };
  16656. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16657. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16658. if (this.blocks) {
  16659. for (var index = 0; index < this.blocks.length; index++) {
  16660. var block = this.blocks[index];
  16661. block.select(frustumPlanes, selection, allowDuplicate);
  16662. }
  16663. return;
  16664. }
  16665. if (allowDuplicate) {
  16666. selection.concat(this.entries);
  16667. }
  16668. else {
  16669. selection.concatWithNoDuplicate(this.entries);
  16670. }
  16671. }
  16672. };
  16673. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16674. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16675. if (this.blocks) {
  16676. for (var index = 0; index < this.blocks.length; index++) {
  16677. var block = this.blocks[index];
  16678. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16679. }
  16680. return;
  16681. }
  16682. if (allowDuplicate) {
  16683. selection.concat(this.entries);
  16684. }
  16685. else {
  16686. selection.concatWithNoDuplicate(this.entries);
  16687. }
  16688. }
  16689. };
  16690. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16691. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16692. if (this.blocks) {
  16693. for (var index = 0; index < this.blocks.length; index++) {
  16694. var block = this.blocks[index];
  16695. block.intersectsRay(ray, selection);
  16696. }
  16697. return;
  16698. }
  16699. selection.concatWithNoDuplicate(this.entries);
  16700. }
  16701. };
  16702. OctreeBlock.prototype.createInnerBlocks = function () {
  16703. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16704. };
  16705. return OctreeBlock;
  16706. })();
  16707. BABYLON.OctreeBlock = OctreeBlock;
  16708. })(BABYLON || (BABYLON = {}));
  16709. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16710. (function (BABYLON) {
  16711. var Bone = (function () {
  16712. function Bone(name, skeleton, parentBone, matrix) {
  16713. this.name = name;
  16714. this.children = new Array();
  16715. this.animations = new Array();
  16716. this._worldTransform = new BABYLON.Matrix();
  16717. this._absoluteTransform = new BABYLON.Matrix();
  16718. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16719. this._skeleton = skeleton;
  16720. this._matrix = matrix;
  16721. this._baseMatrix = matrix;
  16722. skeleton.bones.push(this);
  16723. if (parentBone) {
  16724. this._parent = parentBone;
  16725. parentBone.children.push(this);
  16726. }
  16727. else {
  16728. this._parent = null;
  16729. }
  16730. this._updateDifferenceMatrix();
  16731. }
  16732. // Members
  16733. Bone.prototype.getParent = function () {
  16734. return this._parent;
  16735. };
  16736. Bone.prototype.getLocalMatrix = function () {
  16737. return this._matrix;
  16738. };
  16739. Bone.prototype.getBaseMatrix = function () {
  16740. return this._baseMatrix;
  16741. };
  16742. Bone.prototype.getWorldMatrix = function () {
  16743. return this._worldTransform;
  16744. };
  16745. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16746. return this._invertedAbsoluteTransform;
  16747. };
  16748. Bone.prototype.getAbsoluteMatrix = function () {
  16749. var matrix = this._matrix.clone();
  16750. var parent = this._parent;
  16751. while (parent) {
  16752. matrix = matrix.multiply(parent.getLocalMatrix());
  16753. parent = parent.getParent();
  16754. }
  16755. return matrix;
  16756. };
  16757. // Methods
  16758. Bone.prototype.updateMatrix = function (matrix) {
  16759. this._matrix = matrix;
  16760. this._skeleton._markAsDirty();
  16761. this._updateDifferenceMatrix();
  16762. };
  16763. Bone.prototype._updateDifferenceMatrix = function () {
  16764. if (this._parent) {
  16765. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16766. }
  16767. else {
  16768. this._absoluteTransform.copyFrom(this._matrix);
  16769. }
  16770. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16771. for (var index = 0; index < this.children.length; index++) {
  16772. this.children[index]._updateDifferenceMatrix();
  16773. }
  16774. };
  16775. Bone.prototype.markAsDirty = function () {
  16776. this._skeleton._markAsDirty();
  16777. };
  16778. return Bone;
  16779. })();
  16780. BABYLON.Bone = Bone;
  16781. })(BABYLON || (BABYLON = {}));
  16782. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16783. (function (BABYLON) {
  16784. var Skeleton = (function () {
  16785. function Skeleton(name, id, scene) {
  16786. this.name = name;
  16787. this.id = id;
  16788. this.bones = new Array();
  16789. this._isDirty = true;
  16790. this._identity = BABYLON.Matrix.Identity();
  16791. this.bones = [];
  16792. this._scene = scene;
  16793. scene.skeletons.push(this);
  16794. }
  16795. // Members
  16796. Skeleton.prototype.getTransformMatrices = function () {
  16797. return this._transformMatrices;
  16798. };
  16799. // Methods
  16800. Skeleton.prototype._markAsDirty = function () {
  16801. this._isDirty = true;
  16802. };
  16803. Skeleton.prototype.prepare = function () {
  16804. if (!this._isDirty) {
  16805. return;
  16806. }
  16807. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16808. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16809. }
  16810. for (var index = 0; index < this.bones.length; index++) {
  16811. var bone = this.bones[index];
  16812. var parentBone = bone.getParent();
  16813. if (parentBone) {
  16814. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16815. }
  16816. else {
  16817. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16818. }
  16819. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16820. }
  16821. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16822. this._isDirty = false;
  16823. this._scene._activeBones += this.bones.length;
  16824. };
  16825. Skeleton.prototype.getAnimatables = function () {
  16826. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16827. this._animatables = [];
  16828. for (var index = 0; index < this.bones.length; index++) {
  16829. this._animatables.push(this.bones[index]);
  16830. }
  16831. }
  16832. return this._animatables;
  16833. };
  16834. Skeleton.prototype.clone = function (name, id) {
  16835. var result = new Skeleton(name, id || name, this._scene);
  16836. for (var index = 0; index < this.bones.length; index++) {
  16837. var source = this.bones[index];
  16838. var parentBone = null;
  16839. if (source.getParent()) {
  16840. var parentIndex = this.bones.indexOf(source.getParent());
  16841. parentBone = result.bones[parentIndex];
  16842. }
  16843. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16844. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16845. }
  16846. return result;
  16847. };
  16848. return Skeleton;
  16849. })();
  16850. BABYLON.Skeleton = Skeleton;
  16851. })(BABYLON || (BABYLON = {}));
  16852. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16853. (function (BABYLON) {
  16854. var PostProcess = (function () {
  16855. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16857. this.name = name;
  16858. this.width = -1;
  16859. this.height = -1;
  16860. this._reusable = false;
  16861. this._textures = new BABYLON.SmartArray(2);
  16862. this._currentRenderTextureInd = 0;
  16863. if (camera != null) {
  16864. this._camera = camera;
  16865. this._scene = camera.getScene();
  16866. camera.attachPostProcess(this);
  16867. this._engine = this._scene.getEngine();
  16868. }
  16869. else {
  16870. this._engine = engine;
  16871. }
  16872. this._renderRatio = ratio;
  16873. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16874. this._reusable = reusable || false;
  16875. samplers = samplers || [];
  16876. samplers.push("textureSampler");
  16877. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16878. }
  16879. PostProcess.prototype.isReusable = function () {
  16880. return this._reusable;
  16881. };
  16882. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16883. camera = camera || this._camera;
  16884. var scene = camera.getScene();
  16885. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16886. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16887. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16888. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16889. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16890. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16891. if (this._textures.length > 0) {
  16892. for (var i = 0; i < this._textures.length; i++) {
  16893. this._engine._releaseTexture(this._textures.data[i]);
  16894. }
  16895. this._textures.reset();
  16896. }
  16897. this.width = desiredWidth;
  16898. this.height = desiredHeight;
  16899. 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 }));
  16900. if (this._reusable) {
  16901. 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 }));
  16902. }
  16903. if (this.onSizeChanged) {
  16904. this.onSizeChanged();
  16905. }
  16906. }
  16907. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16908. if (this.onActivate) {
  16909. this.onActivate(camera);
  16910. }
  16911. // Clear
  16912. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16913. if (this._reusable) {
  16914. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16915. }
  16916. };
  16917. PostProcess.prototype.apply = function () {
  16918. // Check
  16919. if (!this._effect.isReady())
  16920. return null;
  16921. // States
  16922. this._engine.enableEffect(this._effect);
  16923. this._engine.setState(false);
  16924. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16925. this._engine.setDepthBuffer(false);
  16926. this._engine.setDepthWrite(false);
  16927. // Texture
  16928. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16929. // Parameters
  16930. if (this.onApply) {
  16931. this.onApply(this._effect);
  16932. }
  16933. return this._effect;
  16934. };
  16935. PostProcess.prototype.dispose = function (camera) {
  16936. camera = camera || this._camera;
  16937. if (this._textures.length > 0) {
  16938. for (var i = 0; i < this._textures.length; i++) {
  16939. this._engine._releaseTexture(this._textures.data[i]);
  16940. }
  16941. this._textures.reset();
  16942. }
  16943. if (!camera) {
  16944. return;
  16945. }
  16946. camera.detachPostProcess(this);
  16947. var index = camera._postProcesses.indexOf(this);
  16948. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16949. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16950. }
  16951. };
  16952. return PostProcess;
  16953. })();
  16954. BABYLON.PostProcess = PostProcess;
  16955. })(BABYLON || (BABYLON = {}));
  16956. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16957. (function (BABYLON) {
  16958. var PostProcessManager = (function () {
  16959. function PostProcessManager(scene) {
  16960. this._vertexDeclaration = [2];
  16961. this._vertexStrideSize = 2 * 4;
  16962. this._scene = scene;
  16963. // VBO
  16964. var vertices = [];
  16965. vertices.push(1, 1);
  16966. vertices.push(-1, 1);
  16967. vertices.push(-1, -1);
  16968. vertices.push(1, -1);
  16969. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16970. // Indices
  16971. var indices = [];
  16972. indices.push(0);
  16973. indices.push(1);
  16974. indices.push(2);
  16975. indices.push(0);
  16976. indices.push(2);
  16977. indices.push(3);
  16978. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16979. }
  16980. // Methods
  16981. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16982. var postProcesses = this._scene.activeCamera._postProcesses;
  16983. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16984. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16985. return false;
  16986. }
  16987. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16988. return true;
  16989. };
  16990. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16991. var engine = this._scene.getEngine();
  16992. for (var index = 0; index < postProcesses.length; index++) {
  16993. if (index < postProcesses.length - 1) {
  16994. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16995. }
  16996. else {
  16997. if (targetTexture) {
  16998. engine.bindFramebuffer(targetTexture);
  16999. }
  17000. else {
  17001. engine.restoreDefaultFramebuffer();
  17002. }
  17003. }
  17004. var pp = postProcesses[index];
  17005. var effect = pp.apply();
  17006. if (effect) {
  17007. if (pp.onBeforeRender) {
  17008. pp.onBeforeRender(effect);
  17009. }
  17010. // VBOs
  17011. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17012. // Draw order
  17013. engine.draw(true, 0, 6);
  17014. }
  17015. }
  17016. // Restore depth buffer
  17017. engine.setDepthBuffer(true);
  17018. engine.setDepthWrite(true);
  17019. };
  17020. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17021. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17022. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17023. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17024. return;
  17025. }
  17026. var engine = this._scene.getEngine();
  17027. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17028. if (index < postProcessesTakenIndices.length - 1) {
  17029. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17030. }
  17031. else {
  17032. if (targetTexture) {
  17033. engine.bindFramebuffer(targetTexture);
  17034. }
  17035. else {
  17036. engine.restoreDefaultFramebuffer();
  17037. }
  17038. }
  17039. if (doNotPresent) {
  17040. break;
  17041. }
  17042. var pp = postProcesses[postProcessesTakenIndices[index]];
  17043. var effect = pp.apply();
  17044. if (effect) {
  17045. if (pp.onBeforeRender) {
  17046. pp.onBeforeRender(effect);
  17047. }
  17048. // VBOs
  17049. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17050. // Draw order
  17051. engine.draw(true, 0, 6);
  17052. }
  17053. }
  17054. // Restore depth buffer
  17055. engine.setDepthBuffer(true);
  17056. engine.setDepthWrite(true);
  17057. };
  17058. PostProcessManager.prototype.dispose = function () {
  17059. if (this._vertexBuffer) {
  17060. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17061. this._vertexBuffer = null;
  17062. }
  17063. if (this._indexBuffer) {
  17064. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17065. this._indexBuffer = null;
  17066. }
  17067. };
  17068. return PostProcessManager;
  17069. })();
  17070. BABYLON.PostProcessManager = PostProcessManager;
  17071. })(BABYLON || (BABYLON = {}));
  17072. //# sourceMappingURL=babylon.postProcessManager.js.map
  17073. var BABYLON;
  17074. (function (BABYLON) {
  17075. var PassPostProcess = (function (_super) {
  17076. __extends(PassPostProcess, _super);
  17077. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17078. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17079. }
  17080. return PassPostProcess;
  17081. })(BABYLON.PostProcess);
  17082. BABYLON.PassPostProcess = PassPostProcess;
  17083. })(BABYLON || (BABYLON = {}));
  17084. //# sourceMappingURL=babylon.passPostProcess.js.map
  17085. var BABYLON;
  17086. (function (BABYLON) {
  17087. var BlurPostProcess = (function (_super) {
  17088. __extends(BlurPostProcess, _super);
  17089. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17090. var _this = this;
  17091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17092. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17093. this.direction = direction;
  17094. this.blurWidth = blurWidth;
  17095. this.onApply = function (effect) {
  17096. effect.setFloat2("screenSize", _this.width, _this.height);
  17097. effect.setVector2("direction", _this.direction);
  17098. effect.setFloat("blurWidth", _this.blurWidth);
  17099. };
  17100. }
  17101. return BlurPostProcess;
  17102. })(BABYLON.PostProcess);
  17103. BABYLON.BlurPostProcess = BlurPostProcess;
  17104. })(BABYLON || (BABYLON = {}));
  17105. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17106. var BABYLON;
  17107. (function (BABYLON) {
  17108. var FilterPostProcess = (function (_super) {
  17109. __extends(FilterPostProcess, _super);
  17110. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17111. var _this = this;
  17112. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17113. this.kernelMatrix = kernelMatrix;
  17114. this.onApply = function (effect) {
  17115. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17116. };
  17117. }
  17118. return FilterPostProcess;
  17119. })(BABYLON.PostProcess);
  17120. BABYLON.FilterPostProcess = FilterPostProcess;
  17121. })(BABYLON || (BABYLON = {}));
  17122. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17123. var BABYLON;
  17124. (function (BABYLON) {
  17125. var RefractionPostProcess = (function (_super) {
  17126. __extends(RefractionPostProcess, _super);
  17127. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17128. var _this = this;
  17129. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17130. this.color = color;
  17131. this.depth = depth;
  17132. this.colorLevel = colorLevel;
  17133. this.onActivate = function (cam) {
  17134. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17135. };
  17136. this.onApply = function (effect) {
  17137. effect.setColor3("baseColor", _this.color);
  17138. effect.setFloat("depth", _this.depth);
  17139. effect.setFloat("colorLevel", _this.colorLevel);
  17140. effect.setTexture("refractionSampler", _this._refRexture);
  17141. };
  17142. }
  17143. // Methods
  17144. RefractionPostProcess.prototype.dispose = function (camera) {
  17145. if (this._refRexture) {
  17146. this._refRexture.dispose();
  17147. }
  17148. _super.prototype.dispose.call(this, camera);
  17149. };
  17150. return RefractionPostProcess;
  17151. })(BABYLON.PostProcess);
  17152. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17153. })(BABYLON || (BABYLON = {}));
  17154. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17155. var BABYLON;
  17156. (function (BABYLON) {
  17157. var BlackAndWhitePostProcess = (function (_super) {
  17158. __extends(BlackAndWhitePostProcess, _super);
  17159. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17160. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17161. }
  17162. return BlackAndWhitePostProcess;
  17163. })(BABYLON.PostProcess);
  17164. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17165. })(BABYLON || (BABYLON = {}));
  17166. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17167. var BABYLON;
  17168. (function (BABYLON) {
  17169. var ConvolutionPostProcess = (function (_super) {
  17170. __extends(ConvolutionPostProcess, _super);
  17171. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17172. var _this = this;
  17173. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17174. this.kernel = kernel;
  17175. this.onApply = function (effect) {
  17176. effect.setFloat2("screenSize", _this.width, _this.height);
  17177. effect.setArray("kernel", _this.kernel);
  17178. };
  17179. }
  17180. // Statics
  17181. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17182. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17183. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17184. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17185. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17186. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17187. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17188. return ConvolutionPostProcess;
  17189. })(BABYLON.PostProcess);
  17190. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17191. })(BABYLON || (BABYLON = {}));
  17192. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17193. var BABYLON;
  17194. (function (BABYLON) {
  17195. var FxaaPostProcess = (function (_super) {
  17196. __extends(FxaaPostProcess, _super);
  17197. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17198. var _this = this;
  17199. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17200. this.onSizeChanged = function () {
  17201. _this.texelWidth = 1.0 / _this.width;
  17202. _this.texelHeight = 1.0 / _this.height;
  17203. };
  17204. this.onApply = function (effect) {
  17205. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17206. };
  17207. }
  17208. return FxaaPostProcess;
  17209. })(BABYLON.PostProcess);
  17210. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17211. })(BABYLON || (BABYLON = {}));
  17212. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17213. (function (BABYLON) {
  17214. var LensFlare = (function () {
  17215. function LensFlare(size, position, color, imgUrl, system) {
  17216. this.size = size;
  17217. this.position = position;
  17218. this.dispose = function () {
  17219. if (this.texture) {
  17220. this.texture.dispose();
  17221. }
  17222. // Remove from scene
  17223. var index = this._system.lensFlares.indexOf(this);
  17224. this._system.lensFlares.splice(index, 1);
  17225. };
  17226. this.color = color || new BABYLON.Color3(1, 1, 1);
  17227. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17228. this._system = system;
  17229. system.lensFlares.push(this);
  17230. }
  17231. return LensFlare;
  17232. })();
  17233. BABYLON.LensFlare = LensFlare;
  17234. })(BABYLON || (BABYLON = {}));
  17235. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17236. (function (BABYLON) {
  17237. var LensFlareSystem = (function () {
  17238. function LensFlareSystem(name, emitter, scene) {
  17239. this.name = name;
  17240. this.lensFlares = new Array();
  17241. this.borderLimit = 300;
  17242. this._vertexDeclaration = [2];
  17243. this._vertexStrideSize = 2 * 4;
  17244. this._isEnabled = true;
  17245. this._scene = scene;
  17246. this._emitter = emitter;
  17247. scene.lensFlareSystems.push(this);
  17248. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17249. // VBO
  17250. var vertices = [];
  17251. vertices.push(1, 1);
  17252. vertices.push(-1, 1);
  17253. vertices.push(-1, -1);
  17254. vertices.push(1, -1);
  17255. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17256. // Indices
  17257. var indices = [];
  17258. indices.push(0);
  17259. indices.push(1);
  17260. indices.push(2);
  17261. indices.push(0);
  17262. indices.push(2);
  17263. indices.push(3);
  17264. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17265. // Effects
  17266. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17267. }
  17268. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17269. get: function () {
  17270. return this._isEnabled;
  17271. },
  17272. set: function (value) {
  17273. this._isEnabled = value;
  17274. },
  17275. enumerable: true,
  17276. configurable: true
  17277. });
  17278. LensFlareSystem.prototype.getScene = function () {
  17279. return this._scene;
  17280. };
  17281. LensFlareSystem.prototype.getEmitter = function () {
  17282. return this._emitter;
  17283. };
  17284. LensFlareSystem.prototype.getEmitterPosition = function () {
  17285. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17286. };
  17287. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17288. var position = this.getEmitterPosition();
  17289. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17290. this._positionX = position.x;
  17291. this._positionY = position.y;
  17292. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17293. if (position.z > 0) {
  17294. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17295. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17296. return true;
  17297. }
  17298. }
  17299. return false;
  17300. };
  17301. LensFlareSystem.prototype._isVisible = function () {
  17302. if (!this._isEnabled) {
  17303. return false;
  17304. }
  17305. var emitterPosition = this.getEmitterPosition();
  17306. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17307. var distance = direction.length();
  17308. direction.normalize();
  17309. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17310. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17311. return !pickInfo.hit || pickInfo.distance > distance;
  17312. };
  17313. LensFlareSystem.prototype.render = function () {
  17314. if (!this._effect.isReady())
  17315. return false;
  17316. var engine = this._scene.getEngine();
  17317. var viewport = this._scene.activeCamera.viewport;
  17318. var globalViewport = viewport.toGlobal(engine);
  17319. // Position
  17320. if (!this.computeEffectivePosition(globalViewport)) {
  17321. return false;
  17322. }
  17323. // Visibility
  17324. if (!this._isVisible()) {
  17325. return false;
  17326. }
  17327. // Intensity
  17328. var awayX;
  17329. var awayY;
  17330. if (this._positionX < this.borderLimit + globalViewport.x) {
  17331. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17332. }
  17333. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17334. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17335. }
  17336. else {
  17337. awayX = 0;
  17338. }
  17339. if (this._positionY < this.borderLimit + globalViewport.y) {
  17340. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17341. }
  17342. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17343. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17344. }
  17345. else {
  17346. awayY = 0;
  17347. }
  17348. var away = (awayX > awayY) ? awayX : awayY;
  17349. if (away > this.borderLimit) {
  17350. away = this.borderLimit;
  17351. }
  17352. var intensity = 1.0 - (away / this.borderLimit);
  17353. if (intensity < 0) {
  17354. return false;
  17355. }
  17356. if (intensity > 1.0) {
  17357. intensity = 1.0;
  17358. }
  17359. // Position
  17360. var centerX = globalViewport.x + globalViewport.width / 2;
  17361. var centerY = globalViewport.y + globalViewport.height / 2;
  17362. var distX = centerX - this._positionX;
  17363. var distY = centerY - this._positionY;
  17364. // Effects
  17365. engine.enableEffect(this._effect);
  17366. engine.setState(false);
  17367. engine.setDepthBuffer(false);
  17368. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17369. // VBOs
  17370. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17371. for (var index = 0; index < this.lensFlares.length; index++) {
  17372. var flare = this.lensFlares[index];
  17373. var x = centerX - (distX * flare.position);
  17374. var y = centerY - (distY * flare.position);
  17375. var cw = flare.size;
  17376. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17377. var cx = 2 * (x / globalViewport.width) - 1.0;
  17378. var cy = 1.0 - 2 * (y / globalViewport.height);
  17379. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17380. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17381. // Texture
  17382. this._effect.setTexture("textureSampler", flare.texture);
  17383. // Color
  17384. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17385. // Draw order
  17386. engine.draw(true, 0, 6);
  17387. }
  17388. engine.setDepthBuffer(true);
  17389. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17390. return true;
  17391. };
  17392. LensFlareSystem.prototype.dispose = function () {
  17393. if (this._vertexBuffer) {
  17394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17395. this._vertexBuffer = null;
  17396. }
  17397. if (this._indexBuffer) {
  17398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17399. this._indexBuffer = null;
  17400. }
  17401. while (this.lensFlares.length) {
  17402. this.lensFlares[0].dispose();
  17403. }
  17404. // Remove from scene
  17405. var index = this._scene.lensFlareSystems.indexOf(this);
  17406. this._scene.lensFlareSystems.splice(index, 1);
  17407. };
  17408. return LensFlareSystem;
  17409. })();
  17410. BABYLON.LensFlareSystem = LensFlareSystem;
  17411. })(BABYLON || (BABYLON = {}));
  17412. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17413. (function (BABYLON) {
  17414. var IntersectionInfo = (function () {
  17415. function IntersectionInfo(bu, bv, distance) {
  17416. this.bu = bu;
  17417. this.bv = bv;
  17418. this.distance = distance;
  17419. this.faceId = 0;
  17420. this.subMeshId = 0;
  17421. }
  17422. return IntersectionInfo;
  17423. })();
  17424. BABYLON.IntersectionInfo = IntersectionInfo;
  17425. var PickingInfo = (function () {
  17426. function PickingInfo() {
  17427. this.hit = false;
  17428. this.distance = 0;
  17429. this.pickedPoint = null;
  17430. this.pickedMesh = null;
  17431. this.bu = 0;
  17432. this.bv = 0;
  17433. this.faceId = -1;
  17434. this.subMeshId = 0;
  17435. }
  17436. // Methods
  17437. PickingInfo.prototype.getNormal = function () {
  17438. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17439. return null;
  17440. }
  17441. var indices = this.pickedMesh.getIndices();
  17442. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17443. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17444. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17445. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17446. normal0 = normal0.scale(this.bu);
  17447. normal1 = normal1.scale(this.bv);
  17448. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17449. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17450. };
  17451. PickingInfo.prototype.getTextureCoordinates = function () {
  17452. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17453. return null;
  17454. }
  17455. var indices = this.pickedMesh.getIndices();
  17456. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17457. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17458. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17459. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17460. uv0 = uv0.scale(this.bu);
  17461. uv1 = uv1.scale(this.bv);
  17462. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17463. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17464. };
  17465. return PickingInfo;
  17466. })();
  17467. BABYLON.PickingInfo = PickingInfo;
  17468. })(BABYLON || (BABYLON = {}));
  17469. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17470. (function (BABYLON) {
  17471. var FilesInput = (function () {
  17472. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17473. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17474. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17475. this._engine = p_engine;
  17476. this._canvas = p_canvas;
  17477. this._currentScene = p_scene;
  17478. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17479. this._progressCallback = p_progressCallback;
  17480. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17481. this._textureLoadingCallback = p_textureLoadingCallback;
  17482. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17483. }
  17484. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17485. var _this = this;
  17486. if (p_elementToMonitor) {
  17487. this._elementToMonitor = p_elementToMonitor;
  17488. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17489. _this.drag(e);
  17490. }, false);
  17491. this._elementToMonitor.addEventListener("dragover", function (e) {
  17492. _this.drag(e);
  17493. }, false);
  17494. this._elementToMonitor.addEventListener("drop", function (e) {
  17495. _this.drop(e);
  17496. }, false);
  17497. }
  17498. };
  17499. FilesInput.prototype.renderFunction = function () {
  17500. if (this._additionnalRenderLoopLogicCallback) {
  17501. this._additionnalRenderLoopLogicCallback();
  17502. }
  17503. if (this._currentScene) {
  17504. if (this._textureLoadingCallback) {
  17505. var remaining = this._currentScene.getWaitingItemsCount();
  17506. if (remaining > 0) {
  17507. this._textureLoadingCallback(remaining);
  17508. }
  17509. }
  17510. this._currentScene.render();
  17511. }
  17512. };
  17513. FilesInput.prototype.drag = function (e) {
  17514. e.stopPropagation();
  17515. e.preventDefault();
  17516. };
  17517. FilesInput.prototype.drop = function (eventDrop) {
  17518. eventDrop.stopPropagation();
  17519. eventDrop.preventDefault();
  17520. this.loadFiles(eventDrop);
  17521. };
  17522. FilesInput.prototype.loadFiles = function (event) {
  17523. if (this._startingProcessingFilesCallback)
  17524. this._startingProcessingFilesCallback();
  17525. // Handling data transfer via drag'n'drop
  17526. if (event && event.dataTransfer && event.dataTransfer.files) {
  17527. this._filesToLoad = event.dataTransfer.files;
  17528. }
  17529. // Handling files from input files
  17530. if (event && event.target && event.target.files) {
  17531. this._filesToLoad = event.target.files;
  17532. }
  17533. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17534. for (var i = 0; i < this._filesToLoad.length; i++) {
  17535. switch (this._filesToLoad[i].type) {
  17536. case "image/jpeg":
  17537. case "image/png":
  17538. case "image/bmp":
  17539. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17540. break;
  17541. case "image/targa":
  17542. case "image/vnd.ms-dds":
  17543. case "audio/wav":
  17544. case "audio/x-wav":
  17545. case "audio/mp3":
  17546. case "audio/mpeg":
  17547. case "audio/mpeg3":
  17548. case "audio/x-mpeg-3":
  17549. case "audio/ogg":
  17550. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17551. break;
  17552. default:
  17553. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17554. this._sceneFileToLoad = this._filesToLoad[i];
  17555. }
  17556. break;
  17557. }
  17558. }
  17559. this.reload();
  17560. }
  17561. };
  17562. FilesInput.prototype.reload = function () {
  17563. var _this = this;
  17564. var that = this;
  17565. // If a ".babylon" file has been provided
  17566. if (this._sceneFileToLoad) {
  17567. if (this._currentScene) {
  17568. this._engine.stopRenderLoop();
  17569. this._currentScene.dispose();
  17570. }
  17571. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17572. that._currentScene = newScene;
  17573. // Wait for textures and shaders to be ready
  17574. that._currentScene.executeWhenReady(function () {
  17575. // Attach camera to canvas inputs
  17576. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17577. that._currentScene.createDefaultCameraOrLight();
  17578. }
  17579. that._currentScene.activeCamera.attachControl(that._canvas);
  17580. if (that._sceneLoadedCallback) {
  17581. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17582. }
  17583. that._engine.runRenderLoop(function () {
  17584. that.renderFunction();
  17585. });
  17586. });
  17587. }, function (progress) {
  17588. if (_this._progressCallback) {
  17589. _this._progressCallback(progress);
  17590. }
  17591. });
  17592. }
  17593. else {
  17594. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17595. }
  17596. };
  17597. FilesInput.FilesTextures = new Array();
  17598. FilesInput.FilesToLoad = new Array();
  17599. return FilesInput;
  17600. })();
  17601. BABYLON.FilesInput = FilesInput;
  17602. })(BABYLON || (BABYLON = {}));
  17603. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17604. (function (BABYLON) {
  17605. var OimoJSPlugin = (function () {
  17606. function OimoJSPlugin() {
  17607. this._registeredMeshes = [];
  17608. /**
  17609. * Update the body position according to the mesh position
  17610. * @param mesh
  17611. */
  17612. this.updateBodyPosition = function (mesh) {
  17613. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17614. var registeredMesh = this._registeredMeshes[index];
  17615. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17616. var body = registeredMesh.body.body;
  17617. mesh.computeWorldMatrix(true);
  17618. var center = mesh.getBoundingInfo().boundingBox.center;
  17619. body.setPosition(center.x, center.y, center.z);
  17620. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17621. return;
  17622. }
  17623. // Case where the parent has been updated
  17624. if (registeredMesh.mesh.parent === mesh) {
  17625. mesh.computeWorldMatrix(true);
  17626. registeredMesh.mesh.computeWorldMatrix(true);
  17627. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17628. var absoluteRotation = mesh.rotation;
  17629. body = registeredMesh.body.body;
  17630. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17631. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17632. return;
  17633. }
  17634. }
  17635. };
  17636. }
  17637. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17638. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17639. };
  17640. OimoJSPlugin.prototype.initialize = function (iterations) {
  17641. this._world = new OIMO.World();
  17642. this._world.clear();
  17643. };
  17644. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17645. this._world.gravity = gravity;
  17646. };
  17647. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17648. var body = null;
  17649. this.unregisterMesh(mesh);
  17650. mesh.computeWorldMatrix(true);
  17651. var initialRotation = null;
  17652. if (mesh.rotationQuaternion) {
  17653. initialRotation = mesh.rotationQuaternion.clone();
  17654. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17655. mesh.computeWorldMatrix(true);
  17656. }
  17657. var bbox = mesh.getBoundingInfo().boundingBox;
  17658. // The delta between the mesh position and the mesh bounding box center
  17659. var deltaPosition = mesh.position.subtract(bbox.center);
  17660. // Transform delta position with the rotation
  17661. if (initialRotation) {
  17662. var m = new BABYLON.Matrix();
  17663. initialRotation.toRotationMatrix(m);
  17664. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17665. }
  17666. switch (impostor) {
  17667. case BABYLON.PhysicsEngine.SphereImpostor:
  17668. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17669. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17670. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17671. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17672. body = new OIMO.Body({
  17673. type: 'sphere',
  17674. size: [size],
  17675. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17676. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17677. move: options.mass != 0,
  17678. config: [options.mass, options.friction, options.restitution],
  17679. world: this._world
  17680. });
  17681. break;
  17682. case BABYLON.PhysicsEngine.PlaneImpostor:
  17683. case BABYLON.PhysicsEngine.CylinderImpostor:
  17684. case BABYLON.PhysicsEngine.BoxImpostor:
  17685. var min = bbox.minimumWorld;
  17686. var max = bbox.maximumWorld;
  17687. var box = max.subtract(min);
  17688. var sizeX = this._checkWithEpsilon(box.x);
  17689. var sizeY = this._checkWithEpsilon(box.y);
  17690. var sizeZ = this._checkWithEpsilon(box.z);
  17691. body = new OIMO.Body({
  17692. type: 'box',
  17693. size: [sizeX, sizeY, sizeZ],
  17694. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17695. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17696. move: options.mass != 0,
  17697. config: [options.mass, options.friction, options.restitution],
  17698. world: this._world
  17699. });
  17700. break;
  17701. }
  17702. //If quaternion was set as the rotation of the object
  17703. if (initialRotation) {
  17704. //We have to access the rigid body's properties to set the quaternion.
  17705. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17706. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17707. //update the internal rotation matrix
  17708. body.body.syncShapes();
  17709. }
  17710. this._registeredMeshes.push({
  17711. mesh: mesh,
  17712. body: body,
  17713. delta: deltaPosition
  17714. });
  17715. return body;
  17716. };
  17717. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17718. var types = [], sizes = [], positions = [], rotations = [];
  17719. var initialMesh = parts[0].mesh;
  17720. for (var index = 0; index < parts.length; index++) {
  17721. var part = parts[index];
  17722. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17723. types.push(bodyParameters.type);
  17724. sizes.push.apply(sizes, bodyParameters.size);
  17725. positions.push.apply(positions, bodyParameters.pos);
  17726. rotations.push.apply(rotations, bodyParameters.rot);
  17727. }
  17728. var body = new OIMO.Body({
  17729. type: types,
  17730. size: sizes,
  17731. pos: positions,
  17732. rot: rotations,
  17733. move: options.mass != 0,
  17734. config: [options.mass, options.friction, options.restitution],
  17735. world: this._world
  17736. });
  17737. this._registeredMeshes.push({
  17738. mesh: initialMesh,
  17739. body: body
  17740. });
  17741. return body;
  17742. };
  17743. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17744. var bodyParameters = null;
  17745. var mesh = part.mesh;
  17746. // We need the bounding box/sphere info to compute the physics body
  17747. mesh.computeWorldMatrix();
  17748. switch (part.impostor) {
  17749. case BABYLON.PhysicsEngine.SphereImpostor:
  17750. var bbox = mesh.getBoundingInfo().boundingBox;
  17751. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17752. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17753. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17754. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17755. bodyParameters = {
  17756. type: 'sphere',
  17757. /* bug with oimo : sphere needs 3 sizes in this case */
  17758. size: [size, -1, -1],
  17759. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17760. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17761. };
  17762. break;
  17763. case BABYLON.PhysicsEngine.PlaneImpostor:
  17764. case BABYLON.PhysicsEngine.BoxImpostor:
  17765. bbox = mesh.getBoundingInfo().boundingBox;
  17766. var min = bbox.minimumWorld;
  17767. var max = bbox.maximumWorld;
  17768. var box = max.subtract(min);
  17769. var sizeX = this._checkWithEpsilon(box.x);
  17770. var sizeY = this._checkWithEpsilon(box.y);
  17771. var sizeZ = this._checkWithEpsilon(box.z);
  17772. var relativePosition = mesh.position;
  17773. bodyParameters = {
  17774. type: 'box',
  17775. size: [sizeX, sizeY, sizeZ],
  17776. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17777. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17778. };
  17779. break;
  17780. }
  17781. return bodyParameters;
  17782. };
  17783. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17784. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17785. var registeredMesh = this._registeredMeshes[index];
  17786. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17787. if (registeredMesh.body) {
  17788. this._world.removeRigidBody(registeredMesh.body.body);
  17789. this._unbindBody(registeredMesh.body);
  17790. }
  17791. this._registeredMeshes.splice(index, 1);
  17792. return;
  17793. }
  17794. }
  17795. };
  17796. OimoJSPlugin.prototype._unbindBody = function (body) {
  17797. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17798. var registeredMesh = this._registeredMeshes[index];
  17799. if (registeredMesh.body === body) {
  17800. registeredMesh.body = null;
  17801. }
  17802. }
  17803. };
  17804. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17805. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17806. var registeredMesh = this._registeredMeshes[index];
  17807. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17808. // Get object mass to have a behaviour similar to cannon.js
  17809. var mass = registeredMesh.body.body.massInfo.mass;
  17810. // The force is scaled with the mass of object
  17811. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17812. return;
  17813. }
  17814. }
  17815. };
  17816. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17817. var body1 = null, body2 = null;
  17818. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17819. var registeredMesh = this._registeredMeshes[index];
  17820. if (registeredMesh.mesh === mesh1) {
  17821. body1 = registeredMesh.body.body;
  17822. }
  17823. else if (registeredMesh.mesh === mesh2) {
  17824. body2 = registeredMesh.body.body;
  17825. }
  17826. }
  17827. if (!body1 || !body2) {
  17828. return false;
  17829. }
  17830. if (!options) {
  17831. options = {};
  17832. }
  17833. new OIMO.Link({
  17834. type: options.type,
  17835. body1: body1,
  17836. body2: body2,
  17837. min: options.min,
  17838. max: options.max,
  17839. axe1: options.axe1,
  17840. axe2: options.axe2,
  17841. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17842. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17843. collision: options.collision,
  17844. spring: options.spring,
  17845. world: this._world
  17846. });
  17847. return true;
  17848. };
  17849. OimoJSPlugin.prototype.dispose = function () {
  17850. this._world.clear();
  17851. while (this._registeredMeshes.length) {
  17852. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17853. }
  17854. };
  17855. OimoJSPlugin.prototype.isSupported = function () {
  17856. return OIMO !== undefined;
  17857. };
  17858. OimoJSPlugin.prototype._getLastShape = function (body) {
  17859. var lastShape = body.shapes;
  17860. while (lastShape.next) {
  17861. lastShape = lastShape.next;
  17862. }
  17863. return lastShape;
  17864. };
  17865. OimoJSPlugin.prototype.runOneStep = function (time) {
  17866. this._world.step();
  17867. // Update the position of all registered meshes
  17868. var i = this._registeredMeshes.length;
  17869. var m;
  17870. while (i--) {
  17871. var body = this._registeredMeshes[i].body.body;
  17872. var mesh = this._registeredMeshes[i].mesh;
  17873. var delta = this._registeredMeshes[i].delta;
  17874. if (!body.sleeping) {
  17875. if (body.shapes.next) {
  17876. var parentShape = this._getLastShape(body);
  17877. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17878. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17879. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17880. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17881. if (!mesh.rotationQuaternion) {
  17882. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17883. }
  17884. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17885. mesh.computeWorldMatrix();
  17886. }
  17887. else {
  17888. m = body.getMatrix();
  17889. mtx = BABYLON.Matrix.FromArray(m);
  17890. // Body position
  17891. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17892. if (!delta) {
  17893. mesh.position.x = bodyX;
  17894. mesh.position.y = bodyY;
  17895. mesh.position.z = bodyZ;
  17896. }
  17897. else {
  17898. mesh.position.x = bodyX + delta.x;
  17899. mesh.position.y = bodyY + delta.y;
  17900. mesh.position.z = bodyZ + delta.z;
  17901. }
  17902. if (!mesh.rotationQuaternion) {
  17903. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17904. }
  17905. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17906. mesh.computeWorldMatrix();
  17907. }
  17908. }
  17909. }
  17910. };
  17911. return OimoJSPlugin;
  17912. })();
  17913. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17914. })(BABYLON || (BABYLON = {}));
  17915. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17916. (function (BABYLON) {
  17917. var PhysicsEngine = (function () {
  17918. function PhysicsEngine(plugin) {
  17919. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17920. }
  17921. PhysicsEngine.prototype._initialize = function (gravity) {
  17922. this._currentPlugin.initialize();
  17923. this._setGravity(gravity);
  17924. };
  17925. PhysicsEngine.prototype._runOneStep = function (delta) {
  17926. if (delta > 0.1) {
  17927. delta = 0.1;
  17928. }
  17929. else if (delta <= 0) {
  17930. delta = 1.0 / 60.0;
  17931. }
  17932. this._currentPlugin.runOneStep(delta);
  17933. };
  17934. PhysicsEngine.prototype._setGravity = function (gravity) {
  17935. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17936. this._currentPlugin.setGravity(this.gravity);
  17937. };
  17938. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17939. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17940. };
  17941. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17942. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17943. };
  17944. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17945. this._currentPlugin.unregisterMesh(mesh);
  17946. };
  17947. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17948. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17949. };
  17950. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17951. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17952. };
  17953. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17954. this._currentPlugin.updateBodyPosition(mesh);
  17955. };
  17956. PhysicsEngine.prototype.dispose = function () {
  17957. this._currentPlugin.dispose();
  17958. };
  17959. PhysicsEngine.prototype.isSupported = function () {
  17960. return this._currentPlugin.isSupported();
  17961. };
  17962. // Statics
  17963. PhysicsEngine.NoImpostor = 0;
  17964. PhysicsEngine.SphereImpostor = 1;
  17965. PhysicsEngine.BoxImpostor = 2;
  17966. PhysicsEngine.PlaneImpostor = 3;
  17967. PhysicsEngine.MeshImpostor = 4;
  17968. PhysicsEngine.CapsuleImpostor = 5;
  17969. PhysicsEngine.ConeImpostor = 6;
  17970. PhysicsEngine.CylinderImpostor = 7;
  17971. PhysicsEngine.ConvexHullImpostor = 8;
  17972. PhysicsEngine.Epsilon = 0.001;
  17973. return PhysicsEngine;
  17974. })();
  17975. BABYLON.PhysicsEngine = PhysicsEngine;
  17976. })(BABYLON || (BABYLON = {}));
  17977. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17978. (function (BABYLON) {
  17979. var serializeLight = function (light) {
  17980. var serializationObject = {};
  17981. serializationObject.name = light.name;
  17982. serializationObject.id = light.id;
  17983. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17984. if (light instanceof BABYLON.PointLight) {
  17985. serializationObject.type = 0;
  17986. serializationObject.position = light.position.asArray();
  17987. }
  17988. else if (light instanceof BABYLON.DirectionalLight) {
  17989. serializationObject.type = 1;
  17990. var directionalLight = light;
  17991. serializationObject.position = directionalLight.position.asArray();
  17992. serializationObject.direction = directionalLight.direction.asArray();
  17993. }
  17994. else if (light instanceof BABYLON.SpotLight) {
  17995. serializationObject.type = 2;
  17996. var spotLight = light;
  17997. serializationObject.position = spotLight.position.asArray();
  17998. serializationObject.direction = spotLight.position.asArray();
  17999. serializationObject.angle = spotLight.angle;
  18000. serializationObject.exponent = spotLight.exponent;
  18001. }
  18002. else if (light instanceof BABYLON.HemisphericLight) {
  18003. serializationObject.type = 3;
  18004. var hemisphericLight = light;
  18005. serializationObject.direction = hemisphericLight.direction.asArray();
  18006. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18007. }
  18008. if (light.intensity) {
  18009. serializationObject.intensity = light.intensity;
  18010. }
  18011. serializationObject.range = light.range;
  18012. serializationObject.diffuse = light.diffuse.asArray();
  18013. serializationObject.specular = light.specular.asArray();
  18014. return serializationObject;
  18015. };
  18016. var serializeFresnelParameter = function (fresnelParameter) {
  18017. var serializationObject = {};
  18018. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18019. serializationObject.leftColor = fresnelParameter.leftColor;
  18020. serializationObject.rightColor = fresnelParameter.rightColor;
  18021. serializationObject.bias = fresnelParameter.bias;
  18022. serializationObject.power = fresnelParameter.power;
  18023. return serializationObject;
  18024. };
  18025. var serializeCamera = function (camera) {
  18026. var serializationObject = {};
  18027. serializationObject.name = camera.name;
  18028. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18029. serializationObject.id = camera.id;
  18030. serializationObject.position = camera.position.asArray();
  18031. // Parent
  18032. if (camera.parent) {
  18033. serializationObject.parentId = camera.parent.id;
  18034. }
  18035. serializationObject.fov = camera.fov;
  18036. serializationObject.minZ = camera.minZ;
  18037. serializationObject.maxZ = camera.maxZ;
  18038. serializationObject.inertia = camera.inertia;
  18039. //setting the type
  18040. if (camera instanceof BABYLON.FreeCamera) {
  18041. serializationObject.type = "FreeCamera";
  18042. }
  18043. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18044. serializationObject.type = "ArcRotateCamera";
  18045. }
  18046. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18047. serializationObject.type = "AnaglyphArcRotateCamera";
  18048. }
  18049. else if (camera instanceof BABYLON.GamepadCamera) {
  18050. serializationObject.type = "GamepadCamera";
  18051. }
  18052. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18053. serializationObject.type = "AnaglyphFreeCamera";
  18054. }
  18055. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18056. serializationObject.type = "DeviceOrientationCamera";
  18057. }
  18058. else if (camera instanceof BABYLON.FollowCamera) {
  18059. serializationObject.type = "FollowCamera";
  18060. }
  18061. else if (camera instanceof BABYLON.OculusCamera) {
  18062. serializationObject.type = "OculusCamera";
  18063. }
  18064. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18065. serializationObject.type = "OculusGamepadCamera";
  18066. }
  18067. else if (camera instanceof BABYLON.TouchCamera) {
  18068. serializationObject.type = "TouchCamera";
  18069. }
  18070. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18071. serializationObject.type = "VirtualJoysticksCamera";
  18072. }
  18073. else if (camera instanceof BABYLON.WebVRCamera) {
  18074. serializationObject.type = "WebVRCamera";
  18075. }
  18076. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18077. serializationObject.type = "VRDeviceOrientationCamera";
  18078. }
  18079. //special properties of specific cameras
  18080. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18081. var arcCamera = camera;
  18082. serializationObject.alpha = arcCamera.alpha;
  18083. serializationObject.beta = arcCamera.beta;
  18084. serializationObject.radius = arcCamera.radius;
  18085. }
  18086. else if (camera instanceof BABYLON.FollowCamera) {
  18087. var followCam = camera;
  18088. serializationObject.radius = followCam.radius;
  18089. serializationObject.heightOffset = followCam.heightOffset;
  18090. serializationObject.rotationOffset = followCam.rotationOffset;
  18091. }
  18092. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18093. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18094. if (camera['_eyeSpace'] !== undefined) {
  18095. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18096. }
  18097. }
  18098. //general properties that not all cameras have. The [] is due to typescript's type safety
  18099. if (camera['speed'] !== undefined) {
  18100. serializationObject.speed = camera['speed'];
  18101. }
  18102. // Target
  18103. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18104. serializationObject.rotation = camera['rotation'].asArray();
  18105. }
  18106. // Locked target
  18107. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18108. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18109. }
  18110. if (camera['checkCollisions'] !== undefined) {
  18111. serializationObject.checkCollisions = camera['checkCollisions'];
  18112. }
  18113. if (camera['applyGravity'] !== undefined) {
  18114. serializationObject.applyGravity = camera['applyGravity'];
  18115. }
  18116. if (camera['ellipsoid']) {
  18117. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18118. }
  18119. // Animations
  18120. appendAnimations(camera, serializationObject);
  18121. // Layer mask
  18122. serializationObject.layerMask = camera.layerMask;
  18123. return serializationObject;
  18124. };
  18125. var appendAnimations = function (source, destination) {
  18126. if (source.animations) {
  18127. destination.animations = [];
  18128. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18129. var animation = source.animations[animationIndex];
  18130. destination.animations.push(serializeAnimation(animation));
  18131. }
  18132. }
  18133. };
  18134. var serializeAnimation = function (animation) {
  18135. var serializationObject = {};
  18136. serializationObject.name = animation.name;
  18137. serializationObject.property = animation.targetProperty;
  18138. serializationObject.framePerSecond = animation.framePerSecond;
  18139. serializationObject.dataType = animation.dataType;
  18140. serializationObject.loopBehavior = animation.loopMode;
  18141. var dataType = animation.dataType;
  18142. serializationObject.keys = [];
  18143. var keys = animation.getKeys();
  18144. for (var index = 0; index < keys.length; index++) {
  18145. var animationKey = keys[index];
  18146. var key = {};
  18147. key.frame = animationKey.frame;
  18148. switch (dataType) {
  18149. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18150. key.values = [animationKey.value];
  18151. break;
  18152. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18153. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18154. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18155. key.values = animationKey.value.asArray();
  18156. break;
  18157. }
  18158. serializationObject.keys.push(key);
  18159. }
  18160. return serializationObject;
  18161. };
  18162. var serializeMultiMaterial = function (material) {
  18163. var serializationObject = {};
  18164. serializationObject.name = material.name;
  18165. serializationObject.id = material.id;
  18166. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18167. serializationObject.materials = [];
  18168. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18169. var subMat = material.subMaterials[matIndex];
  18170. if (subMat) {
  18171. serializationObject.materials.push(subMat.id);
  18172. }
  18173. else {
  18174. serializationObject.materials.push(null);
  18175. }
  18176. }
  18177. return serializationObject;
  18178. };
  18179. var serializeMaterial = function (material) {
  18180. var serializationObject = {};
  18181. serializationObject.name = material.name;
  18182. serializationObject.ambient = material.ambientColor.asArray();
  18183. serializationObject.diffuse = material.diffuseColor.asArray();
  18184. serializationObject.specular = material.specularColor.asArray();
  18185. serializationObject.specularPower = material.specularPower;
  18186. serializationObject.emissive = material.emissiveColor.asArray();
  18187. serializationObject.alpha = material.alpha;
  18188. serializationObject.id = material.id;
  18189. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18190. serializationObject.backFaceCulling = material.backFaceCulling;
  18191. if (material.diffuseTexture) {
  18192. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18193. }
  18194. if (material.diffuseFresnelParameters) {
  18195. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18196. }
  18197. if (material.ambientTexture) {
  18198. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18199. }
  18200. if (material.opacityTexture) {
  18201. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18202. }
  18203. if (material.opacityFresnelParameters) {
  18204. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18205. }
  18206. if (material.reflectionTexture) {
  18207. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18208. }
  18209. if (material.reflectionFresnelParameters) {
  18210. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18211. }
  18212. if (material.emissiveTexture) {
  18213. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18214. }
  18215. if (material.emissiveFresnelParameters) {
  18216. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18217. }
  18218. if (material.specularTexture) {
  18219. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18220. }
  18221. if (material.bumpTexture) {
  18222. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18223. }
  18224. return serializationObject;
  18225. };
  18226. var serializeTexture = function (texture) {
  18227. var serializationObject = {};
  18228. if (!texture.name) {
  18229. return null;
  18230. }
  18231. if (texture instanceof BABYLON.CubeTexture) {
  18232. serializationObject.name = texture.name;
  18233. serializationObject.hasAlpha = texture.hasAlpha;
  18234. serializationObject.level = texture.level;
  18235. serializationObject.coordinatesMode = texture.coordinatesMode;
  18236. return serializationObject;
  18237. }
  18238. if (texture instanceof BABYLON.MirrorTexture) {
  18239. var mirrorTexture = texture;
  18240. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18241. serializationObject.renderList = [];
  18242. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18243. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18244. }
  18245. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18246. }
  18247. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18248. var renderTargetTexture = texture;
  18249. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18250. serializationObject.renderList = [];
  18251. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18252. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18253. }
  18254. }
  18255. var regularTexture = texture;
  18256. serializationObject.name = texture.name;
  18257. serializationObject.hasAlpha = texture.hasAlpha;
  18258. serializationObject.level = texture.level;
  18259. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18260. serializationObject.coordinatesMode = texture.coordinatesMode;
  18261. serializationObject.uOffset = regularTexture.uOffset;
  18262. serializationObject.vOffset = regularTexture.vOffset;
  18263. serializationObject.uScale = regularTexture.uScale;
  18264. serializationObject.vScale = regularTexture.vScale;
  18265. serializationObject.uAng = regularTexture.uAng;
  18266. serializationObject.vAng = regularTexture.vAng;
  18267. serializationObject.wAng = regularTexture.wAng;
  18268. serializationObject.wrapU = texture.wrapU;
  18269. serializationObject.wrapV = texture.wrapV;
  18270. // Animations
  18271. appendAnimations(texture, serializationObject);
  18272. return serializationObject;
  18273. };
  18274. var serializeSkeleton = function (skeleton) {
  18275. var serializationObject = {};
  18276. serializationObject.name = skeleton.name;
  18277. serializationObject.id = skeleton.id;
  18278. serializationObject.bones = [];
  18279. for (var index = 0; index < skeleton.bones.length; index++) {
  18280. var bone = skeleton.bones[index];
  18281. var serializedBone = {
  18282. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18283. name: bone.name,
  18284. matrix: bone.getLocalMatrix().toArray()
  18285. };
  18286. serializationObject.bones.push(serializedBone);
  18287. if (bone.animations && bone.animations.length > 0) {
  18288. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18289. }
  18290. }
  18291. return serializationObject;
  18292. };
  18293. var serializeParticleSystem = function (particleSystem) {
  18294. var serializationObject = {};
  18295. serializationObject.emitterId = particleSystem.emitter.id;
  18296. serializationObject.capacity = particleSystem.getCapacity();
  18297. if (particleSystem.particleTexture) {
  18298. serializationObject.textureName = particleSystem.particleTexture.name;
  18299. }
  18300. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18301. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18302. serializationObject.minSize = particleSystem.minSize;
  18303. serializationObject.maxSize = particleSystem.maxSize;
  18304. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18305. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18306. serializationObject.emitRate = particleSystem.emitRate;
  18307. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18308. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18309. serializationObject.gravity = particleSystem.gravity.asArray();
  18310. serializationObject.direction1 = particleSystem.direction1.asArray();
  18311. serializationObject.direction2 = particleSystem.direction2.asArray();
  18312. serializationObject.color1 = particleSystem.color1.asArray();
  18313. serializationObject.color2 = particleSystem.color2.asArray();
  18314. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18315. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18316. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18317. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18318. serializationObject.blendMode = particleSystem.blendMode;
  18319. return serializationObject;
  18320. };
  18321. var serializeLensFlareSystem = function (lensFlareSystem) {
  18322. var serializationObject = {};
  18323. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18324. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18325. serializationObject.flares = [];
  18326. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18327. var flare = lensFlareSystem.lensFlares[index];
  18328. serializationObject.flares.push({
  18329. size: flare.size,
  18330. position: flare.position,
  18331. color: flare.color.asArray(),
  18332. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18333. });
  18334. }
  18335. return serializationObject;
  18336. };
  18337. var serializeShadowGenerator = function (light) {
  18338. var serializationObject = {};
  18339. var shadowGenerator = light.getShadowGenerator();
  18340. serializationObject.lightId = light.id;
  18341. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18342. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18343. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18344. serializationObject.renderList = [];
  18345. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18346. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18347. serializationObject.renderList.push(mesh.id);
  18348. }
  18349. return serializationObject;
  18350. };
  18351. var serializedGeometries = [];
  18352. var serializeGeometry = function (geometry, serializationGeometries) {
  18353. if (serializedGeometries[geometry.id]) {
  18354. return;
  18355. }
  18356. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18357. serializationGeometries.boxes.push(serializeBox(geometry));
  18358. }
  18359. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18360. serializationGeometries.spheres.push(serializeSphere(geometry));
  18361. }
  18362. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18363. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18364. }
  18365. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18366. serializationGeometries.toruses.push(serializeTorus(geometry));
  18367. }
  18368. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18369. serializationGeometries.grounds.push(serializeGround(geometry));
  18370. }
  18371. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18372. serializationGeometries.planes.push(serializePlane(geometry));
  18373. }
  18374. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18375. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18376. }
  18377. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18378. throw new Error("Unknow primitive type");
  18379. }
  18380. else {
  18381. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18382. }
  18383. serializedGeometries[geometry.id] = true;
  18384. };
  18385. var serializeGeometryBase = function (geometry) {
  18386. var serializationObject = {};
  18387. serializationObject.id = geometry.id;
  18388. if (BABYLON.Tags.HasTags(geometry)) {
  18389. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18390. }
  18391. return serializationObject;
  18392. };
  18393. var serializeVertexData = function (vertexData) {
  18394. var serializationObject = serializeGeometryBase(vertexData);
  18395. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18396. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18397. }
  18398. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18399. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18400. }
  18401. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18402. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18403. }
  18404. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18405. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18406. }
  18407. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18408. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18409. }
  18410. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18411. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18412. serializationObject.matricesIndices._isExpanded = true;
  18413. }
  18414. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18415. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18416. }
  18417. serializationObject.indices = vertexData.getIndices();
  18418. return serializationObject;
  18419. };
  18420. var serializePrimitive = function (primitive) {
  18421. var serializationObject = serializeGeometryBase(primitive);
  18422. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18423. return serializationObject;
  18424. };
  18425. var serializeBox = function (box) {
  18426. var serializationObject = serializePrimitive(box);
  18427. serializationObject.size = box.size;
  18428. return serializationObject;
  18429. };
  18430. var serializeSphere = function (sphere) {
  18431. var serializationObject = serializePrimitive(sphere);
  18432. serializationObject.segments = sphere.segments;
  18433. serializationObject.diameter = sphere.diameter;
  18434. return serializationObject;
  18435. };
  18436. var serializeCylinder = function (cylinder) {
  18437. var serializationObject = serializePrimitive(cylinder);
  18438. serializationObject.height = cylinder.height;
  18439. serializationObject.diameterTop = cylinder.diameterTop;
  18440. serializationObject.diameterBottom = cylinder.diameterBottom;
  18441. serializationObject.tessellation = cylinder.tessellation;
  18442. return serializationObject;
  18443. };
  18444. var serializeTorus = function (torus) {
  18445. var serializationObject = serializePrimitive(torus);
  18446. serializationObject.diameter = torus.diameter;
  18447. serializationObject.thickness = torus.thickness;
  18448. serializationObject.tessellation = torus.tessellation;
  18449. return serializationObject;
  18450. };
  18451. var serializeGround = function (ground) {
  18452. var serializationObject = serializePrimitive(ground);
  18453. serializationObject.width = ground.width;
  18454. serializationObject.height = ground.height;
  18455. serializationObject.subdivisions = ground.subdivisions;
  18456. return serializationObject;
  18457. };
  18458. var serializePlane = function (plane) {
  18459. var serializationObject = serializePrimitive(plane);
  18460. serializationObject.size = plane.size;
  18461. return serializationObject;
  18462. };
  18463. var serializeTorusKnot = function (torusKnot) {
  18464. var serializationObject = serializePrimitive(torusKnot);
  18465. serializationObject.radius = torusKnot.radius;
  18466. serializationObject.tube = torusKnot.tube;
  18467. serializationObject.radialSegments = torusKnot.radialSegments;
  18468. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18469. serializationObject.p = torusKnot.p;
  18470. serializationObject.q = torusKnot.q;
  18471. return serializationObject;
  18472. };
  18473. var serializeMesh = function (mesh, serializationScene) {
  18474. var serializationObject = {};
  18475. serializationObject.name = mesh.name;
  18476. serializationObject.id = mesh.id;
  18477. if (BABYLON.Tags.HasTags(mesh)) {
  18478. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18479. }
  18480. serializationObject.position = mesh.position.asArray();
  18481. if (mesh.rotationQuaternion) {
  18482. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18483. }
  18484. else if (mesh.rotation) {
  18485. serializationObject.rotation = mesh.rotation.asArray();
  18486. }
  18487. serializationObject.scaling = mesh.scaling.asArray();
  18488. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18489. serializationObject.isEnabled = mesh.isEnabled();
  18490. serializationObject.isVisible = mesh.isVisible;
  18491. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18492. serializationObject.pickable = mesh.isPickable;
  18493. serializationObject.receiveShadows = mesh.receiveShadows;
  18494. serializationObject.billboardMode = mesh.billboardMode;
  18495. serializationObject.visibility = mesh.visibility;
  18496. serializationObject.checkCollisions = mesh.checkCollisions;
  18497. // Parent
  18498. if (mesh.parent) {
  18499. serializationObject.parentId = mesh.parent.id;
  18500. }
  18501. // Geometry
  18502. var geometry = mesh._geometry;
  18503. if (geometry) {
  18504. var geometryId = geometry.id;
  18505. serializationObject.geometryId = geometryId;
  18506. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18507. // 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
  18508. serializeGeometry(geometry, serializationScene.geometries);
  18509. }
  18510. // SubMeshes
  18511. serializationObject.subMeshes = [];
  18512. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18513. var subMesh = mesh.subMeshes[subIndex];
  18514. serializationObject.subMeshes.push({
  18515. materialIndex: subMesh.materialIndex,
  18516. verticesStart: subMesh.verticesStart,
  18517. verticesCount: subMesh.verticesCount,
  18518. indexStart: subMesh.indexStart,
  18519. indexCount: subMesh.indexCount
  18520. });
  18521. }
  18522. }
  18523. // Material
  18524. if (mesh.material) {
  18525. serializationObject.materialId = mesh.material.id;
  18526. }
  18527. else {
  18528. mesh.material = null;
  18529. }
  18530. // Skeleton
  18531. if (mesh.skeleton) {
  18532. serializationObject.skeletonId = mesh.skeleton.id;
  18533. }
  18534. // Physics
  18535. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18536. serializationObject.physicsMass = mesh.getPhysicsMass();
  18537. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18538. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18539. switch (mesh.getPhysicsImpostor()) {
  18540. case BABYLON.PhysicsEngine.BoxImpostor:
  18541. serializationObject.physicsImpostor = 1;
  18542. break;
  18543. case BABYLON.PhysicsEngine.SphereImpostor:
  18544. serializationObject.physicsImpostor = 2;
  18545. break;
  18546. }
  18547. }
  18548. // Instances
  18549. serializationObject.instances = [];
  18550. for (var index = 0; index < mesh.instances.length; index++) {
  18551. var instance = mesh.instances[index];
  18552. var serializationInstance = {
  18553. name: instance.name,
  18554. position: instance.position,
  18555. rotation: instance.rotation,
  18556. rotationQuaternion: instance.rotationQuaternion,
  18557. scaling: instance.scaling
  18558. };
  18559. serializationObject.instances.push(serializationInstance);
  18560. // Animations
  18561. appendAnimations(instance, serializationInstance);
  18562. }
  18563. // Animations
  18564. appendAnimations(mesh, serializationObject);
  18565. // Layer mask
  18566. serializationObject.layerMask = mesh.layerMask;
  18567. return serializationObject;
  18568. };
  18569. var SceneSerializer = (function () {
  18570. function SceneSerializer() {
  18571. }
  18572. SceneSerializer.Serialize = function (scene) {
  18573. var serializationObject = {};
  18574. // Scene
  18575. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18576. serializationObject.autoClear = scene.autoClear;
  18577. serializationObject.clearColor = scene.clearColor.asArray();
  18578. serializationObject.ambientColor = scene.ambientColor.asArray();
  18579. serializationObject.gravity = scene.gravity.asArray();
  18580. // Fog
  18581. if (scene.fogMode && scene.fogMode !== 0) {
  18582. serializationObject.fogMode = scene.fogMode;
  18583. serializationObject.fogColor = scene.fogColor.asArray();
  18584. serializationObject.fogStart = scene.fogStart;
  18585. serializationObject.fogEnd = scene.fogEnd;
  18586. serializationObject.fogDensity = scene.fogDensity;
  18587. }
  18588. // Lights
  18589. serializationObject.lights = [];
  18590. for (var index = 0; index < scene.lights.length; index++) {
  18591. var light = scene.lights[index];
  18592. serializationObject.lights.push(serializeLight(light));
  18593. }
  18594. // Cameras
  18595. serializationObject.cameras = [];
  18596. for (index = 0; index < scene.cameras.length; index++) {
  18597. var camera = scene.cameras[index];
  18598. serializationObject.cameras.push(serializeCamera(camera));
  18599. }
  18600. if (scene.activeCamera) {
  18601. serializationObject.activeCameraID = scene.activeCamera.id;
  18602. }
  18603. // Materials
  18604. serializationObject.materials = [];
  18605. serializationObject.multiMaterials = [];
  18606. for (index = 0; index < scene.materials.length; index++) {
  18607. var material = scene.materials[index];
  18608. if (material instanceof BABYLON.StandardMaterial) {
  18609. serializationObject.materials.push(serializeMaterial(material));
  18610. }
  18611. else if (material instanceof BABYLON.MultiMaterial) {
  18612. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18613. }
  18614. }
  18615. // Skeletons
  18616. serializationObject.skeletons = [];
  18617. for (index = 0; index < scene.skeletons.length; index++) {
  18618. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18619. }
  18620. // Geometries
  18621. serializationObject.geometries = {};
  18622. serializationObject.geometries.boxes = [];
  18623. serializationObject.geometries.spheres = [];
  18624. serializationObject.geometries.cylinders = [];
  18625. serializationObject.geometries.toruses = [];
  18626. serializationObject.geometries.grounds = [];
  18627. serializationObject.geometries.planes = [];
  18628. serializationObject.geometries.torusKnots = [];
  18629. serializationObject.geometries.vertexData = [];
  18630. serializedGeometries = [];
  18631. var geometries = scene.getGeometries();
  18632. for (var index = 0; index < geometries.length; index++) {
  18633. var geometry = geometries[index];
  18634. if (geometry.isReady()) {
  18635. serializeGeometry(geometry, serializationObject.geometries);
  18636. }
  18637. }
  18638. // Meshes
  18639. serializationObject.meshes = [];
  18640. for (index = 0; index < scene.meshes.length; index++) {
  18641. var abstractMesh = scene.meshes[index];
  18642. if (abstractMesh instanceof BABYLON.Mesh) {
  18643. var mesh = abstractMesh;
  18644. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18645. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18646. }
  18647. }
  18648. }
  18649. // Particles Systems
  18650. serializationObject.particleSystems = [];
  18651. for (index = 0; index < scene.particleSystems.length; index++) {
  18652. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18653. }
  18654. // Lens flares
  18655. serializationObject.lensFlareSystems = [];
  18656. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18657. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18658. }
  18659. // Shadows
  18660. serializationObject.shadowGenerators = [];
  18661. for (index = 0; index < scene.lights.length; index++) {
  18662. light = scene.lights[index];
  18663. if (light.getShadowGenerator()) {
  18664. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18665. }
  18666. }
  18667. return serializationObject;
  18668. };
  18669. return SceneSerializer;
  18670. })();
  18671. BABYLON.SceneSerializer = SceneSerializer;
  18672. })(BABYLON || (BABYLON = {}));
  18673. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18674. (function (BABYLON) {
  18675. var SceneLoader = (function () {
  18676. function SceneLoader() {
  18677. }
  18678. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18679. get: function () {
  18680. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18681. },
  18682. set: function (value) {
  18683. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18689. get: function () {
  18690. return SceneLoader._ShowLoadingScreen;
  18691. },
  18692. set: function (value) {
  18693. SceneLoader._ShowLoadingScreen = value;
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18699. var dotPosition = sceneFilename.lastIndexOf(".");
  18700. var queryStringPosition = sceneFilename.indexOf("?");
  18701. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18702. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18703. var plugin = this._registeredPlugins[index];
  18704. if (plugin.extensions.indexOf(extension) !== -1) {
  18705. return plugin;
  18706. }
  18707. }
  18708. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18709. };
  18710. // Public functions
  18711. SceneLoader.RegisterPlugin = function (plugin) {
  18712. plugin.extensions = plugin.extensions.toLowerCase();
  18713. SceneLoader._registeredPlugins.push(plugin);
  18714. };
  18715. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18716. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18717. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18718. return;
  18719. }
  18720. var manifestChecked = function (success) {
  18721. scene.database = database;
  18722. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18723. var importMeshFromData = function (data) {
  18724. var meshes = [];
  18725. var particleSystems = [];
  18726. var skeletons = [];
  18727. try {
  18728. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18729. if (onerror) {
  18730. onerror(scene, 'unable to load the scene');
  18731. }
  18732. return;
  18733. }
  18734. }
  18735. catch (e) {
  18736. if (onerror) {
  18737. onerror(scene, e);
  18738. }
  18739. return;
  18740. }
  18741. if (onsuccess) {
  18742. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18743. onsuccess(meshes, particleSystems, skeletons);
  18744. }
  18745. };
  18746. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18747. // Direct load
  18748. importMeshFromData(sceneFilename.substr(5));
  18749. return;
  18750. }
  18751. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18752. importMeshFromData(data);
  18753. }, progressCallBack, database);
  18754. };
  18755. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18756. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18757. };
  18758. /**
  18759. * Load a scene
  18760. * @param rootUrl a string that defines the root url for scene and resources
  18761. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18762. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18763. */
  18764. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18765. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18766. };
  18767. /**
  18768. * Append a scene
  18769. * @param rootUrl a string that defines the root url for scene and resources
  18770. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18771. * @param scene is the instance of BABYLON.Scene to append to
  18772. */
  18773. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18774. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18775. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18776. return;
  18777. }
  18778. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18779. var database;
  18780. if (SceneLoader.ShowLoadingScreen) {
  18781. scene.getEngine().displayLoadingUI();
  18782. }
  18783. var loadSceneFromData = function (data) {
  18784. scene.database = database;
  18785. if (!plugin.load(scene, data, rootUrl)) {
  18786. if (onerror) {
  18787. onerror(scene);
  18788. }
  18789. scene.getEngine().hideLoadingUI();
  18790. return;
  18791. }
  18792. if (onsuccess) {
  18793. onsuccess(scene);
  18794. }
  18795. if (SceneLoader.ShowLoadingScreen) {
  18796. scene.executeWhenReady(function () {
  18797. scene.getEngine().hideLoadingUI();
  18798. });
  18799. }
  18800. };
  18801. var manifestChecked = function (success) {
  18802. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18803. };
  18804. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18805. // Direct load
  18806. loadSceneFromData(sceneFilename.substr(5));
  18807. return;
  18808. }
  18809. if (rootUrl.indexOf("file:") === -1) {
  18810. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18811. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18812. }
  18813. else {
  18814. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18815. }
  18816. };
  18817. // Flags
  18818. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18819. SceneLoader._ShowLoadingScreen = true;
  18820. // Members
  18821. SceneLoader._registeredPlugins = new Array();
  18822. return SceneLoader;
  18823. })();
  18824. BABYLON.SceneLoader = SceneLoader;
  18825. ;
  18826. })(BABYLON || (BABYLON = {}));
  18827. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18828. (function (BABYLON) {
  18829. var Internals;
  18830. (function (Internals) {
  18831. var checkColors4 = function (colors, count) {
  18832. // Check if color3 was used
  18833. if (colors.length === count * 3) {
  18834. var colors4 = [];
  18835. for (var index = 0; index < colors.length; index += 3) {
  18836. var newIndex = (index / 3) * 4;
  18837. colors4[newIndex] = colors[index];
  18838. colors4[newIndex + 1] = colors[index + 1];
  18839. colors4[newIndex + 2] = colors[index + 2];
  18840. colors4[newIndex + 3] = 1.0;
  18841. }
  18842. return colors4;
  18843. }
  18844. return colors;
  18845. };
  18846. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18847. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18848. texture.name = parsedTexture.name;
  18849. texture.hasAlpha = parsedTexture.hasAlpha;
  18850. texture.level = parsedTexture.level;
  18851. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18852. return texture;
  18853. };
  18854. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18855. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18856. return null;
  18857. }
  18858. if (parsedTexture.isCube) {
  18859. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18860. }
  18861. var texture;
  18862. if (parsedTexture.mirrorPlane) {
  18863. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18864. texture._waitingRenderList = parsedTexture.renderList;
  18865. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18866. }
  18867. else if (parsedTexture.isRenderTarget) {
  18868. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18869. texture._waitingRenderList = parsedTexture.renderList;
  18870. }
  18871. else {
  18872. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18873. }
  18874. texture.name = parsedTexture.name;
  18875. texture.hasAlpha = parsedTexture.hasAlpha;
  18876. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18877. texture.level = parsedTexture.level;
  18878. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18879. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18880. texture.uOffset = parsedTexture.uOffset;
  18881. texture.vOffset = parsedTexture.vOffset;
  18882. texture.uScale = parsedTexture.uScale;
  18883. texture.vScale = parsedTexture.vScale;
  18884. texture.uAng = parsedTexture.uAng;
  18885. texture.vAng = parsedTexture.vAng;
  18886. texture.wAng = parsedTexture.wAng;
  18887. texture.wrapU = parsedTexture.wrapU;
  18888. texture.wrapV = parsedTexture.wrapV;
  18889. // Animations
  18890. if (parsedTexture.animations) {
  18891. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18892. var parsedAnimation = parsedTexture.animations[animationIndex];
  18893. texture.animations.push(parseAnimation(parsedAnimation));
  18894. }
  18895. }
  18896. return texture;
  18897. };
  18898. var parseSkeleton = function (parsedSkeleton, scene) {
  18899. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18900. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18901. var parsedBone = parsedSkeleton.bones[index];
  18902. var parentBone = null;
  18903. if (parsedBone.parentBoneIndex > -1) {
  18904. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18905. }
  18906. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18907. if (parsedBone.animation) {
  18908. bone.animations.push(parseAnimation(parsedBone.animation));
  18909. }
  18910. }
  18911. return skeleton;
  18912. };
  18913. var parseFresnelParameters = function (parsedFresnelParameters) {
  18914. var fresnelParameters = new BABYLON.FresnelParameters();
  18915. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18916. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18917. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18918. fresnelParameters.bias = parsedFresnelParameters.bias;
  18919. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18920. return fresnelParameters;
  18921. };
  18922. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18923. var material;
  18924. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18925. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18926. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18927. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18928. material.specularPower = parsedMaterial.specularPower;
  18929. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18930. material.alpha = parsedMaterial.alpha;
  18931. material.id = parsedMaterial.id;
  18932. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18933. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18934. material.wireframe = parsedMaterial.wireframe;
  18935. if (parsedMaterial.diffuseTexture) {
  18936. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18937. }
  18938. if (parsedMaterial.diffuseFresnelParameters) {
  18939. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18940. }
  18941. if (parsedMaterial.ambientTexture) {
  18942. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18943. }
  18944. if (parsedMaterial.opacityTexture) {
  18945. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18946. }
  18947. if (parsedMaterial.opacityFresnelParameters) {
  18948. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18949. }
  18950. if (parsedMaterial.reflectionTexture) {
  18951. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18952. }
  18953. if (parsedMaterial.reflectionFresnelParameters) {
  18954. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18955. }
  18956. if (parsedMaterial.emissiveTexture) {
  18957. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18958. }
  18959. if (parsedMaterial.emissiveFresnelParameters) {
  18960. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18961. }
  18962. if (parsedMaterial.specularTexture) {
  18963. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18964. }
  18965. if (parsedMaterial.bumpTexture) {
  18966. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18967. }
  18968. return material;
  18969. };
  18970. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18971. for (var index = 0; index < parsedData.materials.length; index++) {
  18972. var parsedMaterial = parsedData.materials[index];
  18973. if (parsedMaterial.id === id) {
  18974. return parseMaterial(parsedMaterial, scene, rootUrl);
  18975. }
  18976. }
  18977. return null;
  18978. };
  18979. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18980. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18981. multiMaterial.id = parsedMultiMaterial.id;
  18982. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18983. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18984. var subMatId = parsedMultiMaterial.materials[matIndex];
  18985. if (subMatId) {
  18986. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18987. }
  18988. else {
  18989. multiMaterial.subMaterials.push(null);
  18990. }
  18991. }
  18992. return multiMaterial;
  18993. };
  18994. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18995. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18996. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18997. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18998. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18999. var parsedFlare = parsedLensFlareSystem.flares[index];
  19000. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19001. }
  19002. return lensFlareSystem;
  19003. };
  19004. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19005. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19006. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19007. if (parsedParticleSystem.textureName) {
  19008. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19009. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19010. }
  19011. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19012. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19013. particleSystem.minSize = parsedParticleSystem.minSize;
  19014. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19015. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19016. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19017. particleSystem.emitter = emitter;
  19018. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19019. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19020. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19021. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19022. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19023. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19024. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19025. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19026. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19027. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19028. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19029. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19030. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19031. particleSystem.start();
  19032. return particleSystem;
  19033. };
  19034. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19035. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19036. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19037. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19038. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19039. shadowGenerator.getShadowMap().renderList.push(mesh);
  19040. }
  19041. if (parsedShadowGenerator.usePoissonSampling) {
  19042. shadowGenerator.usePoissonSampling = true;
  19043. }
  19044. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19045. shadowGenerator.useVarianceShadowMap = true;
  19046. }
  19047. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19048. shadowGenerator.useBlurVarianceShadowMap = true;
  19049. }
  19050. if (parsedShadowGenerator.bias) {
  19051. shadowGenerator.bias = parsedShadowGenerator.bias;
  19052. }
  19053. return shadowGenerator;
  19054. };
  19055. var parseAnimation = function (parsedAnimation) {
  19056. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19057. var dataType = parsedAnimation.dataType;
  19058. var keys = [];
  19059. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19060. var key = parsedAnimation.keys[index];
  19061. var data;
  19062. switch (dataType) {
  19063. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19064. data = key.values[0];
  19065. break;
  19066. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19067. data = BABYLON.Quaternion.FromArray(key.values);
  19068. break;
  19069. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19070. data = BABYLON.Matrix.FromArray(key.values);
  19071. break;
  19072. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19073. default:
  19074. data = BABYLON.Vector3.FromArray(key.values);
  19075. break;
  19076. }
  19077. keys.push({
  19078. frame: key.frame,
  19079. value: data
  19080. });
  19081. }
  19082. animation.setKeys(keys);
  19083. return animation;
  19084. };
  19085. var parseLight = function (parsedLight, scene) {
  19086. var light;
  19087. switch (parsedLight.type) {
  19088. case 0:
  19089. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19090. break;
  19091. case 1:
  19092. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19093. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19094. break;
  19095. case 2:
  19096. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19097. break;
  19098. case 3:
  19099. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19100. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19101. break;
  19102. }
  19103. light.id = parsedLight.id;
  19104. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19105. if (parsedLight.intensity !== undefined) {
  19106. light.intensity = parsedLight.intensity;
  19107. }
  19108. if (parsedLight.range) {
  19109. light.range = parsedLight.range;
  19110. }
  19111. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19112. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19113. if (parsedLight.excludedMeshesIds) {
  19114. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19115. }
  19116. // Parent
  19117. if (parsedLight.parentId) {
  19118. light._waitingParentId = parsedLight.parentId;
  19119. }
  19120. if (parsedLight.includedOnlyMeshesIds) {
  19121. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19122. }
  19123. // Animations
  19124. if (parsedLight.animations) {
  19125. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19126. var parsedAnimation = parsedLight.animations[animationIndex];
  19127. light.animations.push(parseAnimation(parsedAnimation));
  19128. }
  19129. }
  19130. if (parsedLight.autoAnimate) {
  19131. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19132. }
  19133. };
  19134. var parseCamera = function (parsedCamera, scene) {
  19135. var camera;
  19136. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19137. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19138. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19139. var alpha = parsedCamera.alpha;
  19140. var beta = parsedCamera.beta;
  19141. var radius = parsedCamera.radius;
  19142. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19143. var eye_space = parsedCamera.eye_space;
  19144. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19145. }
  19146. else {
  19147. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19148. }
  19149. }
  19150. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19151. eye_space = parsedCamera.eye_space;
  19152. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19153. }
  19154. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19155. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19156. }
  19157. else if (parsedCamera.type === "FollowCamera") {
  19158. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19159. camera.heightOffset = parsedCamera.heightOffset;
  19160. camera.radius = parsedCamera.radius;
  19161. camera.rotationOffset = parsedCamera.rotationOffset;
  19162. if (lockedTargetMesh)
  19163. camera.target = lockedTargetMesh;
  19164. }
  19165. else if (parsedCamera.type === "GamepadCamera") {
  19166. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19167. }
  19168. else if (parsedCamera.type === "OculusCamera") {
  19169. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19170. }
  19171. else if (parsedCamera.type === "OculusGamepadCamera") {
  19172. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19173. }
  19174. else if (parsedCamera.type === "TouchCamera") {
  19175. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19176. }
  19177. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19178. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19179. }
  19180. else if (parsedCamera.type === "WebVRCamera") {
  19181. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19182. }
  19183. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19184. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19185. }
  19186. else {
  19187. // Free Camera is the default value
  19188. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19189. }
  19190. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19191. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19192. camera.lockedTarget = lockedTargetMesh;
  19193. }
  19194. camera.id = parsedCamera.id;
  19195. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19196. // Parent
  19197. if (parsedCamera.parentId) {
  19198. camera._waitingParentId = parsedCamera.parentId;
  19199. }
  19200. // Target
  19201. if (parsedCamera.target) {
  19202. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19203. }
  19204. else {
  19205. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19206. }
  19207. camera.fov = parsedCamera.fov;
  19208. camera.minZ = parsedCamera.minZ;
  19209. camera.maxZ = parsedCamera.maxZ;
  19210. camera.speed = parsedCamera.speed;
  19211. camera.inertia = parsedCamera.inertia;
  19212. camera.checkCollisions = parsedCamera.checkCollisions;
  19213. camera.applyGravity = parsedCamera.applyGravity;
  19214. if (parsedCamera.ellipsoid) {
  19215. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19216. }
  19217. // Animations
  19218. if (parsedCamera.animations) {
  19219. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19220. var parsedAnimation = parsedCamera.animations[animationIndex];
  19221. camera.animations.push(parseAnimation(parsedAnimation));
  19222. }
  19223. }
  19224. if (parsedCamera.autoAnimate) {
  19225. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19226. }
  19227. // Layer Mask
  19228. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19229. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19230. }
  19231. else {
  19232. camera.layerMask = 0xFFFFFFFF;
  19233. }
  19234. return camera;
  19235. };
  19236. var parseGeometry = function (parsedGeometry, scene) {
  19237. var id = parsedGeometry.id;
  19238. return scene.getGeometryByID(id);
  19239. };
  19240. var parseBox = function (parsedBox, scene) {
  19241. if (parseGeometry(parsedBox, scene)) {
  19242. return null; // null since geometry could be something else than a box...
  19243. }
  19244. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19245. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19246. scene.pushGeometry(box, true);
  19247. return box;
  19248. };
  19249. var parseSphere = function (parsedSphere, scene) {
  19250. if (parseGeometry(parsedSphere, scene)) {
  19251. return null; // null since geometry could be something else than a sphere...
  19252. }
  19253. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19254. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19255. scene.pushGeometry(sphere, true);
  19256. return sphere;
  19257. };
  19258. var parseCylinder = function (parsedCylinder, scene) {
  19259. if (parseGeometry(parsedCylinder, scene)) {
  19260. return null; // null since geometry could be something else than a cylinder...
  19261. }
  19262. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19263. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19264. scene.pushGeometry(cylinder, true);
  19265. return cylinder;
  19266. };
  19267. var parseTorus = function (parsedTorus, scene) {
  19268. if (parseGeometry(parsedTorus, scene)) {
  19269. return null; // null since geometry could be something else than a torus...
  19270. }
  19271. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19272. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19273. scene.pushGeometry(torus, true);
  19274. return torus;
  19275. };
  19276. var parseGround = function (parsedGround, scene) {
  19277. if (parseGeometry(parsedGround, scene)) {
  19278. return null; // null since geometry could be something else than a ground...
  19279. }
  19280. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19281. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19282. scene.pushGeometry(ground, true);
  19283. return ground;
  19284. };
  19285. var parsePlane = function (parsedPlane, scene) {
  19286. if (parseGeometry(parsedPlane, scene)) {
  19287. return null; // null since geometry could be something else than a plane...
  19288. }
  19289. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19290. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19291. scene.pushGeometry(plane, true);
  19292. return plane;
  19293. };
  19294. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19295. if (parseGeometry(parsedTorusKnot, scene)) {
  19296. return null; // null since geometry could be something else than a torusKnot...
  19297. }
  19298. 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);
  19299. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19300. scene.pushGeometry(torusKnot, true);
  19301. return torusKnot;
  19302. };
  19303. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19304. if (parseGeometry(parsedVertexData, scene)) {
  19305. return null; // null since geometry could be a primitive
  19306. }
  19307. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19308. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19309. if (parsedVertexData.delayLoadingFile) {
  19310. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19311. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19312. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19313. geometry._delayInfo = [];
  19314. if (parsedVertexData.hasUVs) {
  19315. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19316. }
  19317. if (parsedVertexData.hasUVs2) {
  19318. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19319. }
  19320. if (parsedVertexData.hasColors) {
  19321. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19322. }
  19323. if (parsedVertexData.hasMatricesIndices) {
  19324. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19325. }
  19326. if (parsedVertexData.hasMatricesWeights) {
  19327. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19328. }
  19329. geometry._delayLoadingFunction = importVertexData;
  19330. }
  19331. else {
  19332. importVertexData(parsedVertexData, geometry);
  19333. }
  19334. scene.pushGeometry(geometry, true);
  19335. return geometry;
  19336. };
  19337. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19338. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19339. mesh.id = parsedMesh.id;
  19340. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19341. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19342. if (parsedMesh.rotationQuaternion) {
  19343. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19344. }
  19345. else if (parsedMesh.rotation) {
  19346. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19347. }
  19348. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19349. if (parsedMesh.localMatrix) {
  19350. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19351. }
  19352. else if (parsedMesh.pivotMatrix) {
  19353. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19354. }
  19355. mesh.setEnabled(parsedMesh.isEnabled);
  19356. mesh.isVisible = parsedMesh.isVisible;
  19357. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19358. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19359. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19360. if (parsedMesh.applyFog !== undefined) {
  19361. mesh.applyFog = parsedMesh.applyFog;
  19362. }
  19363. if (parsedMesh.pickable !== undefined) {
  19364. mesh.isPickable = parsedMesh.pickable;
  19365. }
  19366. if (parsedMesh.alphaIndex !== undefined) {
  19367. mesh.alphaIndex = parsedMesh.alphaIndex;
  19368. }
  19369. mesh.receiveShadows = parsedMesh.receiveShadows;
  19370. mesh.billboardMode = parsedMesh.billboardMode;
  19371. if (parsedMesh.visibility !== undefined) {
  19372. mesh.visibility = parsedMesh.visibility;
  19373. }
  19374. mesh.checkCollisions = parsedMesh.checkCollisions;
  19375. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19376. // Parent
  19377. if (parsedMesh.parentId) {
  19378. mesh._waitingParentId = parsedMesh.parentId;
  19379. }
  19380. // Actions
  19381. if (parsedMesh.actions !== undefined) {
  19382. mesh._waitingActions = parsedMesh.actions;
  19383. }
  19384. // Geometry
  19385. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19386. if (parsedMesh.delayLoadingFile) {
  19387. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19388. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19389. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19390. if (parsedMesh._binaryInfo) {
  19391. mesh._binaryInfo = parsedMesh._binaryInfo;
  19392. }
  19393. mesh._delayInfo = [];
  19394. if (parsedMesh.hasUVs) {
  19395. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19396. }
  19397. if (parsedMesh.hasUVs2) {
  19398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19399. }
  19400. if (parsedMesh.hasColors) {
  19401. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19402. }
  19403. if (parsedMesh.hasMatricesIndices) {
  19404. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19405. }
  19406. if (parsedMesh.hasMatricesWeights) {
  19407. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19408. }
  19409. mesh._delayLoadingFunction = importGeometry;
  19410. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19411. mesh._checkDelayState();
  19412. }
  19413. }
  19414. else {
  19415. importGeometry(parsedMesh, mesh);
  19416. }
  19417. // Material
  19418. if (parsedMesh.materialId) {
  19419. mesh.setMaterialByID(parsedMesh.materialId);
  19420. }
  19421. else {
  19422. mesh.material = null;
  19423. }
  19424. // Skeleton
  19425. if (parsedMesh.skeletonId > -1) {
  19426. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19427. }
  19428. // Physics
  19429. if (parsedMesh.physicsImpostor) {
  19430. if (!scene.isPhysicsEnabled()) {
  19431. scene.enablePhysics();
  19432. }
  19433. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19434. }
  19435. // Animations
  19436. if (parsedMesh.animations) {
  19437. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19438. var parsedAnimation = parsedMesh.animations[animationIndex];
  19439. mesh.animations.push(parseAnimation(parsedAnimation));
  19440. }
  19441. }
  19442. if (parsedMesh.autoAnimate) {
  19443. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19444. }
  19445. // Layer Mask
  19446. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19447. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19448. }
  19449. else {
  19450. mesh.layerMask = 0xFFFFFFFF;
  19451. }
  19452. // Instances
  19453. if (parsedMesh.instances) {
  19454. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19455. var parsedInstance = parsedMesh.instances[index];
  19456. var instance = mesh.createInstance(parsedInstance.name);
  19457. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19458. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19459. if (parsedInstance.rotationQuaternion) {
  19460. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19461. }
  19462. else if (parsedInstance.rotation) {
  19463. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19464. }
  19465. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19466. instance.checkCollisions = mesh.checkCollisions;
  19467. if (parsedMesh.animations) {
  19468. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19469. parsedAnimation = parsedMesh.animations[animationIndex];
  19470. instance.animations.push(parseAnimation(parsedAnimation));
  19471. }
  19472. }
  19473. }
  19474. }
  19475. return mesh;
  19476. };
  19477. var parseActions = function (parsedActions, object, scene) {
  19478. var actionManager = new BABYLON.ActionManager(scene);
  19479. if (object === null)
  19480. scene.actionManager = actionManager;
  19481. else
  19482. object.actionManager = actionManager;
  19483. // instanciate a new object
  19484. var instanciate = function (name, params) {
  19485. var newInstance = Object.create(BABYLON[name].prototype);
  19486. newInstance.constructor.apply(newInstance, params);
  19487. return newInstance;
  19488. };
  19489. var parseParameter = function (name, value, target, propertyPath) {
  19490. if (propertyPath === null) {
  19491. // String, boolean or float
  19492. var floatValue = parseFloat(value);
  19493. if (value === "true" || value === "false")
  19494. return value === "true";
  19495. else
  19496. return isNaN(floatValue) ? value : floatValue;
  19497. }
  19498. var effectiveTarget = propertyPath.split(".");
  19499. var values = value.split(",");
  19500. for (var i = 0; i < effectiveTarget.length; i++) {
  19501. target = target[effectiveTarget[i]];
  19502. }
  19503. // Return appropriate value with its type
  19504. if (target instanceof Boolean)
  19505. return values[0] === "true";
  19506. if (target instanceof String)
  19507. return values[0];
  19508. // Parameters with multiple values such as Vector3 etc.
  19509. var split = new Array();
  19510. for (var i = 0; i < values.length; i++)
  19511. split.push(parseFloat(values[i]));
  19512. if (target instanceof BABYLON.Vector3)
  19513. return BABYLON.Vector3.FromArray(split);
  19514. if (target instanceof BABYLON.Vector4)
  19515. return BABYLON.Vector4.FromArray(split);
  19516. if (target instanceof BABYLON.Color3)
  19517. return BABYLON.Color3.FromArray(split);
  19518. if (target instanceof BABYLON.Color4)
  19519. return BABYLON.Color4.FromArray(split);
  19520. return parseFloat(values[0]);
  19521. };
  19522. // traverse graph per trigger
  19523. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19524. if (combineArray === void 0) { combineArray = null; }
  19525. if (parsedAction.detached)
  19526. return;
  19527. var parameters = new Array();
  19528. var target = null;
  19529. var propertyPath = null;
  19530. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19531. // Parameters
  19532. if (parsedAction.type === 2)
  19533. parameters.push(actionManager);
  19534. else
  19535. parameters.push(trigger);
  19536. if (combine) {
  19537. var actions = new Array();
  19538. for (var j = 0; j < parsedAction.combine.length; j++) {
  19539. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19540. }
  19541. parameters.push(actions);
  19542. }
  19543. else {
  19544. for (var i = 0; i < parsedAction.properties.length; i++) {
  19545. var value = parsedAction.properties[i].value;
  19546. var name = parsedAction.properties[i].name;
  19547. if (name === "target")
  19548. value = target = scene.getNodeByName(value);
  19549. else if (name === "parent")
  19550. value = scene.getNodeByName(value);
  19551. else if (name === "sound")
  19552. value = scene.getSoundByName(value);
  19553. else if (name !== "propertyPath") {
  19554. if (parsedAction.type === 2 && name === "operator")
  19555. value = BABYLON.ValueCondition[value];
  19556. else
  19557. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19558. }
  19559. else {
  19560. propertyPath = value;
  19561. }
  19562. parameters.push(value);
  19563. }
  19564. }
  19565. parameters.push(condition);
  19566. // If interpolate value action
  19567. if (parsedAction.name === "InterpolateValueAction") {
  19568. var param = parameters[parameters.length - 2];
  19569. parameters[parameters.length - 1] = param;
  19570. parameters[parameters.length - 2] = condition;
  19571. }
  19572. // Action or condition(s) and not CombineAction
  19573. var newAction = instanciate(parsedAction.name, parameters);
  19574. if (combineArray === null) {
  19575. if (newAction instanceof BABYLON.Condition) {
  19576. condition = newAction;
  19577. newAction = action;
  19578. }
  19579. else {
  19580. condition = null;
  19581. if (action)
  19582. action.then(newAction);
  19583. else
  19584. actionManager.registerAction(newAction);
  19585. }
  19586. }
  19587. else {
  19588. combineArray.push(newAction);
  19589. }
  19590. for (var i = 0; i < parsedAction.children.length; i++)
  19591. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19592. };
  19593. for (var i = 0; i < parsedActions.children.length; i++) {
  19594. var triggerParams;
  19595. var trigger = parsedActions.children[i];
  19596. if (trigger.properties.length > 0) {
  19597. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19598. }
  19599. else
  19600. triggerParams = BABYLON.ActionManager[trigger.name];
  19601. for (var j = 0; j < trigger.children.length; j++)
  19602. traverse(trigger.children[j], triggerParams, null, null);
  19603. }
  19604. };
  19605. var parseSound = function (parsedSound, scene, rootUrl) {
  19606. var soundName = parsedSound.name;
  19607. var soundUrl = rootUrl + soundName;
  19608. var options = {
  19609. autoplay: parsedSound.autoplay,
  19610. loop: parsedSound.loop,
  19611. volume: parsedSound.volume,
  19612. spatialSound: parsedSound.spatialSound,
  19613. maxDistance: parsedSound.maxDistance,
  19614. rolloffFactor: parsedSound.rolloffFactor,
  19615. refDistance: parsedSound.refDistance,
  19616. distanceModel: parsedSound.distanceModel,
  19617. panningModel: parsedSound.panningModel,
  19618. playbackRate: parsedSound.playbackRate
  19619. };
  19620. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19621. scene._removePendingData(newSound);
  19622. }, options);
  19623. scene._addPendingData(newSound);
  19624. if (parsedSound.position) {
  19625. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19626. newSound.setPosition(soundPosition);
  19627. }
  19628. if (parsedSound.isDirectional) {
  19629. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19630. if (parsedSound.localDirectionToMesh) {
  19631. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19632. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19633. }
  19634. }
  19635. if (parsedSound.connectedMeshId) {
  19636. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19637. if (connectedMesh) {
  19638. newSound.attachToMesh(connectedMesh);
  19639. }
  19640. }
  19641. };
  19642. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19643. names = (names instanceof Array) ? names : [names];
  19644. for (var i in names) {
  19645. if (mesh.name === names[i]) {
  19646. hierarchyIds.push(mesh.id);
  19647. return true;
  19648. }
  19649. }
  19650. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19651. hierarchyIds.push(mesh.id);
  19652. return true;
  19653. }
  19654. return false;
  19655. };
  19656. var importVertexData = function (parsedVertexData, geometry) {
  19657. var vertexData = new BABYLON.VertexData();
  19658. // positions
  19659. var positions = parsedVertexData.positions;
  19660. if (positions) {
  19661. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19662. }
  19663. // normals
  19664. var normals = parsedVertexData.normals;
  19665. if (normals) {
  19666. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19667. }
  19668. // uvs
  19669. var uvs = parsedVertexData.uvs;
  19670. if (uvs) {
  19671. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19672. }
  19673. // uv2s
  19674. var uv2s = parsedVertexData.uv2s;
  19675. if (uv2s) {
  19676. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19677. }
  19678. // colors
  19679. var colors = parsedVertexData.colors;
  19680. if (colors) {
  19681. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19682. }
  19683. // matricesIndices
  19684. var matricesIndices = parsedVertexData.matricesIndices;
  19685. if (matricesIndices) {
  19686. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19687. }
  19688. // matricesWeights
  19689. var matricesWeights = parsedVertexData.matricesWeights;
  19690. if (matricesWeights) {
  19691. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19692. }
  19693. // indices
  19694. var indices = parsedVertexData.indices;
  19695. if (indices) {
  19696. vertexData.indices = indices;
  19697. }
  19698. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19699. };
  19700. var importGeometry = function (parsedGeometry, mesh) {
  19701. var scene = mesh.getScene();
  19702. // Geometry
  19703. var geometryId = parsedGeometry.geometryId;
  19704. if (geometryId) {
  19705. var geometry = scene.getGeometryByID(geometryId);
  19706. if (geometry) {
  19707. geometry.applyToMesh(mesh);
  19708. }
  19709. }
  19710. else if (parsedGeometry instanceof ArrayBuffer) {
  19711. var binaryInfo = mesh._binaryInfo;
  19712. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19713. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19714. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19715. }
  19716. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19717. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19718. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19719. }
  19720. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19721. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19722. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19723. }
  19724. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19725. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19726. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19727. }
  19728. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19729. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19730. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19731. }
  19732. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19733. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19734. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19735. }
  19736. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19737. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19738. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19739. }
  19740. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19741. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19742. mesh.setIndices(indicesData);
  19743. }
  19744. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19745. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19746. mesh.subMeshes = [];
  19747. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19748. var materialIndex = subMeshesData[(i * 5) + 0];
  19749. var verticesStart = subMeshesData[(i * 5) + 1];
  19750. var verticesCount = subMeshesData[(i * 5) + 2];
  19751. var indexStart = subMeshesData[(i * 5) + 3];
  19752. var indexCount = subMeshesData[(i * 5) + 4];
  19753. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19754. }
  19755. }
  19756. }
  19757. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19758. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19759. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19760. if (parsedGeometry.uvs) {
  19761. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19762. }
  19763. if (parsedGeometry.uvs2) {
  19764. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19765. }
  19766. if (parsedGeometry.colors) {
  19767. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19768. }
  19769. if (parsedGeometry.matricesIndices) {
  19770. if (!parsedGeometry.matricesIndices._isExpanded) {
  19771. var floatIndices = [];
  19772. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19773. var matricesIndex = parsedGeometry.matricesIndices[i];
  19774. floatIndices.push(matricesIndex & 0x000000FF);
  19775. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19776. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19777. floatIndices.push(matricesIndex >> 24);
  19778. }
  19779. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19780. }
  19781. else {
  19782. delete parsedGeometry.matricesIndices._isExpanded;
  19783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19784. }
  19785. }
  19786. if (parsedGeometry.matricesWeights) {
  19787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19788. }
  19789. mesh.setIndices(parsedGeometry.indices);
  19790. // SubMeshes
  19791. if (parsedGeometry.subMeshes) {
  19792. mesh.subMeshes = [];
  19793. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19794. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19795. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19796. }
  19797. }
  19798. }
  19799. // Flat shading
  19800. if (mesh._shouldGenerateFlatShading) {
  19801. mesh.convertToFlatShadedMesh();
  19802. delete mesh._shouldGenerateFlatShading;
  19803. }
  19804. // Update
  19805. mesh.computeWorldMatrix(true);
  19806. // Octree
  19807. if (scene._selectionOctree) {
  19808. scene._selectionOctree.addMesh(mesh);
  19809. }
  19810. };
  19811. BABYLON.SceneLoader.RegisterPlugin({
  19812. extensions: ".babylon",
  19813. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19814. var parsedData = JSON.parse(data);
  19815. var loadedSkeletonsIds = [];
  19816. var loadedMaterialsIds = [];
  19817. var hierarchyIds = [];
  19818. for (var index = 0; index < parsedData.meshes.length; index++) {
  19819. var parsedMesh = parsedData.meshes[index];
  19820. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19821. if (meshesNames instanceof Array) {
  19822. // Remove found mesh name from list.
  19823. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19824. }
  19825. // Material ?
  19826. if (parsedMesh.materialId) {
  19827. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19828. if (!materialFound) {
  19829. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19830. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19831. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19832. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19833. var subMatId = parsedMultiMaterial.materials[matIndex];
  19834. loadedMaterialsIds.push(subMatId);
  19835. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19836. }
  19837. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19838. parseMultiMaterial(parsedMultiMaterial, scene);
  19839. materialFound = true;
  19840. break;
  19841. }
  19842. }
  19843. }
  19844. if (!materialFound) {
  19845. loadedMaterialsIds.push(parsedMesh.materialId);
  19846. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19847. }
  19848. }
  19849. // Skeleton ?
  19850. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19851. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19852. if (!skeletonAlreadyLoaded) {
  19853. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19854. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19855. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19856. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19857. loadedSkeletonsIds.push(parsedSkeleton.id);
  19858. }
  19859. }
  19860. }
  19861. }
  19862. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19863. meshes.push(mesh);
  19864. }
  19865. }
  19866. for (index = 0; index < scene.meshes.length; index++) {
  19867. var currentMesh = scene.meshes[index];
  19868. if (currentMesh._waitingParentId) {
  19869. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19870. currentMesh._waitingParentId = undefined;
  19871. }
  19872. }
  19873. // Particles
  19874. if (parsedData.particleSystems) {
  19875. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19876. var parsedParticleSystem = parsedData.particleSystems[index];
  19877. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19878. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19879. }
  19880. }
  19881. }
  19882. return true;
  19883. },
  19884. load: function (scene, data, rootUrl) {
  19885. var parsedData = JSON.parse(data);
  19886. // Scene
  19887. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19888. scene.autoClear = parsedData.autoClear;
  19889. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19890. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19891. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19892. // Fog
  19893. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19894. scene.fogMode = parsedData.fogMode;
  19895. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19896. scene.fogStart = parsedData.fogStart;
  19897. scene.fogEnd = parsedData.fogEnd;
  19898. scene.fogDensity = parsedData.fogDensity;
  19899. }
  19900. for (var index = 0; index < parsedData.lights.length; index++) {
  19901. var parsedLight = parsedData.lights[index];
  19902. parseLight(parsedLight, scene);
  19903. }
  19904. // Materials
  19905. if (parsedData.materials) {
  19906. for (index = 0; index < parsedData.materials.length; index++) {
  19907. var parsedMaterial = parsedData.materials[index];
  19908. parseMaterial(parsedMaterial, scene, rootUrl);
  19909. }
  19910. }
  19911. if (parsedData.multiMaterials) {
  19912. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19913. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19914. parseMultiMaterial(parsedMultiMaterial, scene);
  19915. }
  19916. }
  19917. // Skeletons
  19918. if (parsedData.skeletons) {
  19919. for (index = 0; index < parsedData.skeletons.length; index++) {
  19920. var parsedSkeleton = parsedData.skeletons[index];
  19921. parseSkeleton(parsedSkeleton, scene);
  19922. }
  19923. }
  19924. // Geometries
  19925. var geometries = parsedData.geometries;
  19926. if (geometries) {
  19927. // Boxes
  19928. var boxes = geometries.boxes;
  19929. if (boxes) {
  19930. for (index = 0; index < boxes.length; index++) {
  19931. var parsedBox = boxes[index];
  19932. parseBox(parsedBox, scene);
  19933. }
  19934. }
  19935. // Spheres
  19936. var spheres = geometries.spheres;
  19937. if (spheres) {
  19938. for (index = 0; index < spheres.length; index++) {
  19939. var parsedSphere = spheres[index];
  19940. parseSphere(parsedSphere, scene);
  19941. }
  19942. }
  19943. // Cylinders
  19944. var cylinders = geometries.cylinders;
  19945. if (cylinders) {
  19946. for (index = 0; index < cylinders.length; index++) {
  19947. var parsedCylinder = cylinders[index];
  19948. parseCylinder(parsedCylinder, scene);
  19949. }
  19950. }
  19951. // Toruses
  19952. var toruses = geometries.toruses;
  19953. if (toruses) {
  19954. for (index = 0; index < toruses.length; index++) {
  19955. var parsedTorus = toruses[index];
  19956. parseTorus(parsedTorus, scene);
  19957. }
  19958. }
  19959. // Grounds
  19960. var grounds = geometries.grounds;
  19961. if (grounds) {
  19962. for (index = 0; index < grounds.length; index++) {
  19963. var parsedGround = grounds[index];
  19964. parseGround(parsedGround, scene);
  19965. }
  19966. }
  19967. // Planes
  19968. var planes = geometries.planes;
  19969. if (planes) {
  19970. for (index = 0; index < planes.length; index++) {
  19971. var parsedPlane = planes[index];
  19972. parsePlane(parsedPlane, scene);
  19973. }
  19974. }
  19975. // TorusKnots
  19976. var torusKnots = geometries.torusKnots;
  19977. if (torusKnots) {
  19978. for (index = 0; index < torusKnots.length; index++) {
  19979. var parsedTorusKnot = torusKnots[index];
  19980. parseTorusKnot(parsedTorusKnot, scene);
  19981. }
  19982. }
  19983. // VertexData
  19984. var vertexData = geometries.vertexData;
  19985. if (vertexData) {
  19986. for (index = 0; index < vertexData.length; index++) {
  19987. var parsedVertexData = vertexData[index];
  19988. parseVertexData(parsedVertexData, scene, rootUrl);
  19989. }
  19990. }
  19991. }
  19992. for (index = 0; index < parsedData.meshes.length; index++) {
  19993. var parsedMesh = parsedData.meshes[index];
  19994. parseMesh(parsedMesh, scene, rootUrl);
  19995. }
  19996. for (index = 0; index < parsedData.cameras.length; index++) {
  19997. var parsedCamera = parsedData.cameras[index];
  19998. parseCamera(parsedCamera, scene);
  19999. }
  20000. if (parsedData.activeCameraID) {
  20001. scene.setActiveCameraByID(parsedData.activeCameraID);
  20002. }
  20003. for (index = 0; index < scene.cameras.length; index++) {
  20004. var camera = scene.cameras[index];
  20005. if (camera._waitingParentId) {
  20006. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20007. camera._waitingParentId = undefined;
  20008. }
  20009. }
  20010. for (index = 0; index < scene.lights.length; index++) {
  20011. var light = scene.lights[index];
  20012. if (light._waitingParentId) {
  20013. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20014. light._waitingParentId = undefined;
  20015. }
  20016. }
  20017. // Sounds
  20018. if (parsedData.sounds) {
  20019. for (index = 0; index < parsedData.sounds.length; index++) {
  20020. var parsedSound = parsedData.sounds[index];
  20021. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20022. parseSound(parsedSound, scene, rootUrl);
  20023. }
  20024. else {
  20025. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20026. }
  20027. }
  20028. }
  20029. for (index = 0; index < scene.meshes.length; index++) {
  20030. var mesh = scene.meshes[index];
  20031. if (mesh._waitingParentId) {
  20032. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20033. mesh._waitingParentId = undefined;
  20034. }
  20035. if (mesh._waitingActions) {
  20036. parseActions(mesh._waitingActions, mesh, scene);
  20037. mesh._waitingActions = undefined;
  20038. }
  20039. }
  20040. // Particles Systems
  20041. if (parsedData.particleSystems) {
  20042. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20043. var parsedParticleSystem = parsedData.particleSystems[index];
  20044. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20045. }
  20046. }
  20047. // Lens flares
  20048. if (parsedData.lensFlareSystems) {
  20049. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20050. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20051. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20052. }
  20053. }
  20054. // Shadows
  20055. if (parsedData.shadowGenerators) {
  20056. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20057. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20058. parseShadowGenerator(parsedShadowGenerator, scene);
  20059. }
  20060. }
  20061. // Actions (scene)
  20062. if (parsedData.actions) {
  20063. parseActions(parsedData.actions, null, scene);
  20064. }
  20065. // Finish
  20066. return true;
  20067. }
  20068. });
  20069. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20070. })(BABYLON || (BABYLON = {}));
  20071. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20072. (function (BABYLON) {
  20073. // Unique ID when we import meshes from Babylon to CSG
  20074. var currentCSGMeshId = 0;
  20075. // # class Vertex
  20076. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20077. // one to provide additional features like texture coordinates and vertex
  20078. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20079. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20080. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20081. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20082. // is not used anywhere else.
  20083. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20084. var Vertex = (function () {
  20085. function Vertex(pos, normal, uv) {
  20086. this.pos = pos;
  20087. this.normal = normal;
  20088. this.uv = uv;
  20089. }
  20090. Vertex.prototype.clone = function () {
  20091. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20092. };
  20093. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20094. // orientation of a polygon is flipped.
  20095. Vertex.prototype.flip = function () {
  20096. this.normal = this.normal.scale(-1);
  20097. };
  20098. // Create a new vertex between this vertex and `other` by linearly
  20099. // interpolating all properties using a parameter of `t`. Subclasses should
  20100. // override this to interpolate additional properties.
  20101. Vertex.prototype.interpolate = function (other, t) {
  20102. 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));
  20103. };
  20104. return Vertex;
  20105. })();
  20106. // # class Plane
  20107. // Represents a plane in 3D space.
  20108. var Plane = (function () {
  20109. function Plane(normal, w) {
  20110. this.normal = normal;
  20111. this.w = w;
  20112. }
  20113. Plane.FromPoints = function (a, b, c) {
  20114. var v0 = c.subtract(a);
  20115. var v1 = b.subtract(a);
  20116. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20117. return null;
  20118. }
  20119. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20120. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20121. };
  20122. Plane.prototype.clone = function () {
  20123. return new Plane(this.normal.clone(), this.w);
  20124. };
  20125. Plane.prototype.flip = function () {
  20126. this.normal.scaleInPlace(-1);
  20127. this.w = -this.w;
  20128. };
  20129. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20130. // fragments in the appropriate lists. Coplanar polygons go into either
  20131. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20132. // respect to this plane. Polygons in front or in back of this plane go into
  20133. // either `front` or `back`.
  20134. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20135. var COPLANAR = 0;
  20136. var FRONT = 1;
  20137. var BACK = 2;
  20138. var SPANNING = 3;
  20139. // Classify each point as well as the entire polygon into one of the above
  20140. // four classes.
  20141. var polygonType = 0;
  20142. var types = [];
  20143. for (var i = 0; i < polygon.vertices.length; i++) {
  20144. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20145. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20146. polygonType |= type;
  20147. types.push(type);
  20148. }
  20149. switch (polygonType) {
  20150. case COPLANAR:
  20151. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20152. break;
  20153. case FRONT:
  20154. front.push(polygon);
  20155. break;
  20156. case BACK:
  20157. back.push(polygon);
  20158. break;
  20159. case SPANNING:
  20160. var f = [], b = [];
  20161. for (i = 0; i < polygon.vertices.length; i++) {
  20162. var j = (i + 1) % polygon.vertices.length;
  20163. var ti = types[i], tj = types[j];
  20164. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20165. if (ti != BACK)
  20166. f.push(vi);
  20167. if (ti != FRONT)
  20168. b.push(ti != BACK ? vi.clone() : vi);
  20169. if ((ti | tj) == SPANNING) {
  20170. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20171. var v = vi.interpolate(vj, t);
  20172. f.push(v);
  20173. b.push(v.clone());
  20174. }
  20175. }
  20176. if (f.length >= 3) {
  20177. var poly = new Polygon(f, polygon.shared);
  20178. if (poly.plane)
  20179. front.push(poly);
  20180. }
  20181. if (b.length >= 3) {
  20182. poly = new Polygon(b, polygon.shared);
  20183. if (poly.plane)
  20184. back.push(poly);
  20185. }
  20186. break;
  20187. }
  20188. };
  20189. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20190. // point is on the plane.
  20191. Plane.EPSILON = 1e-5;
  20192. return Plane;
  20193. })();
  20194. // # class Polygon
  20195. // Represents a convex polygon. The vertices used to initialize a polygon must
  20196. // be coplanar and form a convex loop.
  20197. //
  20198. // Each convex polygon has a `shared` property, which is shared between all
  20199. // polygons that are clones of each other or were split from the same polygon.
  20200. // This can be used to define per-polygon properties (such as surface color).
  20201. var Polygon = (function () {
  20202. function Polygon(vertices, shared) {
  20203. this.vertices = vertices;
  20204. this.shared = shared;
  20205. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20206. }
  20207. Polygon.prototype.clone = function () {
  20208. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20209. return new Polygon(vertices, this.shared);
  20210. };
  20211. Polygon.prototype.flip = function () {
  20212. this.vertices.reverse().map(function (v) {
  20213. v.flip();
  20214. });
  20215. this.plane.flip();
  20216. };
  20217. return Polygon;
  20218. })();
  20219. // # class Node
  20220. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20221. // by picking a polygon to split along. That polygon (and all other coplanar
  20222. // polygons) are added directly to that node and the other polygons are added to
  20223. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20224. // no distinction between internal and leaf nodes.
  20225. var Node = (function () {
  20226. function Node(polygons) {
  20227. this.plane = null;
  20228. this.front = null;
  20229. this.back = null;
  20230. this.polygons = [];
  20231. if (polygons) {
  20232. this.build(polygons);
  20233. }
  20234. }
  20235. Node.prototype.clone = function () {
  20236. var node = new Node();
  20237. node.plane = this.plane && this.plane.clone();
  20238. node.front = this.front && this.front.clone();
  20239. node.back = this.back && this.back.clone();
  20240. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20241. return node;
  20242. };
  20243. // Convert solid space to empty space and empty space to solid space.
  20244. Node.prototype.invert = function () {
  20245. for (var i = 0; i < this.polygons.length; i++) {
  20246. this.polygons[i].flip();
  20247. }
  20248. if (this.plane) {
  20249. this.plane.flip();
  20250. }
  20251. if (this.front) {
  20252. this.front.invert();
  20253. }
  20254. if (this.back) {
  20255. this.back.invert();
  20256. }
  20257. var temp = this.front;
  20258. this.front = this.back;
  20259. this.back = temp;
  20260. };
  20261. // Recursively remove all polygons in `polygons` that are inside this BSP
  20262. // tree.
  20263. Node.prototype.clipPolygons = function (polygons) {
  20264. if (!this.plane)
  20265. return polygons.slice();
  20266. var front = [], back = [];
  20267. for (var i = 0; i < polygons.length; i++) {
  20268. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20269. }
  20270. if (this.front) {
  20271. front = this.front.clipPolygons(front);
  20272. }
  20273. if (this.back) {
  20274. back = this.back.clipPolygons(back);
  20275. }
  20276. else {
  20277. back = [];
  20278. }
  20279. return front.concat(back);
  20280. };
  20281. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20282. // `bsp`.
  20283. Node.prototype.clipTo = function (bsp) {
  20284. this.polygons = bsp.clipPolygons(this.polygons);
  20285. if (this.front)
  20286. this.front.clipTo(bsp);
  20287. if (this.back)
  20288. this.back.clipTo(bsp);
  20289. };
  20290. // Return a list of all polygons in this BSP tree.
  20291. Node.prototype.allPolygons = function () {
  20292. var polygons = this.polygons.slice();
  20293. if (this.front)
  20294. polygons = polygons.concat(this.front.allPolygons());
  20295. if (this.back)
  20296. polygons = polygons.concat(this.back.allPolygons());
  20297. return polygons;
  20298. };
  20299. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20300. // new polygons are filtered down to the bottom of the tree and become new
  20301. // nodes there. Each set of polygons is partitioned using the first polygon
  20302. // (no heuristic is used to pick a good split).
  20303. Node.prototype.build = function (polygons) {
  20304. if (!polygons.length)
  20305. return;
  20306. if (!this.plane)
  20307. this.plane = polygons[0].plane.clone();
  20308. var front = [], back = [];
  20309. for (var i = 0; i < polygons.length; i++) {
  20310. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20311. }
  20312. if (front.length) {
  20313. if (!this.front)
  20314. this.front = new Node();
  20315. this.front.build(front);
  20316. }
  20317. if (back.length) {
  20318. if (!this.back)
  20319. this.back = new Node();
  20320. this.back.build(back);
  20321. }
  20322. };
  20323. return Node;
  20324. })();
  20325. var CSG = (function () {
  20326. function CSG() {
  20327. this.polygons = new Array();
  20328. }
  20329. // Convert BABYLON.Mesh to BABYLON.CSG
  20330. CSG.FromMesh = function (mesh) {
  20331. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20332. if (mesh instanceof BABYLON.Mesh) {
  20333. mesh.computeWorldMatrix(true);
  20334. var matrix = mesh.getWorldMatrix();
  20335. var meshPosition = mesh.position.clone();
  20336. var meshRotation = mesh.rotation.clone();
  20337. var meshScaling = mesh.scaling.clone();
  20338. }
  20339. else {
  20340. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20341. }
  20342. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20343. var subMeshes = mesh.subMeshes;
  20344. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20345. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20346. vertices = [];
  20347. for (var j = 0; j < 3; j++) {
  20348. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20349. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20350. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20351. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20352. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20353. vertex = new Vertex(position, normal, uv);
  20354. vertices.push(vertex);
  20355. }
  20356. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20357. // To handle the case of degenerated triangle
  20358. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20359. if (polygon.plane)
  20360. polygons.push(polygon);
  20361. }
  20362. }
  20363. var csg = CSG.FromPolygons(polygons);
  20364. csg.matrix = matrix;
  20365. csg.position = meshPosition;
  20366. csg.rotation = meshRotation;
  20367. csg.scaling = meshScaling;
  20368. currentCSGMeshId++;
  20369. return csg;
  20370. };
  20371. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20372. CSG.FromPolygons = function (polygons) {
  20373. var csg = new BABYLON.CSG();
  20374. csg.polygons = polygons;
  20375. return csg;
  20376. };
  20377. CSG.prototype.clone = function () {
  20378. var csg = new BABYLON.CSG();
  20379. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20380. csg.copyTransformAttributes(this);
  20381. return csg;
  20382. };
  20383. CSG.prototype.toPolygons = function () {
  20384. return this.polygons;
  20385. };
  20386. CSG.prototype.union = function (csg) {
  20387. var a = new Node(this.clone().polygons);
  20388. var b = new Node(csg.clone().polygons);
  20389. a.clipTo(b);
  20390. b.clipTo(a);
  20391. b.invert();
  20392. b.clipTo(a);
  20393. b.invert();
  20394. a.build(b.allPolygons());
  20395. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20396. };
  20397. CSG.prototype.unionInPlace = function (csg) {
  20398. var a = new Node(this.polygons);
  20399. var b = new Node(csg.polygons);
  20400. a.clipTo(b);
  20401. b.clipTo(a);
  20402. b.invert();
  20403. b.clipTo(a);
  20404. b.invert();
  20405. a.build(b.allPolygons());
  20406. this.polygons = a.allPolygons();
  20407. };
  20408. CSG.prototype.subtract = function (csg) {
  20409. var a = new Node(this.clone().polygons);
  20410. var b = new Node(csg.clone().polygons);
  20411. a.invert();
  20412. a.clipTo(b);
  20413. b.clipTo(a);
  20414. b.invert();
  20415. b.clipTo(a);
  20416. b.invert();
  20417. a.build(b.allPolygons());
  20418. a.invert();
  20419. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20420. };
  20421. CSG.prototype.subtractInPlace = function (csg) {
  20422. var a = new Node(this.polygons);
  20423. var b = new Node(csg.polygons);
  20424. a.invert();
  20425. a.clipTo(b);
  20426. b.clipTo(a);
  20427. b.invert();
  20428. b.clipTo(a);
  20429. b.invert();
  20430. a.build(b.allPolygons());
  20431. a.invert();
  20432. this.polygons = a.allPolygons();
  20433. };
  20434. CSG.prototype.intersect = function (csg) {
  20435. var a = new Node(this.clone().polygons);
  20436. var b = new Node(csg.clone().polygons);
  20437. a.invert();
  20438. b.clipTo(a);
  20439. b.invert();
  20440. a.clipTo(b);
  20441. b.clipTo(a);
  20442. a.build(b.allPolygons());
  20443. a.invert();
  20444. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20445. };
  20446. CSG.prototype.intersectInPlace = function (csg) {
  20447. var a = new Node(this.polygons);
  20448. var b = new Node(csg.polygons);
  20449. a.invert();
  20450. b.clipTo(a);
  20451. b.invert();
  20452. a.clipTo(b);
  20453. b.clipTo(a);
  20454. a.build(b.allPolygons());
  20455. a.invert();
  20456. this.polygons = a.allPolygons();
  20457. };
  20458. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20459. // not modified.
  20460. CSG.prototype.inverse = function () {
  20461. var csg = this.clone();
  20462. csg.inverseInPlace();
  20463. return csg;
  20464. };
  20465. CSG.prototype.inverseInPlace = function () {
  20466. this.polygons.map(function (p) {
  20467. p.flip();
  20468. });
  20469. };
  20470. // This is used to keep meshes transformations so they can be restored
  20471. // when we build back a Babylon Mesh
  20472. // NB : All CSG operations are performed in world coordinates
  20473. CSG.prototype.copyTransformAttributes = function (csg) {
  20474. this.matrix = csg.matrix;
  20475. this.position = csg.position;
  20476. this.rotation = csg.rotation;
  20477. this.scaling = csg.scaling;
  20478. return this;
  20479. };
  20480. // Build Raw mesh from CSG
  20481. // Coordinates here are in world space
  20482. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20483. var matrix = this.matrix.clone();
  20484. matrix.invert();
  20485. 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;
  20486. if (keepSubMeshes) {
  20487. // Sort Polygons, since subMeshes are indices range
  20488. polygons.sort(function (a, b) {
  20489. if (a.shared.meshId === b.shared.meshId) {
  20490. return a.shared.subMeshId - b.shared.subMeshId;
  20491. }
  20492. else {
  20493. return a.shared.meshId - b.shared.meshId;
  20494. }
  20495. });
  20496. }
  20497. for (var i = 0, il = polygons.length; i < il; i++) {
  20498. polygon = polygons[i];
  20499. // Building SubMeshes
  20500. if (!subMesh_dict[polygon.shared.meshId]) {
  20501. subMesh_dict[polygon.shared.meshId] = {};
  20502. }
  20503. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20504. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20505. indexStart: +Infinity,
  20506. indexEnd: -Infinity,
  20507. materialIndex: polygon.shared.materialIndex
  20508. };
  20509. }
  20510. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20511. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20512. polygonIndices[0] = 0;
  20513. polygonIndices[1] = j - 1;
  20514. polygonIndices[2] = j;
  20515. for (var k = 0; k < 3; k++) {
  20516. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20517. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20518. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20519. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20520. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20521. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20522. // Check if 2 points can be merged
  20523. 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)) {
  20524. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20525. uvs.push(uv.x, uv.y);
  20526. normals.push(normal.x, normal.y, normal.z);
  20527. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20528. }
  20529. indices.push(vertex_idx);
  20530. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20531. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20532. currentIndex++;
  20533. }
  20534. }
  20535. }
  20536. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20537. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20538. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20539. mesh.setIndices(indices);
  20540. if (keepSubMeshes) {
  20541. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20542. var materialIndexOffset = 0, materialMaxIndex;
  20543. mesh.subMeshes.length = 0;
  20544. for (var m in subMesh_dict) {
  20545. materialMaxIndex = -1;
  20546. for (var sm in subMesh_dict[m]) {
  20547. subMesh_obj = subMesh_dict[m][sm];
  20548. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20549. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20550. }
  20551. materialIndexOffset += ++materialMaxIndex;
  20552. }
  20553. }
  20554. return mesh;
  20555. };
  20556. // Build Mesh from CSG taking material and transforms into account
  20557. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20558. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20559. mesh.material = material;
  20560. mesh.position.copyFrom(this.position);
  20561. mesh.rotation.copyFrom(this.rotation);
  20562. mesh.scaling.copyFrom(this.scaling);
  20563. mesh.computeWorldMatrix(true);
  20564. return mesh;
  20565. };
  20566. return CSG;
  20567. })();
  20568. BABYLON.CSG = CSG;
  20569. })(BABYLON || (BABYLON = {}));
  20570. //# sourceMappingURL=babylon.csg.js.map
  20571. var BABYLON;
  20572. (function (BABYLON) {
  20573. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20574. __extends(OculusDistortionCorrectionPostProcess, _super);
  20575. //ANY
  20576. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20577. var _this = this;
  20578. _super.call(this, name, "oculusDistortionCorrection", [
  20579. 'LensCenter',
  20580. 'Scale',
  20581. 'ScaleIn',
  20582. 'HmdWarpParam'
  20583. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20584. this._isRightEye = isRightEye;
  20585. this._distortionFactors = cameraSettings.DistortionK;
  20586. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20587. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20588. this.onSizeChanged = function () {
  20589. _this.aspectRatio = _this.width * .5 / _this.height;
  20590. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20591. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20592. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20593. };
  20594. this.onApply = function (effect) {
  20595. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20596. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20597. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20598. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20599. };
  20600. }
  20601. return OculusDistortionCorrectionPostProcess;
  20602. })(BABYLON.PostProcess);
  20603. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20604. })(BABYLON || (BABYLON = {}));
  20605. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20606. // 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
  20607. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20608. var BABYLON;
  20609. (function (BABYLON) {
  20610. (function (JoystickAxis) {
  20611. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20612. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20613. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20614. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20615. var JoystickAxis = BABYLON.JoystickAxis;
  20616. var VirtualJoystick = (function () {
  20617. function VirtualJoystick(leftJoystick) {
  20618. var _this = this;
  20619. if (leftJoystick) {
  20620. this._leftJoystick = true;
  20621. }
  20622. else {
  20623. this._leftJoystick = false;
  20624. }
  20625. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20626. VirtualJoystick._globalJoystickIndex++;
  20627. // By default left & right arrow keys are moving the X
  20628. // and up & down keys are moving the Y
  20629. this._axisTargetedByLeftAndRight = 0 /* X */;
  20630. this._axisTargetedByUpAndDown = 1 /* Y */;
  20631. this.reverseLeftRight = false;
  20632. this.reverseUpDown = false;
  20633. // collections of pointers
  20634. this._touches = new BABYLON.VirtualJoystick.Collection();
  20635. this.deltaPosition = BABYLON.Vector3.Zero();
  20636. this._joystickSensibility = 25;
  20637. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20638. this._rotationSpeed = 25;
  20639. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20640. this._rotateOnAxisRelativeToMesh = false;
  20641. // injecting a canvas element on top of the canvas 3D game
  20642. if (!VirtualJoystick.vjCanvas) {
  20643. window.addEventListener("resize", function () {
  20644. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20645. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20646. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20647. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20648. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20649. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20650. }, false);
  20651. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20652. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20653. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20654. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20655. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20656. VirtualJoystick.vjCanvas.style.width = "100%";
  20657. VirtualJoystick.vjCanvas.style.height = "100%";
  20658. VirtualJoystick.vjCanvas.style.position = "absolute";
  20659. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20660. VirtualJoystick.vjCanvas.style.top = "0px";
  20661. VirtualJoystick.vjCanvas.style.left = "0px";
  20662. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20663. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20664. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20665. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20666. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20667. document.body.appendChild(VirtualJoystick.vjCanvas);
  20668. }
  20669. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20670. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20671. this.pressed = false;
  20672. // default joystick color
  20673. this._joystickColor = "cyan";
  20674. this._joystickPointerID = -1;
  20675. // current joystick position
  20676. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20677. // origin joystick position
  20678. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20679. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20680. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20681. _this._onPointerDown(evt);
  20682. }, false);
  20683. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20684. _this._onPointerMove(evt);
  20685. }, false);
  20686. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20687. _this._onPointerUp(evt);
  20688. }, false);
  20689. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20690. _this._onPointerUp(evt);
  20691. }, false);
  20692. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20693. evt.preventDefault(); // Disables system menu
  20694. }, false);
  20695. requestAnimationFrame(function () {
  20696. _this._drawVirtualJoystick();
  20697. });
  20698. }
  20699. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20700. this._joystickSensibility = newJoystickSensibility;
  20701. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20702. };
  20703. VirtualJoystick.prototype._onPointerDown = function (e) {
  20704. var positionOnScreenCondition;
  20705. e.preventDefault();
  20706. if (this._leftJoystick === true) {
  20707. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20708. }
  20709. else {
  20710. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20711. }
  20712. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20713. // First contact will be dedicated to the virtual joystick
  20714. this._joystickPointerID = e.pointerId;
  20715. this._joystickPointerStartPos.x = e.clientX;
  20716. this._joystickPointerStartPos.y = e.clientY;
  20717. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20718. this._deltaJoystickVector.x = 0;
  20719. this._deltaJoystickVector.y = 0;
  20720. this.pressed = true;
  20721. this._touches.add(e.pointerId.toString(), e);
  20722. }
  20723. else {
  20724. // You can only trigger the action buttons with a joystick declared
  20725. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20726. this._action();
  20727. this._touches.add(e.pointerId.toString(), e);
  20728. }
  20729. }
  20730. };
  20731. VirtualJoystick.prototype._onPointerMove = function (e) {
  20732. // If the current pointer is the one associated to the joystick (first touch contact)
  20733. if (this._joystickPointerID == e.pointerId) {
  20734. this._joystickPointerPos.x = e.clientX;
  20735. this._joystickPointerPos.y = e.clientY;
  20736. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20737. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20738. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20739. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20740. switch (this._axisTargetedByLeftAndRight) {
  20741. case 0 /* X */:
  20742. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20743. break;
  20744. case 1 /* Y */:
  20745. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20746. break;
  20747. case 2 /* Z */:
  20748. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20749. break;
  20750. }
  20751. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20752. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20753. switch (this._axisTargetedByUpAndDown) {
  20754. case 0 /* X */:
  20755. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20756. break;
  20757. case 1 /* Y */:
  20758. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20759. break;
  20760. case 2 /* Z */:
  20761. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20762. break;
  20763. }
  20764. }
  20765. else {
  20766. if (this._touches.item(e.pointerId.toString())) {
  20767. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20768. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20769. }
  20770. }
  20771. };
  20772. VirtualJoystick.prototype._onPointerUp = function (e) {
  20773. this._clearCanvas();
  20774. if (this._joystickPointerID == e.pointerId) {
  20775. this._joystickPointerID = -1;
  20776. this.pressed = false;
  20777. }
  20778. this._deltaJoystickVector.x = 0;
  20779. this._deltaJoystickVector.y = 0;
  20780. this._touches.remove(e.pointerId.toString());
  20781. };
  20782. /**
  20783. * Change the color of the virtual joystick
  20784. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20785. */
  20786. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20787. this._joystickColor = newColor;
  20788. };
  20789. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20790. this._action = action;
  20791. };
  20792. // Define which axis you'd like to control for left & right
  20793. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20794. switch (axis) {
  20795. case 0 /* X */:
  20796. case 1 /* Y */:
  20797. case 2 /* Z */:
  20798. this._axisTargetedByLeftAndRight = axis;
  20799. break;
  20800. default:
  20801. this._axisTargetedByLeftAndRight = 0 /* X */;
  20802. break;
  20803. }
  20804. };
  20805. // Define which axis you'd like to control for up & down
  20806. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20807. switch (axis) {
  20808. case 0 /* X */:
  20809. case 1 /* Y */:
  20810. case 2 /* Z */:
  20811. this._axisTargetedByUpAndDown = axis;
  20812. break;
  20813. default:
  20814. this._axisTargetedByUpAndDown = 1 /* Y */;
  20815. break;
  20816. }
  20817. };
  20818. VirtualJoystick.prototype._clearCanvas = function () {
  20819. if (this._leftJoystick) {
  20820. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20821. }
  20822. else {
  20823. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20824. }
  20825. };
  20826. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20827. var _this = this;
  20828. if (this.pressed) {
  20829. this._clearCanvas();
  20830. this._touches.forEach(function (touch) {
  20831. if (touch.pointerId === _this._joystickPointerID) {
  20832. VirtualJoystick.vjCanvasContext.beginPath();
  20833. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20834. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20835. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20836. VirtualJoystick.vjCanvasContext.stroke();
  20837. VirtualJoystick.vjCanvasContext.beginPath();
  20838. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20839. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20840. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20841. VirtualJoystick.vjCanvasContext.stroke();
  20842. VirtualJoystick.vjCanvasContext.beginPath();
  20843. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20844. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20845. VirtualJoystick.vjCanvasContext.stroke();
  20846. }
  20847. else {
  20848. VirtualJoystick.vjCanvasContext.beginPath();
  20849. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20850. VirtualJoystick.vjCanvasContext.beginPath();
  20851. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20852. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20853. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20854. VirtualJoystick.vjCanvasContext.stroke();
  20855. }
  20856. ;
  20857. });
  20858. }
  20859. requestAnimationFrame(function () {
  20860. _this._drawVirtualJoystick();
  20861. });
  20862. };
  20863. VirtualJoystick.prototype.releaseCanvas = function () {
  20864. if (VirtualJoystick.vjCanvas) {
  20865. document.body.removeChild(VirtualJoystick.vjCanvas);
  20866. VirtualJoystick.vjCanvas = null;
  20867. }
  20868. };
  20869. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20870. VirtualJoystick._globalJoystickIndex = 0;
  20871. return VirtualJoystick;
  20872. })();
  20873. BABYLON.VirtualJoystick = VirtualJoystick;
  20874. })(BABYLON || (BABYLON = {}));
  20875. var BABYLON;
  20876. (function (BABYLON) {
  20877. var VirtualJoystick;
  20878. (function (VirtualJoystick) {
  20879. var Collection = (function () {
  20880. function Collection() {
  20881. this._count = 0;
  20882. this._collection = new Array();
  20883. }
  20884. Collection.prototype.Count = function () {
  20885. return this._count;
  20886. };
  20887. Collection.prototype.add = function (key, item) {
  20888. if (this._collection[key] != undefined) {
  20889. return undefined;
  20890. }
  20891. this._collection[key] = item;
  20892. return ++this._count;
  20893. };
  20894. Collection.prototype.remove = function (key) {
  20895. if (this._collection[key] == undefined) {
  20896. return undefined;
  20897. }
  20898. delete this._collection[key];
  20899. return --this._count;
  20900. };
  20901. Collection.prototype.item = function (key) {
  20902. return this._collection[key];
  20903. };
  20904. Collection.prototype.forEach = function (block) {
  20905. var key;
  20906. for (key in this._collection) {
  20907. if (this._collection.hasOwnProperty(key)) {
  20908. block(this._collection[key]);
  20909. }
  20910. }
  20911. };
  20912. return Collection;
  20913. })();
  20914. VirtualJoystick.Collection = Collection;
  20915. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20916. })(BABYLON || (BABYLON = {}));
  20917. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20918. var BABYLON;
  20919. (function (BABYLON) {
  20920. var OculusRiftDevKit2013_Metric = {
  20921. HResolution: 1280,
  20922. VResolution: 800,
  20923. HScreenSize: 0.149759993,
  20924. VScreenSize: 0.0935999975,
  20925. VScreenCenter: 0.0467999987,
  20926. EyeToScreenDistance: 0.0410000011,
  20927. LensSeparationDistance: 0.0635000020,
  20928. InterpupillaryDistance: 0.0640000030,
  20929. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20930. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20931. PostProcessScaleFactor: 1.714605507808412,
  20932. LensCenterOffset: 0.151976421
  20933. };
  20934. var _OculusInnerCamera = (function (_super) {
  20935. __extends(_OculusInnerCamera, _super);
  20936. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20937. _super.call(this, name, position, scene);
  20938. this._workMatrix = new BABYLON.Matrix();
  20939. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20940. // Constants
  20941. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20942. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20943. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20944. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20945. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20946. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20947. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20948. // Postprocess
  20949. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20950. }
  20951. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20952. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20953. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20954. return this._projectionMatrix;
  20955. };
  20956. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20957. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20958. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20959. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20960. // Computing target and final matrix
  20961. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20962. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20963. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20964. return this._viewMatrix;
  20965. };
  20966. return _OculusInnerCamera;
  20967. })(BABYLON.FreeCamera);
  20968. var OculusCamera = (function (_super) {
  20969. __extends(OculusCamera, _super);
  20970. function OculusCamera(name, position, scene) {
  20971. _super.call(this, name, position, scene);
  20972. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20973. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20974. this.subCameras.push(this._leftCamera);
  20975. this.subCameras.push(this._rightCamera);
  20976. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20977. }
  20978. OculusCamera.prototype._update = function () {
  20979. this._leftCamera.position.copyFrom(this.position);
  20980. this._rightCamera.position.copyFrom(this.position);
  20981. this._updateCamera(this._leftCamera);
  20982. this._updateCamera(this._rightCamera);
  20983. _super.prototype._update.call(this);
  20984. };
  20985. OculusCamera.prototype._updateCamera = function (camera) {
  20986. camera.minZ = this.minZ;
  20987. camera.maxZ = this.maxZ;
  20988. camera.rotation.x = this.rotation.x;
  20989. camera.rotation.y = this.rotation.y;
  20990. camera.rotation.z = this.rotation.z;
  20991. };
  20992. // Oculus events
  20993. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20994. var yaw = evt.alpha / 180 * Math.PI;
  20995. var pitch = evt.beta / 180 * Math.PI;
  20996. var roll = evt.gamma / 180 * Math.PI;
  20997. if (!this._offsetOrientation) {
  20998. this._offsetOrientation = {
  20999. yaw: yaw,
  21000. pitch: pitch,
  21001. roll: roll
  21002. };
  21003. return;
  21004. }
  21005. else {
  21006. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21007. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21008. this.rotation.z += this._offsetOrientation.roll - roll;
  21009. this._offsetOrientation.yaw = yaw;
  21010. this._offsetOrientation.pitch = pitch;
  21011. this._offsetOrientation.roll = roll;
  21012. }
  21013. };
  21014. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21015. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21016. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21017. };
  21018. OculusCamera.prototype.detachControl = function (element) {
  21019. _super.prototype.detachControl.call(this, element);
  21020. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21021. };
  21022. return OculusCamera;
  21023. })(BABYLON.FreeCamera);
  21024. BABYLON.OculusCamera = OculusCamera;
  21025. })(BABYLON || (BABYLON = {}));
  21026. //# sourceMappingURL=babylon.oculusCamera.js.map
  21027. var BABYLON;
  21028. (function (BABYLON) {
  21029. var OculusRiftDevKit2013_Metric = {
  21030. HResolution: 1280,
  21031. VResolution: 800,
  21032. HScreenSize: 0.149759993,
  21033. VScreenSize: 0.0935999975,
  21034. VScreenCenter: 0.0467999987,
  21035. EyeToScreenDistance: 0.0410000011,
  21036. LensSeparationDistance: 0.0635000020,
  21037. InterpupillaryDistance: 0.0640000030,
  21038. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21039. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21040. PostProcessScaleFactor: 1.714605507808412,
  21041. LensCenterOffset: 0.151976421
  21042. };
  21043. var _OculusInnerGamepadCamera = (function (_super) {
  21044. __extends(_OculusInnerGamepadCamera, _super);
  21045. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21046. _super.call(this, name, position, scene);
  21047. this._workMatrix = new BABYLON.Matrix();
  21048. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21049. // Constants
  21050. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21051. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21052. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21053. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21054. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21055. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21056. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21057. // Postprocess
  21058. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21059. }
  21060. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21061. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21062. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21063. return this._projectionMatrix;
  21064. };
  21065. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21066. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21067. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21068. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21069. // Computing target and final matrix
  21070. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21071. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21072. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21073. return this._viewMatrix;
  21074. };
  21075. return _OculusInnerGamepadCamera;
  21076. })(BABYLON.FreeCamera);
  21077. var OculusGamepadCamera = (function (_super) {
  21078. __extends(OculusGamepadCamera, _super);
  21079. function OculusGamepadCamera(name, position, scene) {
  21080. var _this = this;
  21081. _super.call(this, name, position, scene);
  21082. this.angularSensibility = 200;
  21083. this.moveSensibility = 75;
  21084. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21085. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21086. this.subCameras.push(this._leftCamera);
  21087. this.subCameras.push(this._rightCamera);
  21088. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21089. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21090. _this._onNewGameConnected(gamepad);
  21091. });
  21092. }
  21093. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21094. // Only the first gamepad can control the camera
  21095. if (gamepad.index === 0) {
  21096. this._gamepad = gamepad;
  21097. }
  21098. };
  21099. OculusGamepadCamera.prototype._update = function () {
  21100. this._leftCamera.position.copyFrom(this.position);
  21101. this._rightCamera.position.copyFrom(this.position);
  21102. this._updateCamera(this._leftCamera);
  21103. this._updateCamera(this._rightCamera);
  21104. _super.prototype._update.call(this);
  21105. };
  21106. OculusGamepadCamera.prototype._checkInputs = function () {
  21107. if (!this._gamepad) {
  21108. return;
  21109. }
  21110. var LSValues = this._gamepad.leftStick;
  21111. var normalizedLX = LSValues.x / this.moveSensibility;
  21112. var normalizedLY = LSValues.y / this.moveSensibility;
  21113. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21114. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21115. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21116. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21117. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21118. };
  21119. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21120. camera.minZ = this.minZ;
  21121. camera.maxZ = this.maxZ;
  21122. camera.rotation.x = this.rotation.x;
  21123. camera.rotation.y = this.rotation.y;
  21124. camera.rotation.z = this.rotation.z;
  21125. };
  21126. // Oculus events
  21127. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21128. var yaw = evt.alpha / 180 * Math.PI;
  21129. var pitch = evt.beta / 180 * Math.PI;
  21130. var roll = evt.gamma / 180 * Math.PI;
  21131. if (!this._offsetOrientation) {
  21132. this._offsetOrientation = {
  21133. yaw: yaw,
  21134. pitch: pitch,
  21135. roll: roll
  21136. };
  21137. return;
  21138. }
  21139. else {
  21140. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21141. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21142. this.rotation.z += this._offsetOrientation.roll - roll;
  21143. this._offsetOrientation.yaw = yaw;
  21144. this._offsetOrientation.pitch = pitch;
  21145. this._offsetOrientation.roll = roll;
  21146. }
  21147. };
  21148. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21149. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21150. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21151. };
  21152. OculusGamepadCamera.prototype.detachControl = function (element) {
  21153. _super.prototype.detachControl.call(this, element);
  21154. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21155. };
  21156. OculusGamepadCamera.prototype.dispose = function () {
  21157. this._gamepads.dispose();
  21158. _super.prototype.dispose.call(this);
  21159. };
  21160. return OculusGamepadCamera;
  21161. })(BABYLON.FreeCamera);
  21162. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21163. })(BABYLON || (BABYLON = {}));
  21164. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21165. var BABYLON;
  21166. (function (BABYLON) {
  21167. // We're mainly based on the logic defined into the FreeCamera code
  21168. var VirtualJoysticksCamera = (function (_super) {
  21169. __extends(VirtualJoysticksCamera, _super);
  21170. function VirtualJoysticksCamera(name, position, scene) {
  21171. _super.call(this, name, position, scene);
  21172. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21173. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21174. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21175. this._leftjoystick.setJoystickSensibility(0.15);
  21176. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21177. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21178. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21179. this._rightjoystick.reverseUpDown = true;
  21180. this._rightjoystick.setJoystickSensibility(0.05);
  21181. this._rightjoystick.setJoystickColor("yellow");
  21182. }
  21183. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21184. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21185. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21186. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21187. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21188. if (!this._leftjoystick.pressed) {
  21189. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21190. }
  21191. if (!this._rightjoystick.pressed) {
  21192. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21193. }
  21194. };
  21195. VirtualJoysticksCamera.prototype.dispose = function () {
  21196. this._leftjoystick.releaseCanvas();
  21197. _super.prototype.dispose.call(this);
  21198. };
  21199. return VirtualJoysticksCamera;
  21200. })(BABYLON.FreeCamera);
  21201. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21202. })(BABYLON || (BABYLON = {}));
  21203. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21204. var BABYLON;
  21205. (function (BABYLON) {
  21206. var ShaderMaterial = (function (_super) {
  21207. __extends(ShaderMaterial, _super);
  21208. function ShaderMaterial(name, scene, shaderPath, options) {
  21209. _super.call(this, name, scene);
  21210. this._textures = new Array();
  21211. this._floats = new Array();
  21212. this._floatsArrays = {};
  21213. this._colors3 = new Array();
  21214. this._colors4 = new Array();
  21215. this._vectors2 = new Array();
  21216. this._vectors3 = new Array();
  21217. this._matrices = new Array();
  21218. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21219. this._shaderPath = shaderPath;
  21220. options.needAlphaBlending = options.needAlphaBlending || false;
  21221. options.needAlphaTesting = options.needAlphaTesting || false;
  21222. options.attributes = options.attributes || ["position", "normal", "uv"];
  21223. options.uniforms = options.uniforms || ["worldViewProjection"];
  21224. options.samplers = options.samplers || [];
  21225. this._options = options;
  21226. }
  21227. ShaderMaterial.prototype.needAlphaBlending = function () {
  21228. return this._options.needAlphaBlending;
  21229. };
  21230. ShaderMaterial.prototype.needAlphaTesting = function () {
  21231. return this._options.needAlphaTesting;
  21232. };
  21233. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21234. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21235. this._options.uniforms.push(uniformName);
  21236. }
  21237. };
  21238. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21239. if (this._options.samplers.indexOf(name) === -1) {
  21240. this._options.samplers.push(name);
  21241. }
  21242. this._textures[name] = texture;
  21243. return this;
  21244. };
  21245. ShaderMaterial.prototype.setFloat = function (name, value) {
  21246. this._checkUniform(name);
  21247. this._floats[name] = value;
  21248. return this;
  21249. };
  21250. ShaderMaterial.prototype.setFloats = function (name, value) {
  21251. this._checkUniform(name);
  21252. this._floatsArrays[name] = value;
  21253. return this;
  21254. };
  21255. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21256. this._checkUniform(name);
  21257. this._colors3[name] = value;
  21258. return this;
  21259. };
  21260. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21261. this._checkUniform(name);
  21262. this._colors4[name] = value;
  21263. return this;
  21264. };
  21265. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21266. this._checkUniform(name);
  21267. this._vectors2[name] = value;
  21268. return this;
  21269. };
  21270. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21271. this._checkUniform(name);
  21272. this._vectors3[name] = value;
  21273. return this;
  21274. };
  21275. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21276. this._checkUniform(name);
  21277. this._matrices[name] = value;
  21278. return this;
  21279. };
  21280. ShaderMaterial.prototype.isReady = function () {
  21281. var scene = this.getScene();
  21282. var engine = scene.getEngine();
  21283. if (!this.checkReadyOnEveryCall) {
  21284. if (this._renderId === scene.getRenderId()) {
  21285. return true;
  21286. }
  21287. }
  21288. var previousEffect = this._effect;
  21289. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21290. if (!this._effect.isReady()) {
  21291. return false;
  21292. }
  21293. if (previousEffect !== this._effect) {
  21294. scene.resetCachedMaterial();
  21295. }
  21296. this._renderId = scene.getRenderId();
  21297. return true;
  21298. };
  21299. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21300. var scene = this.getScene();
  21301. if (this._options.uniforms.indexOf("world") !== -1) {
  21302. this._effect.setMatrix("world", world);
  21303. }
  21304. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21305. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21306. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21307. }
  21308. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21309. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21310. }
  21311. };
  21312. ShaderMaterial.prototype.bind = function (world) {
  21313. // Std values
  21314. this.bindOnlyWorldMatrix(world);
  21315. if (this.getScene().getCachedMaterial() !== this) {
  21316. if (this._options.uniforms.indexOf("view") !== -1) {
  21317. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21318. }
  21319. if (this._options.uniforms.indexOf("projection") !== -1) {
  21320. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21321. }
  21322. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21323. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21324. }
  21325. for (var name in this._textures) {
  21326. this._effect.setTexture(name, this._textures[name]);
  21327. }
  21328. for (name in this._floats) {
  21329. this._effect.setFloat(name, this._floats[name]);
  21330. }
  21331. for (name in this._floatsArrays) {
  21332. this._effect.setArray(name, this._floatsArrays[name]);
  21333. }
  21334. for (name in this._colors3) {
  21335. this._effect.setColor3(name, this._colors3[name]);
  21336. }
  21337. for (name in this._colors4) {
  21338. var color = this._colors4[name];
  21339. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21340. }
  21341. for (name in this._vectors2) {
  21342. this._effect.setVector2(name, this._vectors2[name]);
  21343. }
  21344. for (name in this._vectors3) {
  21345. this._effect.setVector3(name, this._vectors3[name]);
  21346. }
  21347. for (name in this._matrices) {
  21348. this._effect.setMatrix(name, this._matrices[name]);
  21349. }
  21350. }
  21351. _super.prototype.bind.call(this, world, null);
  21352. };
  21353. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21354. for (var name in this._textures) {
  21355. this._textures[name].dispose();
  21356. }
  21357. this._textures = [];
  21358. _super.prototype.dispose.call(this, forceDisposeEffect);
  21359. };
  21360. return ShaderMaterial;
  21361. })(BABYLON.Material);
  21362. BABYLON.ShaderMaterial = ShaderMaterial;
  21363. })(BABYLON || (BABYLON = {}));
  21364. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21365. (function (BABYLON) {
  21366. var VertexData = (function () {
  21367. function VertexData() {
  21368. }
  21369. VertexData.prototype.set = function (data, kind) {
  21370. switch (kind) {
  21371. case BABYLON.VertexBuffer.PositionKind:
  21372. this.positions = data;
  21373. break;
  21374. case BABYLON.VertexBuffer.NormalKind:
  21375. this.normals = data;
  21376. break;
  21377. case BABYLON.VertexBuffer.UVKind:
  21378. this.uvs = data;
  21379. break;
  21380. case BABYLON.VertexBuffer.UV2Kind:
  21381. this.uv2s = data;
  21382. break;
  21383. case BABYLON.VertexBuffer.ColorKind:
  21384. this.colors = data;
  21385. break;
  21386. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21387. this.matricesIndices = data;
  21388. break;
  21389. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21390. this.matricesWeights = data;
  21391. break;
  21392. }
  21393. };
  21394. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21395. this._applyTo(mesh, updatable);
  21396. };
  21397. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21398. this._applyTo(geometry, updatable);
  21399. };
  21400. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21401. this._update(mesh);
  21402. };
  21403. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21404. this._update(geometry);
  21405. };
  21406. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21407. if (this.positions) {
  21408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21409. }
  21410. if (this.normals) {
  21411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21412. }
  21413. if (this.uvs) {
  21414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21415. }
  21416. if (this.uv2s) {
  21417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21418. }
  21419. if (this.colors) {
  21420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21421. }
  21422. if (this.matricesIndices) {
  21423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21424. }
  21425. if (this.matricesWeights) {
  21426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21427. }
  21428. if (this.indices) {
  21429. meshOrGeometry.setIndices(this.indices);
  21430. }
  21431. };
  21432. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21433. if (this.positions) {
  21434. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21435. }
  21436. if (this.normals) {
  21437. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21438. }
  21439. if (this.uvs) {
  21440. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21441. }
  21442. if (this.uv2s) {
  21443. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21444. }
  21445. if (this.colors) {
  21446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21447. }
  21448. if (this.matricesIndices) {
  21449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21450. }
  21451. if (this.matricesWeights) {
  21452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21453. }
  21454. if (this.indices) {
  21455. meshOrGeometry.setIndices(this.indices);
  21456. }
  21457. };
  21458. VertexData.prototype.transform = function (matrix) {
  21459. var transformed = BABYLON.Vector3.Zero();
  21460. if (this.positions) {
  21461. var position = BABYLON.Vector3.Zero();
  21462. for (var index = 0; index < this.positions.length; index += 3) {
  21463. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21464. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21465. this.positions[index] = transformed.x;
  21466. this.positions[index + 1] = transformed.y;
  21467. this.positions[index + 2] = transformed.z;
  21468. }
  21469. }
  21470. if (this.normals) {
  21471. var normal = BABYLON.Vector3.Zero();
  21472. for (index = 0; index < this.normals.length; index += 3) {
  21473. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21474. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21475. this.normals[index] = transformed.x;
  21476. this.normals[index + 1] = transformed.y;
  21477. this.normals[index + 2] = transformed.z;
  21478. }
  21479. }
  21480. };
  21481. VertexData.prototype.merge = function (other) {
  21482. if (other.indices) {
  21483. if (!this.indices) {
  21484. this.indices = [];
  21485. }
  21486. var offset = this.positions ? this.positions.length / 3 : 0;
  21487. for (var index = 0; index < other.indices.length; index++) {
  21488. this.indices.push(other.indices[index] + offset);
  21489. }
  21490. }
  21491. if (other.positions) {
  21492. if (!this.positions) {
  21493. this.positions = [];
  21494. }
  21495. for (index = 0; index < other.positions.length; index++) {
  21496. this.positions.push(other.positions[index]);
  21497. }
  21498. }
  21499. if (other.normals) {
  21500. if (!this.normals) {
  21501. this.normals = [];
  21502. }
  21503. for (index = 0; index < other.normals.length; index++) {
  21504. this.normals.push(other.normals[index]);
  21505. }
  21506. }
  21507. if (other.uvs) {
  21508. if (!this.uvs) {
  21509. this.uvs = [];
  21510. }
  21511. for (index = 0; index < other.uvs.length; index++) {
  21512. this.uvs.push(other.uvs[index]);
  21513. }
  21514. }
  21515. if (other.uv2s) {
  21516. if (!this.uv2s) {
  21517. this.uv2s = [];
  21518. }
  21519. for (index = 0; index < other.uv2s.length; index++) {
  21520. this.uv2s.push(other.uv2s[index]);
  21521. }
  21522. }
  21523. if (other.matricesIndices) {
  21524. if (!this.matricesIndices) {
  21525. this.matricesIndices = [];
  21526. }
  21527. for (index = 0; index < other.matricesIndices.length; index++) {
  21528. this.matricesIndices.push(other.matricesIndices[index]);
  21529. }
  21530. }
  21531. if (other.matricesWeights) {
  21532. if (!this.matricesWeights) {
  21533. this.matricesWeights = [];
  21534. }
  21535. for (index = 0; index < other.matricesWeights.length; index++) {
  21536. this.matricesWeights.push(other.matricesWeights[index]);
  21537. }
  21538. }
  21539. if (other.colors) {
  21540. if (!this.colors) {
  21541. this.colors = [];
  21542. }
  21543. for (index = 0; index < other.colors.length; index++) {
  21544. this.colors.push(other.colors[index]);
  21545. }
  21546. }
  21547. };
  21548. // Statics
  21549. VertexData.ExtractFromMesh = function (mesh) {
  21550. return VertexData._ExtractFrom(mesh);
  21551. };
  21552. VertexData.ExtractFromGeometry = function (geometry) {
  21553. return VertexData._ExtractFrom(geometry);
  21554. };
  21555. VertexData._ExtractFrom = function (meshOrGeometry) {
  21556. var result = new VertexData();
  21557. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21558. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21559. }
  21560. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21561. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21562. }
  21563. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21564. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21565. }
  21566. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21567. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21568. }
  21569. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21570. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21571. }
  21572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21573. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21574. }
  21575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21576. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21577. }
  21578. result.indices = meshOrGeometry.getIndices();
  21579. return result;
  21580. };
  21581. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21582. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21583. closeArray = closeArray || false;
  21584. closePath = closePath || false;
  21585. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21586. offset = offset || defaultOffset;
  21587. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21588. var positions = [];
  21589. var indices = [];
  21590. var normals = [];
  21591. var uvs = [];
  21592. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21593. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21594. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21595. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21596. var minlg; // minimal length among all paths from pathArray
  21597. var lg = []; // array of path lengths : nb of vertex per path
  21598. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21599. var p; // path iterator
  21600. var i; // point iterator
  21601. var j; // point iterator
  21602. // if single path in pathArray
  21603. if (pathArray.length < 2) {
  21604. var ar1 = [];
  21605. var ar2 = [];
  21606. for (i = 0; i < pathArray[0].length - offset; i++) {
  21607. ar1.push(pathArray[0][i]);
  21608. ar2.push(pathArray[0][i + offset]);
  21609. }
  21610. pathArray = [ar1, ar2];
  21611. }
  21612. // positions and horizontal distances (u)
  21613. var idc = 0;
  21614. minlg = pathArray[0].length;
  21615. for (p = 0; p < pathArray.length; p++) {
  21616. uTotalDistance[p] = 0;
  21617. us[p] = [0];
  21618. var path = pathArray[p];
  21619. var l = path.length;
  21620. minlg = (minlg < l) ? minlg : l;
  21621. lg[p] = l;
  21622. idx[p] = idc;
  21623. j = 0;
  21624. while (j < l) {
  21625. positions.push(path[j].x, path[j].y, path[j].z);
  21626. if (j > 0) {
  21627. var vectlg = path[j].subtract(path[j - 1]).length();
  21628. var dist = vectlg + uTotalDistance[p];
  21629. us[p].push(dist);
  21630. uTotalDistance[p] = dist;
  21631. }
  21632. j++;
  21633. }
  21634. if (closePath) {
  21635. vectlg = path[0].subtract(path[j - 1]).length();
  21636. dist = vectlg + uTotalDistance[p];
  21637. uTotalDistance[p] = dist;
  21638. }
  21639. idc += l;
  21640. }
  21641. for (i = 0; i < minlg; i++) {
  21642. vTotalDistance[i] = 0;
  21643. vs[i] = [0];
  21644. var path1;
  21645. var path2;
  21646. for (p = 0; p < pathArray.length - 1; p++) {
  21647. path1 = pathArray[p];
  21648. path2 = pathArray[p + 1];
  21649. vectlg = path2[i].subtract(path1[i]).length();
  21650. dist = vectlg + vTotalDistance[i];
  21651. vs[i].push(dist);
  21652. vTotalDistance[i] = dist;
  21653. }
  21654. if (closeArray) {
  21655. path1 = pathArray[p];
  21656. path2 = pathArray[0];
  21657. vectlg = path2[i].subtract(path1[i]).length();
  21658. dist = vectlg + vTotalDistance[i];
  21659. vTotalDistance[i] = dist;
  21660. }
  21661. }
  21662. // uvs
  21663. var u;
  21664. var v;
  21665. for (p = 0; p < pathArray.length; p++) {
  21666. for (i = 0; i < minlg; i++) {
  21667. u = us[p][i] / uTotalDistance[p];
  21668. v = vs[i][p] / vTotalDistance[i];
  21669. uvs.push(u, v);
  21670. }
  21671. }
  21672. // indices
  21673. p = 0; // path index
  21674. var pi = 0; // positions array index
  21675. var l1 = lg[p] - 1; // path1 length
  21676. var l2 = lg[p + 1] - 1; // path2 length
  21677. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21678. var shft = idx[1] - idx[0]; // shift
  21679. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21680. var t1; // two consecutive triangles, so 4 points : point1
  21681. var t2; // point2
  21682. var t3; // point3
  21683. var t4; // point4
  21684. while (pi <= min && p < path1nb) {
  21685. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  21686. t1 = pi;
  21687. t2 = pi + shft;
  21688. t3 = pi + 1;
  21689. t4 = pi + shft + 1;
  21690. indices.push(pi, pi + shft, pi + 1);
  21691. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21692. pi += 1;
  21693. if (pi === min) {
  21694. if (closePath) {
  21695. indices.push(pi, pi + shft, idx[p]);
  21696. indices.push(idx[p] + shft, idx[p], pi + shft);
  21697. t3 = idx[p];
  21698. t4 = idx[p] + shft;
  21699. }
  21700. p++;
  21701. if (p === lg.length - 1) {
  21702. shft = idx[0] - idx[p];
  21703. l1 = lg[p] - 1;
  21704. l2 = lg[0] - 1;
  21705. }
  21706. else {
  21707. shft = idx[p + 1] - idx[p];
  21708. l1 = lg[p] - 1;
  21709. l2 = lg[p + 1] - 1;
  21710. }
  21711. pi = idx[p];
  21712. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21713. }
  21714. }
  21715. // normals
  21716. VertexData.ComputeNormals(positions, indices, normals);
  21717. // sides
  21718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21719. // Result
  21720. var vertexData = new VertexData();
  21721. vertexData.indices = indices;
  21722. vertexData.positions = positions;
  21723. vertexData.normals = normals;
  21724. vertexData.uvs = uvs;
  21725. return vertexData;
  21726. };
  21727. VertexData.CreateBox = function (size, sideOrientation) {
  21728. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21729. var normalsSource = [
  21730. new BABYLON.Vector3(0, 0, 1),
  21731. new BABYLON.Vector3(0, 0, -1),
  21732. new BABYLON.Vector3(1, 0, 0),
  21733. new BABYLON.Vector3(-1, 0, 0),
  21734. new BABYLON.Vector3(0, 1, 0),
  21735. new BABYLON.Vector3(0, -1, 0)
  21736. ];
  21737. var indices = [];
  21738. var positions = [];
  21739. var normals = [];
  21740. var uvs = [];
  21741. size = size || 1;
  21742. for (var index = 0; index < normalsSource.length; index++) {
  21743. var normal = normalsSource[index];
  21744. // Get two vectors perpendicular to the face normal and to each other.
  21745. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21746. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21747. // Six indices (two triangles) per face.
  21748. var verticesLength = positions.length / 3;
  21749. indices.push(verticesLength);
  21750. indices.push(verticesLength + 1);
  21751. indices.push(verticesLength + 2);
  21752. indices.push(verticesLength);
  21753. indices.push(verticesLength + 2);
  21754. indices.push(verticesLength + 3);
  21755. // Four vertices per face.
  21756. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21757. positions.push(vertex.x, vertex.y, vertex.z);
  21758. normals.push(normal.x, normal.y, normal.z);
  21759. uvs.push(1.0, 1.0);
  21760. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21761. positions.push(vertex.x, vertex.y, vertex.z);
  21762. normals.push(normal.x, normal.y, normal.z);
  21763. uvs.push(0.0, 1.0);
  21764. vertex = normal.add(side1).add(side2).scale(size / 2);
  21765. positions.push(vertex.x, vertex.y, vertex.z);
  21766. normals.push(normal.x, normal.y, normal.z);
  21767. uvs.push(0.0, 0.0);
  21768. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21769. positions.push(vertex.x, vertex.y, vertex.z);
  21770. normals.push(normal.x, normal.y, normal.z);
  21771. uvs.push(1.0, 0.0);
  21772. }
  21773. // sides
  21774. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21775. // Result
  21776. var vertexData = new VertexData();
  21777. vertexData.indices = indices;
  21778. vertexData.positions = positions;
  21779. vertexData.normals = normals;
  21780. vertexData.uvs = uvs;
  21781. return vertexData;
  21782. };
  21783. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21784. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21785. segments = segments || 32;
  21786. diameter = diameter || 1;
  21787. var radius = diameter / 2;
  21788. var totalZRotationSteps = 2 + segments;
  21789. var totalYRotationSteps = 2 * totalZRotationSteps;
  21790. var indices = [];
  21791. var positions = [];
  21792. var normals = [];
  21793. var uvs = [];
  21794. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21795. var normalizedZ = zRotationStep / totalZRotationSteps;
  21796. var angleZ = (normalizedZ * Math.PI);
  21797. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21798. var normalizedY = yRotationStep / totalYRotationSteps;
  21799. var angleY = normalizedY * Math.PI * 2;
  21800. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21801. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21802. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21803. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21804. var vertex = complete.scale(radius);
  21805. var normal = BABYLON.Vector3.Normalize(vertex);
  21806. positions.push(vertex.x, vertex.y, vertex.z);
  21807. normals.push(normal.x, normal.y, normal.z);
  21808. uvs.push(normalizedZ, normalizedY);
  21809. }
  21810. if (zRotationStep > 0) {
  21811. var verticesCount = positions.length / 3;
  21812. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21813. indices.push((firstIndex));
  21814. indices.push((firstIndex + 1));
  21815. indices.push(firstIndex + totalYRotationSteps + 1);
  21816. indices.push((firstIndex + totalYRotationSteps + 1));
  21817. indices.push((firstIndex + 1));
  21818. indices.push((firstIndex + totalYRotationSteps + 2));
  21819. }
  21820. }
  21821. }
  21822. // Sides
  21823. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21824. // Result
  21825. var vertexData = new VertexData();
  21826. vertexData.indices = indices;
  21827. vertexData.positions = positions;
  21828. vertexData.normals = normals;
  21829. vertexData.uvs = uvs;
  21830. return vertexData;
  21831. };
  21832. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21833. if (subdivisions === void 0) { subdivisions = 1; }
  21834. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21835. var radiusTop = diameterTop / 2;
  21836. var radiusBottom = diameterBottom / 2;
  21837. var indices = [];
  21838. var positions = [];
  21839. var normals = [];
  21840. var uvs = [];
  21841. height = height || 1;
  21842. diameterTop = diameterTop || 0.5;
  21843. diameterBottom = diameterBottom || 1;
  21844. tessellation = tessellation || 16;
  21845. subdivisions = subdivisions || 1;
  21846. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21847. var getCircleVector = function (i) {
  21848. var angle = (i * 2.0 * Math.PI / tessellation);
  21849. var dx = Math.cos(angle);
  21850. var dz = Math.sin(angle);
  21851. return new BABYLON.Vector3(dx, 0, dz);
  21852. };
  21853. var createCylinderCap = function (isTop) {
  21854. var radius = isTop ? radiusTop : radiusBottom;
  21855. if (radius === 0) {
  21856. return;
  21857. }
  21858. var vbase = positions.length / 3;
  21859. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21860. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21861. if (!isTop) {
  21862. offset.scaleInPlace(-1);
  21863. textureScale.x = -textureScale.x;
  21864. }
  21865. for (var i = 0; i < tessellation; i++) {
  21866. var circleVector = getCircleVector(i);
  21867. var position = circleVector.scale(radius).add(offset);
  21868. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21869. positions.push(position.x, position.y, position.z);
  21870. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21871. }
  21872. for (i = 0; i < tessellation - 2; i++) {
  21873. if (!isTop) {
  21874. indices.push(vbase);
  21875. indices.push(vbase + (i + 2) % tessellation);
  21876. indices.push(vbase + (i + 1) % tessellation);
  21877. }
  21878. else {
  21879. indices.push(vbase);
  21880. indices.push(vbase + (i + 1) % tessellation);
  21881. indices.push(vbase + (i + 2) % tessellation);
  21882. }
  21883. }
  21884. };
  21885. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21886. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21887. var stride = tessellation + 1;
  21888. for (var i = 0; i <= tessellation; i++) {
  21889. var circleVector = getCircleVector(i);
  21890. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21891. var position, radius = radiusBottom;
  21892. for (var s = 0; s <= subdivisions; s++) {
  21893. // Update variables
  21894. position = circleVector.scale(radius);
  21895. position.addInPlace(base.add(offset.scale(s)));
  21896. textureCoordinate.y += 1 / subdivisions;
  21897. radius += (radiusTop - radiusBottom) / subdivisions;
  21898. // Push in arrays
  21899. positions.push(position.x, position.y, position.z);
  21900. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21901. }
  21902. }
  21903. subdivisions += 1;
  21904. for (s = 0; s < subdivisions - 1; s++) {
  21905. for (i = 0; i <= tessellation; i++) {
  21906. indices.push(i * subdivisions + s);
  21907. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21908. indices.push(i * subdivisions + (s + 1));
  21909. indices.push(i * subdivisions + (s + 1));
  21910. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21911. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21912. }
  21913. }
  21914. // Create flat triangle fan caps to seal the top and bottom.
  21915. createCylinderCap(true);
  21916. createCylinderCap(false);
  21917. // Normals
  21918. VertexData.ComputeNormals(positions, indices, normals);
  21919. // Sides
  21920. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21921. // Result
  21922. var vertexData = new VertexData();
  21923. vertexData.indices = indices;
  21924. vertexData.positions = positions;
  21925. vertexData.normals = normals;
  21926. vertexData.uvs = uvs;
  21927. return vertexData;
  21928. };
  21929. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21930. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21931. var indices = [];
  21932. var positions = [];
  21933. var normals = [];
  21934. var uvs = [];
  21935. diameter = diameter || 1;
  21936. thickness = thickness || 0.5;
  21937. tessellation = tessellation || 16;
  21938. var stride = tessellation + 1;
  21939. for (var i = 0; i <= tessellation; i++) {
  21940. var u = i / tessellation;
  21941. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21942. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21943. for (var j = 0; j <= tessellation; j++) {
  21944. var v = 1 - j / tessellation;
  21945. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21946. var dx = Math.cos(innerAngle);
  21947. var dy = Math.sin(innerAngle);
  21948. // Create a vertex.
  21949. var normal = new BABYLON.Vector3(dx, dy, 0);
  21950. var position = normal.scale(thickness / 2);
  21951. var textureCoordinate = new BABYLON.Vector2(u, v);
  21952. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21953. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21954. positions.push(position.x, position.y, position.z);
  21955. normals.push(normal.x, normal.y, normal.z);
  21956. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21957. // And create indices for two triangles.
  21958. var nextI = (i + 1) % stride;
  21959. var nextJ = (j + 1) % stride;
  21960. indices.push(i * stride + j);
  21961. indices.push(i * stride + nextJ);
  21962. indices.push(nextI * stride + j);
  21963. indices.push(i * stride + nextJ);
  21964. indices.push(nextI * stride + nextJ);
  21965. indices.push(nextI * stride + j);
  21966. }
  21967. }
  21968. // Sides
  21969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21970. // Result
  21971. var vertexData = new VertexData();
  21972. vertexData.indices = indices;
  21973. vertexData.positions = positions;
  21974. vertexData.normals = normals;
  21975. vertexData.uvs = uvs;
  21976. return vertexData;
  21977. };
  21978. VertexData.CreateLines = function (points) {
  21979. var indices = [];
  21980. var positions = [];
  21981. for (var index = 0; index < points.length; index++) {
  21982. positions.push(points[index].x, points[index].y, points[index].z);
  21983. if (index > 0) {
  21984. indices.push(index - 1);
  21985. indices.push(index);
  21986. }
  21987. }
  21988. // Result
  21989. var vertexData = new VertexData();
  21990. vertexData.indices = indices;
  21991. vertexData.positions = positions;
  21992. return vertexData;
  21993. };
  21994. VertexData.CreateGround = function (width, height, subdivisions) {
  21995. var indices = [];
  21996. var positions = [];
  21997. var normals = [];
  21998. var uvs = [];
  21999. var row, col;
  22000. width = width || 1;
  22001. height = height || 1;
  22002. subdivisions = subdivisions || 1;
  22003. for (row = 0; row <= subdivisions; row++) {
  22004. for (col = 0; col <= subdivisions; col++) {
  22005. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22006. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22007. positions.push(position.x, position.y, position.z);
  22008. normals.push(normal.x, normal.y, normal.z);
  22009. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22010. }
  22011. }
  22012. for (row = 0; row < subdivisions; row++) {
  22013. for (col = 0; col < subdivisions; col++) {
  22014. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22015. indices.push(col + 1 + row * (subdivisions + 1));
  22016. indices.push(col + row * (subdivisions + 1));
  22017. indices.push(col + (row + 1) * (subdivisions + 1));
  22018. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22019. indices.push(col + row * (subdivisions + 1));
  22020. }
  22021. }
  22022. // Result
  22023. var vertexData = new VertexData();
  22024. vertexData.indices = indices;
  22025. vertexData.positions = positions;
  22026. vertexData.normals = normals;
  22027. vertexData.uvs = uvs;
  22028. return vertexData;
  22029. };
  22030. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22031. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22032. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22033. var indices = [];
  22034. var positions = [];
  22035. var normals = [];
  22036. var uvs = [];
  22037. var row, col, tileRow, tileCol;
  22038. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22039. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22040. precision.w = (precision.w < 1) ? 1 : precision.w;
  22041. precision.h = (precision.h < 1) ? 1 : precision.h;
  22042. var tileSize = {
  22043. 'w': (xmax - xmin) / subdivisions.w,
  22044. 'h': (zmax - zmin) / subdivisions.h
  22045. };
  22046. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22047. // Indices
  22048. var base = positions.length / 3;
  22049. var rowLength = precision.w + 1;
  22050. for (row = 0; row < precision.h; row++) {
  22051. for (col = 0; col < precision.w; col++) {
  22052. var square = [
  22053. base + col + row * rowLength,
  22054. base + (col + 1) + row * rowLength,
  22055. base + (col + 1) + (row + 1) * rowLength,
  22056. base + col + (row + 1) * rowLength
  22057. ];
  22058. indices.push(square[1]);
  22059. indices.push(square[2]);
  22060. indices.push(square[3]);
  22061. indices.push(square[0]);
  22062. indices.push(square[1]);
  22063. indices.push(square[3]);
  22064. }
  22065. }
  22066. // Position, normals and uvs
  22067. var position = BABYLON.Vector3.Zero();
  22068. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22069. for (row = 0; row <= precision.h; row++) {
  22070. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22071. for (col = 0; col <= precision.w; col++) {
  22072. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22073. position.y = 0;
  22074. positions.push(position.x, position.y, position.z);
  22075. normals.push(normal.x, normal.y, normal.z);
  22076. uvs.push(col / precision.w, row / precision.h);
  22077. }
  22078. }
  22079. }
  22080. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22081. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22082. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22083. }
  22084. }
  22085. // Result
  22086. var vertexData = new VertexData();
  22087. vertexData.indices = indices;
  22088. vertexData.positions = positions;
  22089. vertexData.normals = normals;
  22090. vertexData.uvs = uvs;
  22091. return vertexData;
  22092. };
  22093. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22094. var indices = [];
  22095. var positions = [];
  22096. var normals = [];
  22097. var uvs = [];
  22098. var row, col;
  22099. for (row = 0; row <= subdivisions; row++) {
  22100. for (col = 0; col <= subdivisions; col++) {
  22101. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22102. // Compute height
  22103. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22104. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22105. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22106. var r = buffer[pos] / 255.0;
  22107. var g = buffer[pos + 1] / 255.0;
  22108. var b = buffer[pos + 2] / 255.0;
  22109. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22110. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22111. // Add vertex
  22112. positions.push(position.x, position.y, position.z);
  22113. normals.push(0, 0, 0);
  22114. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22115. }
  22116. }
  22117. for (row = 0; row < subdivisions; row++) {
  22118. for (col = 0; col < subdivisions; col++) {
  22119. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22120. indices.push(col + 1 + row * (subdivisions + 1));
  22121. indices.push(col + row * (subdivisions + 1));
  22122. indices.push(col + (row + 1) * (subdivisions + 1));
  22123. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22124. indices.push(col + row * (subdivisions + 1));
  22125. }
  22126. }
  22127. // Normals
  22128. VertexData.ComputeNormals(positions, indices, normals);
  22129. // Result
  22130. var vertexData = new VertexData();
  22131. vertexData.indices = indices;
  22132. vertexData.positions = positions;
  22133. vertexData.normals = normals;
  22134. vertexData.uvs = uvs;
  22135. return vertexData;
  22136. };
  22137. VertexData.CreatePlane = function (size, sideOrientation) {
  22138. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22139. var indices = [];
  22140. var positions = [];
  22141. var normals = [];
  22142. var uvs = [];
  22143. size = size || 1;
  22144. // Vertices
  22145. var halfSize = size / 2.0;
  22146. positions.push(-halfSize, -halfSize, 0);
  22147. normals.push(0, 0, -1.0);
  22148. uvs.push(0.0, 0.0);
  22149. positions.push(halfSize, -halfSize, 0);
  22150. normals.push(0, 0, -1.0);
  22151. uvs.push(1.0, 0.0);
  22152. positions.push(halfSize, halfSize, 0);
  22153. normals.push(0, 0, -1.0);
  22154. uvs.push(1.0, 1.0);
  22155. positions.push(-halfSize, halfSize, 0);
  22156. normals.push(0, 0, -1.0);
  22157. uvs.push(0.0, 1.0);
  22158. // Indices
  22159. indices.push(0);
  22160. indices.push(1);
  22161. indices.push(2);
  22162. indices.push(0);
  22163. indices.push(2);
  22164. indices.push(3);
  22165. // Sides
  22166. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22167. // Result
  22168. var vertexData = new VertexData();
  22169. vertexData.indices = indices;
  22170. vertexData.positions = positions;
  22171. vertexData.normals = normals;
  22172. vertexData.uvs = uvs;
  22173. return vertexData;
  22174. };
  22175. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22176. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22177. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22178. var indices = [];
  22179. var positions = [];
  22180. var normals = [];
  22181. var uvs = [];
  22182. radius = radius || 2;
  22183. tube = tube || 0.5;
  22184. radialSegments = radialSegments || 32;
  22185. tubularSegments = tubularSegments || 32;
  22186. p = p || 2;
  22187. q = q || 3;
  22188. // Helper
  22189. var getPos = function (angle) {
  22190. var cu = Math.cos(angle);
  22191. var su = Math.sin(angle);
  22192. var quOverP = q / p * angle;
  22193. var cs = Math.cos(quOverP);
  22194. var tx = radius * (2 + cs) * 0.5 * cu;
  22195. var ty = radius * (2 + cs) * su * 0.5;
  22196. var tz = radius * Math.sin(quOverP) * 0.5;
  22197. return new BABYLON.Vector3(tx, ty, tz);
  22198. };
  22199. for (var i = 0; i <= radialSegments; i++) {
  22200. var modI = i % radialSegments;
  22201. var u = modI / radialSegments * 2 * p * Math.PI;
  22202. var p1 = getPos(u);
  22203. var p2 = getPos(u + 0.01);
  22204. var tang = p2.subtract(p1);
  22205. var n = p2.add(p1);
  22206. var bitan = BABYLON.Vector3.Cross(tang, n);
  22207. n = BABYLON.Vector3.Cross(bitan, tang);
  22208. bitan.normalize();
  22209. n.normalize();
  22210. for (var j = 0; j < tubularSegments; j++) {
  22211. var modJ = j % tubularSegments;
  22212. var v = modJ / tubularSegments * 2 * Math.PI;
  22213. var cx = -tube * Math.cos(v);
  22214. var cy = tube * Math.sin(v);
  22215. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22216. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22217. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22218. uvs.push(i / radialSegments);
  22219. uvs.push(j / tubularSegments);
  22220. }
  22221. }
  22222. for (i = 0; i < radialSegments; i++) {
  22223. for (j = 0; j < tubularSegments; j++) {
  22224. var jNext = (j + 1) % tubularSegments;
  22225. var a = i * tubularSegments + j;
  22226. var b = (i + 1) * tubularSegments + j;
  22227. var c = (i + 1) * tubularSegments + jNext;
  22228. var d = i * tubularSegments + jNext;
  22229. indices.push(d);
  22230. indices.push(b);
  22231. indices.push(a);
  22232. indices.push(d);
  22233. indices.push(c);
  22234. indices.push(b);
  22235. }
  22236. }
  22237. // Normals
  22238. VertexData.ComputeNormals(positions, indices, normals);
  22239. // Sides
  22240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22241. // Result
  22242. var vertexData = new VertexData();
  22243. vertexData.indices = indices;
  22244. vertexData.positions = positions;
  22245. vertexData.normals = normals;
  22246. vertexData.uvs = uvs;
  22247. return vertexData;
  22248. };
  22249. // Tools
  22250. VertexData.ComputeNormals = function (positions, indices, normals) {
  22251. var positionVectors = [];
  22252. var facesOfVertices = [];
  22253. var index;
  22254. for (index = 0; index < positions.length; index += 3) {
  22255. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22256. positionVectors.push(vector3);
  22257. facesOfVertices.push([]);
  22258. }
  22259. // Compute normals
  22260. var facesNormals = [];
  22261. for (index = 0; index < indices.length / 3; index++) {
  22262. var i1 = indices[index * 3];
  22263. var i2 = indices[index * 3 + 1];
  22264. var i3 = indices[index * 3 + 2];
  22265. var p1 = positionVectors[i1];
  22266. var p2 = positionVectors[i2];
  22267. var p3 = positionVectors[i3];
  22268. var p1p2 = p1.subtract(p2);
  22269. var p3p2 = p3.subtract(p2);
  22270. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22271. facesOfVertices[i1].push(index);
  22272. facesOfVertices[i2].push(index);
  22273. facesOfVertices[i3].push(index);
  22274. }
  22275. for (index = 0; index < positionVectors.length; index++) {
  22276. var faces = facesOfVertices[index];
  22277. var normal = BABYLON.Vector3.Zero();
  22278. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22279. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22280. }
  22281. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22282. normals[index * 3] = normal.x;
  22283. normals[index * 3 + 1] = normal.y;
  22284. normals[index * 3 + 2] = normal.z;
  22285. }
  22286. };
  22287. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22288. var li = indices.length;
  22289. var ln = normals.length;
  22290. var i;
  22291. var n;
  22292. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22293. switch (sideOrientation) {
  22294. case BABYLON.Mesh.FRONTSIDE:
  22295. break;
  22296. case BABYLON.Mesh.BACKSIDE:
  22297. var tmp;
  22298. for (i = 0; i < li; i += 3) {
  22299. tmp = indices[i];
  22300. indices[i] = indices[i + 2];
  22301. indices[i + 2] = tmp;
  22302. }
  22303. for (n = 0; n < ln; n++) {
  22304. normals[n] = -normals[n];
  22305. }
  22306. break;
  22307. case BABYLON.Mesh.DOUBLESIDE:
  22308. // positions
  22309. var lp = positions.length;
  22310. var l = lp / 3;
  22311. for (var p = 0; p < lp; p++) {
  22312. positions[lp + p] = positions[p];
  22313. }
  22314. for (i = 0; i < li; i += 3) {
  22315. indices[i + li] = indices[i + 2] + l;
  22316. indices[i + 1 + li] = indices[i + 1] + l;
  22317. indices[i + 2 + li] = indices[i] + l;
  22318. }
  22319. for (n = 0; n < ln; n++) {
  22320. normals[ln + n] = -normals[n];
  22321. }
  22322. // uvs
  22323. var lu = uvs.length;
  22324. for (var u = 0; u < lu; u++) {
  22325. uvs[u + lu] = uvs[u];
  22326. }
  22327. break;
  22328. }
  22329. };
  22330. return VertexData;
  22331. })();
  22332. BABYLON.VertexData = VertexData;
  22333. })(BABYLON || (BABYLON = {}));
  22334. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22335. var BABYLON;
  22336. (function (BABYLON) {
  22337. var buildCamera = function (that, name) {
  22338. that._leftCamera.isIntermediate = true;
  22339. that.subCameras.push(that._leftCamera);
  22340. that.subCameras.push(that._rightCamera);
  22341. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22342. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22343. that._anaglyphPostProcess.onApply = function (effect) {
  22344. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22345. };
  22346. that._update();
  22347. };
  22348. var AnaglyphArcRotateCamera = (function (_super) {
  22349. __extends(AnaglyphArcRotateCamera, _super);
  22350. // ANY
  22351. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22352. _super.call(this, name, alpha, beta, radius, target, scene);
  22353. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22354. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22355. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22356. buildCamera(this, name);
  22357. }
  22358. AnaglyphArcRotateCamera.prototype._update = function () {
  22359. this._updateCamera(this._leftCamera);
  22360. this._updateCamera(this._rightCamera);
  22361. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22362. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22363. _super.prototype._update.call(this);
  22364. };
  22365. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22366. camera.beta = this.beta;
  22367. camera.radius = this.radius;
  22368. camera.minZ = this.minZ;
  22369. camera.maxZ = this.maxZ;
  22370. camera.fov = this.fov;
  22371. camera.target = this.target;
  22372. };
  22373. return AnaglyphArcRotateCamera;
  22374. })(BABYLON.ArcRotateCamera);
  22375. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22376. var AnaglyphFreeCamera = (function (_super) {
  22377. __extends(AnaglyphFreeCamera, _super);
  22378. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22379. _super.call(this, name, position, scene);
  22380. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22381. this._transformMatrix = new BABYLON.Matrix();
  22382. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22383. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22384. buildCamera(this, name);
  22385. }
  22386. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22387. var target = this.getTarget();
  22388. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22389. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22390. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22391. };
  22392. AnaglyphFreeCamera.prototype._update = function () {
  22393. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22394. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22395. this._updateCamera(this._leftCamera);
  22396. this._updateCamera(this._rightCamera);
  22397. _super.prototype._update.call(this);
  22398. };
  22399. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22400. camera.minZ = this.minZ;
  22401. camera.maxZ = this.maxZ;
  22402. camera.fov = this.fov;
  22403. camera.viewport = this.viewport;
  22404. camera.setTarget(this.getTarget());
  22405. };
  22406. return AnaglyphFreeCamera;
  22407. })(BABYLON.FreeCamera);
  22408. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22409. })(BABYLON || (BABYLON = {}));
  22410. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22411. var BABYLON;
  22412. (function (BABYLON) {
  22413. var AnaglyphPostProcess = (function (_super) {
  22414. __extends(AnaglyphPostProcess, _super);
  22415. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22416. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22417. }
  22418. return AnaglyphPostProcess;
  22419. })(BABYLON.PostProcess);
  22420. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22421. })(BABYLON || (BABYLON = {}));
  22422. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22423. (function (BABYLON) {
  22424. var Tags = (function () {
  22425. function Tags() {
  22426. }
  22427. Tags.EnableFor = function (obj) {
  22428. obj._tags = obj._tags || {};
  22429. obj.hasTags = function () {
  22430. return Tags.HasTags(obj);
  22431. };
  22432. obj.addTags = function (tagsString) {
  22433. return Tags.AddTagsTo(obj, tagsString);
  22434. };
  22435. obj.removeTags = function (tagsString) {
  22436. return Tags.RemoveTagsFrom(obj, tagsString);
  22437. };
  22438. obj.matchesTagsQuery = function (tagsQuery) {
  22439. return Tags.MatchesQuery(obj, tagsQuery);
  22440. };
  22441. };
  22442. Tags.DisableFor = function (obj) {
  22443. delete obj._tags;
  22444. delete obj.hasTags;
  22445. delete obj.addTags;
  22446. delete obj.removeTags;
  22447. delete obj.matchesTagsQuery;
  22448. };
  22449. Tags.HasTags = function (obj) {
  22450. if (!obj._tags) {
  22451. return false;
  22452. }
  22453. return !BABYLON.Tools.IsEmpty(obj._tags);
  22454. };
  22455. Tags.GetTags = function (obj) {
  22456. if (!obj._tags) {
  22457. return null;
  22458. }
  22459. return obj._tags;
  22460. };
  22461. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22462. // a tag cannot start with '||', '&&', and '!'
  22463. // it cannot contain whitespaces
  22464. Tags.AddTagsTo = function (obj, tagsString) {
  22465. if (!tagsString) {
  22466. return;
  22467. }
  22468. var tags = tagsString.split(" ");
  22469. for (var t in tags) {
  22470. Tags._AddTagTo(obj, tags[t]);
  22471. }
  22472. };
  22473. Tags._AddTagTo = function (obj, tag) {
  22474. tag = tag.trim();
  22475. if (tag === "" || tag === "true" || tag === "false") {
  22476. return;
  22477. }
  22478. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22479. return;
  22480. }
  22481. Tags.EnableFor(obj);
  22482. obj._tags[tag] = true;
  22483. };
  22484. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22485. if (!Tags.HasTags(obj)) {
  22486. return;
  22487. }
  22488. var tags = tagsString.split(" ");
  22489. for (var t in tags) {
  22490. Tags._RemoveTagFrom(obj, tags[t]);
  22491. }
  22492. };
  22493. Tags._RemoveTagFrom = function (obj, tag) {
  22494. delete obj._tags[tag];
  22495. };
  22496. Tags.MatchesQuery = function (obj, tagsQuery) {
  22497. if (tagsQuery === undefined) {
  22498. return true;
  22499. }
  22500. if (tagsQuery === "") {
  22501. return Tags.HasTags(obj);
  22502. }
  22503. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22504. };
  22505. return Tags;
  22506. })();
  22507. BABYLON.Tags = Tags;
  22508. })(BABYLON || (BABYLON = {}));
  22509. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22510. (function (BABYLON) {
  22511. var Internals;
  22512. (function (Internals) {
  22513. var AndOrNotEvaluator = (function () {
  22514. function AndOrNotEvaluator() {
  22515. }
  22516. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22517. if (!query.match(/\([^\(\)]*\)/g)) {
  22518. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22519. }
  22520. else {
  22521. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22522. // remove parenthesis
  22523. r = r.slice(1, r.length - 1);
  22524. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22525. });
  22526. }
  22527. if (query === "true") {
  22528. return true;
  22529. }
  22530. if (query === "false") {
  22531. return false;
  22532. }
  22533. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22534. };
  22535. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22536. evaluateCallback = evaluateCallback || (function (r) {
  22537. return r === "true" ? true : false;
  22538. });
  22539. var result;
  22540. var or = parenthesisContent.split("||");
  22541. for (var i in or) {
  22542. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22543. var and = ori.split("&&");
  22544. if (and.length > 1) {
  22545. for (var j = 0; j < and.length; ++j) {
  22546. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22547. if (andj !== "true" && andj !== "false") {
  22548. if (andj[0] === "!") {
  22549. result = !evaluateCallback(andj.substring(1));
  22550. }
  22551. else {
  22552. result = evaluateCallback(andj);
  22553. }
  22554. }
  22555. else {
  22556. result = andj === "true" ? true : false;
  22557. }
  22558. if (!result) {
  22559. ori = "false";
  22560. break;
  22561. }
  22562. }
  22563. }
  22564. if (result || ori === "true") {
  22565. result = true;
  22566. break;
  22567. }
  22568. // result equals false (or undefined)
  22569. if (ori !== "true" && ori !== "false") {
  22570. if (ori[0] === "!") {
  22571. result = !evaluateCallback(ori.substring(1));
  22572. }
  22573. else {
  22574. result = evaluateCallback(ori);
  22575. }
  22576. }
  22577. else {
  22578. result = ori === "true" ? true : false;
  22579. }
  22580. }
  22581. // the whole parenthesis scope is replaced by 'true' or 'false'
  22582. return result ? "true" : "false";
  22583. };
  22584. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22585. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22586. // remove whitespaces
  22587. r = r.replace(/[\s]/g, function () { return ""; });
  22588. return r.length % 2 ? "!" : "";
  22589. });
  22590. booleanString = booleanString.trim();
  22591. if (booleanString === "!true") {
  22592. booleanString = "false";
  22593. }
  22594. else if (booleanString === "!false") {
  22595. booleanString = "true";
  22596. }
  22597. return booleanString;
  22598. };
  22599. return AndOrNotEvaluator;
  22600. })();
  22601. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22602. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22603. })(BABYLON || (BABYLON = {}));
  22604. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22605. (function (BABYLON) {
  22606. var PostProcessRenderPass = (function () {
  22607. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22608. this._enabled = true;
  22609. this._refCount = 0;
  22610. this._name = name;
  22611. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22612. this.setRenderList(renderList);
  22613. this._renderTexture.onBeforeRender = beforeRender;
  22614. this._renderTexture.onAfterRender = afterRender;
  22615. this._scene = scene;
  22616. this._renderList = renderList;
  22617. }
  22618. // private
  22619. PostProcessRenderPass.prototype._incRefCount = function () {
  22620. if (this._refCount === 0) {
  22621. this._scene.customRenderTargets.push(this._renderTexture);
  22622. }
  22623. return ++this._refCount;
  22624. };
  22625. PostProcessRenderPass.prototype._decRefCount = function () {
  22626. this._refCount--;
  22627. if (this._refCount <= 0) {
  22628. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22629. }
  22630. return this._refCount;
  22631. };
  22632. PostProcessRenderPass.prototype._update = function () {
  22633. this.setRenderList(this._renderList);
  22634. };
  22635. // public
  22636. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22637. this._renderTexture.renderList = renderList;
  22638. };
  22639. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22640. return this._renderTexture;
  22641. };
  22642. return PostProcessRenderPass;
  22643. })();
  22644. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22645. })(BABYLON || (BABYLON = {}));
  22646. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22647. (function (BABYLON) {
  22648. var PostProcessRenderEffect = (function () {
  22649. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22650. this._engine = engine;
  22651. this._name = name;
  22652. this._singleInstance = singleInstance || true;
  22653. this._getPostProcess = getPostProcess;
  22654. this._cameras = [];
  22655. this._indicesForCamera = [];
  22656. this._postProcesses = {};
  22657. this._renderPasses = {};
  22658. this._renderEffectAsPasses = {};
  22659. }
  22660. PostProcessRenderEffect.prototype._update = function () {
  22661. for (var renderPassName in this._renderPasses) {
  22662. this._renderPasses[renderPassName]._update();
  22663. }
  22664. };
  22665. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22666. this._renderPasses[renderPass._name] = renderPass;
  22667. this._linkParameters();
  22668. };
  22669. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22670. delete this._renderPasses[renderPass._name];
  22671. this._linkParameters();
  22672. };
  22673. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22674. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22675. this._linkParameters();
  22676. };
  22677. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22678. for (var renderPassName in this._renderPasses) {
  22679. if (renderPassName === passName) {
  22680. return this._renderPasses[passName];
  22681. }
  22682. }
  22683. };
  22684. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22685. this._renderPasses = {};
  22686. this._linkParameters();
  22687. };
  22688. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22689. var cameraKey;
  22690. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22691. for (var i = 0; i < _cam.length; i++) {
  22692. var camera = _cam[i];
  22693. var cameraName = camera.name;
  22694. if (this._singleInstance) {
  22695. cameraKey = 0;
  22696. }
  22697. else {
  22698. cameraKey = cameraName;
  22699. }
  22700. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22701. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22702. if (!this._indicesForCamera[cameraName]) {
  22703. this._indicesForCamera[cameraName] = [];
  22704. }
  22705. this._indicesForCamera[cameraName].push(index);
  22706. if (this._cameras.indexOf(camera) === -1) {
  22707. this._cameras[cameraName] = camera;
  22708. }
  22709. for (var passName in this._renderPasses) {
  22710. this._renderPasses[passName]._incRefCount();
  22711. }
  22712. }
  22713. this._linkParameters();
  22714. };
  22715. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22716. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22717. for (var i = 0; i < _cam.length; i++) {
  22718. var camera = _cam[i];
  22719. var cameraName = camera.name;
  22720. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22721. var index = this._cameras.indexOf(cameraName);
  22722. this._indicesForCamera.splice(index, 1);
  22723. this._cameras.splice(index, 1);
  22724. for (var passName in this._renderPasses) {
  22725. this._renderPasses[passName]._decRefCount();
  22726. }
  22727. }
  22728. };
  22729. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22730. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22731. for (var i = 0; i < _cam.length; i++) {
  22732. var camera = _cam[i];
  22733. var cameraName = camera.name;
  22734. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22735. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22736. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22737. }
  22738. }
  22739. for (var passName in this._renderPasses) {
  22740. this._renderPasses[passName]._incRefCount();
  22741. }
  22742. }
  22743. };
  22744. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22745. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22746. for (var i = 0; i < _cam.length; i++) {
  22747. var camera = _cam[i];
  22748. var cameraName = camera.Name;
  22749. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22750. for (var passName in this._renderPasses) {
  22751. this._renderPasses[passName]._decRefCount();
  22752. }
  22753. }
  22754. };
  22755. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22756. if (this._singleInstance) {
  22757. return this._postProcesses[0];
  22758. }
  22759. else {
  22760. return this._postProcesses[camera.name];
  22761. }
  22762. };
  22763. PostProcessRenderEffect.prototype._linkParameters = function () {
  22764. var _this = this;
  22765. for (var index in this._postProcesses) {
  22766. if (this.applyParameters) {
  22767. this.applyParameters(this._postProcesses[index]);
  22768. }
  22769. this._postProcesses[index].onBeforeRender = function (effect) {
  22770. _this._linkTextures(effect);
  22771. };
  22772. }
  22773. };
  22774. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22775. for (var renderPassName in this._renderPasses) {
  22776. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22777. }
  22778. for (var renderEffectName in this._renderEffectAsPasses) {
  22779. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22780. }
  22781. };
  22782. return PostProcessRenderEffect;
  22783. })();
  22784. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22785. })(BABYLON || (BABYLON = {}));
  22786. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22787. (function (BABYLON) {
  22788. var PostProcessRenderPipeline = (function () {
  22789. function PostProcessRenderPipeline(engine, name) {
  22790. this._engine = engine;
  22791. this._name = name;
  22792. this._renderEffects = {};
  22793. this._renderEffectsForIsolatedPass = {};
  22794. this._cameras = [];
  22795. }
  22796. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22797. this._renderEffects[renderEffect._name] = renderEffect;
  22798. };
  22799. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22800. var renderEffects = this._renderEffects[renderEffectName];
  22801. if (!renderEffects) {
  22802. return;
  22803. }
  22804. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22805. };
  22806. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22807. var renderEffects = this._renderEffects[renderEffectName];
  22808. if (!renderEffects) {
  22809. return;
  22810. }
  22811. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22812. };
  22813. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22814. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22815. var indicesToDelete = [];
  22816. for (var i = 0; i < _cam.length; i++) {
  22817. var camera = _cam[i];
  22818. var cameraName = camera.name;
  22819. if (this._cameras.indexOf(camera) === -1) {
  22820. this._cameras[cameraName] = camera;
  22821. }
  22822. else if (unique) {
  22823. indicesToDelete.push(i);
  22824. }
  22825. }
  22826. for (var i = 0; i < indicesToDelete.length; i++) {
  22827. cameras.splice(indicesToDelete[i], 1);
  22828. }
  22829. for (var renderEffectName in this._renderEffects) {
  22830. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22831. }
  22832. };
  22833. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22834. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22835. for (var renderEffectName in this._renderEffects) {
  22836. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22837. }
  22838. for (var i = 0; i < _cam.length; i++) {
  22839. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22840. }
  22841. };
  22842. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22843. var _this = this;
  22844. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22845. var pass = null;
  22846. for (var renderEffectName in this._renderEffects) {
  22847. pass = this._renderEffects[renderEffectName].getPass(passName);
  22848. if (pass != null) {
  22849. break;
  22850. }
  22851. }
  22852. if (pass === null) {
  22853. return;
  22854. }
  22855. for (var renderEffectName in this._renderEffects) {
  22856. this._renderEffects[renderEffectName]._disable(_cam);
  22857. }
  22858. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22859. for (var i = 0; i < _cam.length; i++) {
  22860. var camera = _cam[i];
  22861. var cameraName = camera.name;
  22862. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22863. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22864. });
  22865. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22866. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22867. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22868. }
  22869. };
  22870. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22871. var _this = this;
  22872. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22873. for (var i = 0; i < _cam.length; i++) {
  22874. var camera = _cam[i];
  22875. var cameraName = camera.name;
  22876. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22877. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22878. });
  22879. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22880. }
  22881. for (var renderEffectName in this._renderEffects) {
  22882. this._renderEffects[renderEffectName]._enable(_cam);
  22883. }
  22884. };
  22885. PostProcessRenderPipeline.prototype._update = function () {
  22886. for (var renderEffectName in this._renderEffects) {
  22887. this._renderEffects[renderEffectName]._update();
  22888. }
  22889. for (var i = 0; i < this._cameras.length; i++) {
  22890. var cameraName = this._cameras[i].name;
  22891. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22892. this._renderEffectsForIsolatedPass[cameraName]._update();
  22893. }
  22894. }
  22895. };
  22896. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22897. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22898. return PostProcessRenderPipeline;
  22899. })();
  22900. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22901. })(BABYLON || (BABYLON = {}));
  22902. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22903. (function (BABYLON) {
  22904. var PostProcessRenderPipelineManager = (function () {
  22905. function PostProcessRenderPipelineManager() {
  22906. this._renderPipelines = {};
  22907. }
  22908. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22909. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22910. };
  22911. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22912. var renderPipeline = this._renderPipelines[renderPipelineName];
  22913. if (!renderPipeline) {
  22914. return;
  22915. }
  22916. renderPipeline._attachCameras(cameras, unique);
  22917. };
  22918. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22919. var renderPipeline = this._renderPipelines[renderPipelineName];
  22920. if (!renderPipeline) {
  22921. return;
  22922. }
  22923. renderPipeline._detachCameras(cameras);
  22924. };
  22925. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22926. var renderPipeline = this._renderPipelines[renderPipelineName];
  22927. if (!renderPipeline) {
  22928. return;
  22929. }
  22930. renderPipeline._enableEffect(renderEffectName, cameras);
  22931. };
  22932. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22933. var renderPipeline = this._renderPipelines[renderPipelineName];
  22934. if (!renderPipeline) {
  22935. return;
  22936. }
  22937. renderPipeline._disableEffect(renderEffectName, cameras);
  22938. };
  22939. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22940. var renderPipeline = this._renderPipelines[renderPipelineName];
  22941. if (!renderPipeline) {
  22942. return;
  22943. }
  22944. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22945. };
  22946. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22947. var renderPipeline = this._renderPipelines[renderPipelineName];
  22948. if (!renderPipeline) {
  22949. return;
  22950. }
  22951. renderPipeline._disableDisplayOnlyPass(cameras);
  22952. };
  22953. PostProcessRenderPipelineManager.prototype.update = function () {
  22954. for (var renderPipelineName in this._renderPipelines) {
  22955. this._renderPipelines[renderPipelineName]._update();
  22956. }
  22957. };
  22958. return PostProcessRenderPipelineManager;
  22959. })();
  22960. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22961. })(BABYLON || (BABYLON = {}));
  22962. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22963. var BABYLON;
  22964. (function (BABYLON) {
  22965. var DisplayPassPostProcess = (function (_super) {
  22966. __extends(DisplayPassPostProcess, _super);
  22967. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22968. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22969. }
  22970. return DisplayPassPostProcess;
  22971. })(BABYLON.PostProcess);
  22972. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22973. })(BABYLON || (BABYLON = {}));
  22974. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22975. (function (BABYLON) {
  22976. var BoundingBoxRenderer = (function () {
  22977. function BoundingBoxRenderer(scene) {
  22978. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22979. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22980. this.showBackLines = true;
  22981. this.renderList = new BABYLON.SmartArray(32);
  22982. this._scene = scene;
  22983. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22984. attributes: ["position"],
  22985. uniforms: ["worldViewProjection", "color"]
  22986. });
  22987. var engine = this._scene.getEngine();
  22988. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22989. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22990. 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]);
  22991. }
  22992. BoundingBoxRenderer.prototype.reset = function () {
  22993. this.renderList.reset();
  22994. };
  22995. BoundingBoxRenderer.prototype.render = function () {
  22996. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22997. return;
  22998. }
  22999. var engine = this._scene.getEngine();
  23000. engine.setDepthWrite(false);
  23001. this._colorShader._preBind();
  23002. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23003. var boundingBox = this.renderList.data[boundingBoxIndex];
  23004. var min = boundingBox.minimum;
  23005. var max = boundingBox.maximum;
  23006. var diff = max.subtract(min);
  23007. var median = min.add(diff.scale(0.5));
  23008. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23009. // VBOs
  23010. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23011. if (this.showBackLines) {
  23012. // Back
  23013. engine.setDepthFunctionToGreaterOrEqual();
  23014. this._scene.resetCachedMaterial();
  23015. this._colorShader.setColor4("color", this.backColor.toColor4());
  23016. this._colorShader.bind(worldMatrix);
  23017. // Draw order
  23018. engine.draw(false, 0, 24);
  23019. }
  23020. // Front
  23021. engine.setDepthFunctionToLess();
  23022. this._scene.resetCachedMaterial();
  23023. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23024. this._colorShader.bind(worldMatrix);
  23025. // Draw order
  23026. engine.draw(false, 0, 24);
  23027. }
  23028. this._colorShader.unbind();
  23029. engine.setDepthFunctionToLessOrEqual();
  23030. engine.setDepthWrite(true);
  23031. };
  23032. BoundingBoxRenderer.prototype.dispose = function () {
  23033. this._colorShader.dispose();
  23034. this._vb.dispose();
  23035. this._scene.getEngine()._releaseBuffer(this._ib);
  23036. };
  23037. return BoundingBoxRenderer;
  23038. })();
  23039. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23040. })(BABYLON || (BABYLON = {}));
  23041. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23042. (function (BABYLON) {
  23043. var Internals;
  23044. (function (Internals) {
  23045. /*
  23046. * Based on jsTGALoader - Javascript loader for TGA file
  23047. * By Vincent Thibault
  23048. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23049. */
  23050. var TGATools = (function () {
  23051. function TGATools() {
  23052. }
  23053. TGATools.GetTGAHeader = function (data) {
  23054. var offset = 0;
  23055. var header = {
  23056. id_length: data[offset++],
  23057. colormap_type: data[offset++],
  23058. image_type: data[offset++],
  23059. colormap_index: data[offset++] | data[offset++] << 8,
  23060. colormap_length: data[offset++] | data[offset++] << 8,
  23061. colormap_size: data[offset++],
  23062. origin: [
  23063. data[offset++] | data[offset++] << 8,
  23064. data[offset++] | data[offset++] << 8
  23065. ],
  23066. width: data[offset++] | data[offset++] << 8,
  23067. height: data[offset++] | data[offset++] << 8,
  23068. pixel_size: data[offset++],
  23069. flags: data[offset++]
  23070. };
  23071. return header;
  23072. };
  23073. TGATools.UploadContent = function (gl, data) {
  23074. // Not enough data to contain header ?
  23075. if (data.length < 19) {
  23076. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23077. return;
  23078. }
  23079. // Read Header
  23080. var offset = 18;
  23081. var header = TGATools.GetTGAHeader(data);
  23082. // Assume it's a valid Targa file.
  23083. if (header.id_length + offset > data.length) {
  23084. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23085. return;
  23086. }
  23087. // Skip not needed data
  23088. offset += header.id_length;
  23089. var use_rle = false;
  23090. var use_pal = false;
  23091. var use_rgb = false;
  23092. var use_grey = false;
  23093. switch (header.image_type) {
  23094. case TGATools._TYPE_RLE_INDEXED:
  23095. use_rle = true;
  23096. case TGATools._TYPE_INDEXED:
  23097. use_pal = true;
  23098. break;
  23099. case TGATools._TYPE_RLE_RGB:
  23100. use_rle = true;
  23101. case TGATools._TYPE_RGB:
  23102. use_rgb = true;
  23103. break;
  23104. case TGATools._TYPE_RLE_GREY:
  23105. use_rle = true;
  23106. case TGATools._TYPE_GREY:
  23107. use_grey = true;
  23108. break;
  23109. }
  23110. var pixel_data;
  23111. var numAlphaBits = header.flags & 0xf;
  23112. var pixel_size = header.pixel_size >> 3;
  23113. var pixel_total = header.width * header.height * pixel_size;
  23114. // Read palettes
  23115. var palettes;
  23116. if (use_pal) {
  23117. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23118. }
  23119. // Read LRE
  23120. if (use_rle) {
  23121. pixel_data = new Uint8Array(pixel_total);
  23122. var c, count, i;
  23123. var localOffset = 0;
  23124. var pixels = new Uint8Array(pixel_size);
  23125. while (offset < pixel_total && localOffset < pixel_total) {
  23126. c = data[offset++];
  23127. count = (c & 0x7f) + 1;
  23128. // RLE pixels
  23129. if (c & 0x80) {
  23130. for (i = 0; i < pixel_size; ++i) {
  23131. pixels[i] = data[offset++];
  23132. }
  23133. for (i = 0; i < count; ++i) {
  23134. pixel_data.set(pixels, localOffset + i * pixel_size);
  23135. }
  23136. localOffset += pixel_size * count;
  23137. }
  23138. else {
  23139. count *= pixel_size;
  23140. for (i = 0; i < count; ++i) {
  23141. pixel_data[localOffset + i] = data[offset++];
  23142. }
  23143. localOffset += count;
  23144. }
  23145. }
  23146. }
  23147. else {
  23148. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23149. }
  23150. // Load to texture
  23151. var x_start, y_start, x_step, y_step, y_end, x_end;
  23152. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23153. default:
  23154. case TGATools._ORIGIN_UL:
  23155. x_start = 0;
  23156. x_step = 1;
  23157. x_end = header.width;
  23158. y_start = 0;
  23159. y_step = 1;
  23160. y_end = header.height;
  23161. break;
  23162. case TGATools._ORIGIN_BL:
  23163. x_start = 0;
  23164. x_step = 1;
  23165. x_end = header.width;
  23166. y_start = header.height - 1;
  23167. y_step = -1;
  23168. y_end = -1;
  23169. break;
  23170. case TGATools._ORIGIN_UR:
  23171. x_start = header.width - 1;
  23172. x_step = -1;
  23173. x_end = -1;
  23174. y_start = 0;
  23175. y_step = 1;
  23176. y_end = header.height;
  23177. break;
  23178. case TGATools._ORIGIN_BR:
  23179. x_start = header.width - 1;
  23180. x_step = -1;
  23181. x_end = -1;
  23182. y_start = header.height - 1;
  23183. y_step = -1;
  23184. y_end = -1;
  23185. break;
  23186. }
  23187. // Load the specify method
  23188. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23189. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23190. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23191. };
  23192. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23193. var image = pixel_data, colormap = palettes;
  23194. var width = header.width, height = header.height;
  23195. var color, i = 0, x, y;
  23196. var imageData = new Uint8Array(width * height * 4);
  23197. for (y = y_start; y !== y_end; y += y_step) {
  23198. for (x = x_start; x !== x_end; x += x_step, i++) {
  23199. color = image[i];
  23200. imageData[(x + width * y) * 4 + 3] = 255;
  23201. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23202. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23203. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23204. }
  23205. }
  23206. return imageData;
  23207. };
  23208. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23209. var image = pixel_data;
  23210. var width = header.width, height = header.height;
  23211. var color, i = 0, x, y;
  23212. var imageData = new Uint8Array(width * height * 4);
  23213. for (y = y_start; y !== y_end; y += y_step) {
  23214. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23215. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23216. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23217. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23218. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23219. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23220. }
  23221. }
  23222. return imageData;
  23223. };
  23224. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23225. var image = pixel_data;
  23226. var width = header.width, height = header.height;
  23227. var i = 0, x, y;
  23228. var imageData = new Uint8Array(width * height * 4);
  23229. for (y = y_start; y !== y_end; y += y_step) {
  23230. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23231. imageData[(x + width * y) * 4 + 3] = 255;
  23232. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23233. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23234. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23235. }
  23236. }
  23237. return imageData;
  23238. };
  23239. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23240. var image = pixel_data;
  23241. var width = header.width, height = header.height;
  23242. var i = 0, x, y;
  23243. var imageData = new Uint8Array(width * height * 4);
  23244. for (y = y_start; y !== y_end; y += y_step) {
  23245. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23246. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23247. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23248. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23249. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23250. }
  23251. }
  23252. return imageData;
  23253. };
  23254. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23255. var image = pixel_data;
  23256. var width = header.width, height = header.height;
  23257. var color, i = 0, x, y;
  23258. var imageData = new Uint8Array(width * height * 4);
  23259. for (y = y_start; y !== y_end; y += y_step) {
  23260. for (x = x_start; x !== x_end; x += x_step, i++) {
  23261. color = image[i];
  23262. imageData[(x + width * y) * 4 + 0] = color;
  23263. imageData[(x + width * y) * 4 + 1] = color;
  23264. imageData[(x + width * y) * 4 + 2] = color;
  23265. imageData[(x + width * y) * 4 + 3] = 255;
  23266. }
  23267. }
  23268. return imageData;
  23269. };
  23270. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23271. var image = pixel_data;
  23272. var width = header.width, height = header.height;
  23273. var i = 0, x, y;
  23274. var imageData = new Uint8Array(width * height * 4);
  23275. for (y = y_start; y !== y_end; y += y_step) {
  23276. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23277. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23278. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23279. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23280. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23281. }
  23282. }
  23283. return imageData;
  23284. };
  23285. TGATools._TYPE_NO_DATA = 0;
  23286. TGATools._TYPE_INDEXED = 1;
  23287. TGATools._TYPE_RGB = 2;
  23288. TGATools._TYPE_GREY = 3;
  23289. TGATools._TYPE_RLE_INDEXED = 9;
  23290. TGATools._TYPE_RLE_RGB = 10;
  23291. TGATools._TYPE_RLE_GREY = 11;
  23292. TGATools._ORIGIN_MASK = 0x30;
  23293. TGATools._ORIGIN_SHIFT = 0x04;
  23294. TGATools._ORIGIN_BL = 0x00;
  23295. TGATools._ORIGIN_BR = 0x01;
  23296. TGATools._ORIGIN_UL = 0x02;
  23297. TGATools._ORIGIN_UR = 0x03;
  23298. return TGATools;
  23299. })();
  23300. Internals.TGATools = TGATools;
  23301. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23302. })(BABYLON || (BABYLON = {}));
  23303. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23304. (function (BABYLON) {
  23305. var Internals;
  23306. (function (Internals) {
  23307. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23308. // All values and structures referenced from:
  23309. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23310. var DDS_MAGIC = 0x20534444;
  23311. 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;
  23312. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23313. 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;
  23314. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23315. function FourCCToInt32(value) {
  23316. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23317. }
  23318. function Int32ToFourCC(value) {
  23319. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23320. }
  23321. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23322. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23323. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23324. var headerLengthInt = 31; // The header length in 32 bit ints
  23325. // Offsets into the header array
  23326. var off_magic = 0;
  23327. var off_size = 1;
  23328. var off_flags = 2;
  23329. var off_height = 3;
  23330. var off_width = 4;
  23331. var off_mipmapCount = 7;
  23332. var off_pfFlags = 20;
  23333. var off_pfFourCC = 21;
  23334. var off_RGBbpp = 22;
  23335. var off_RMask = 23;
  23336. var off_GMask = 24;
  23337. var off_BMask = 25;
  23338. var off_AMask = 26;
  23339. var off_caps1 = 27;
  23340. var off_caps2 = 28;
  23341. ;
  23342. var DDSTools = (function () {
  23343. function DDSTools() {
  23344. }
  23345. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23346. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23347. var mipmapCount = 1;
  23348. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23349. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23350. }
  23351. return {
  23352. width: header[off_width],
  23353. height: header[off_height],
  23354. mipmapCount: mipmapCount,
  23355. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23356. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23357. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23358. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23359. };
  23360. };
  23361. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23362. var byteArray = new Uint8Array(dataLength);
  23363. var srcData = new Uint8Array(arrayBuffer);
  23364. var index = 0;
  23365. for (var y = height - 1; y >= 0; y--) {
  23366. for (var x = 0; x < width; x++) {
  23367. var srcPos = dataOffset + (x + y * width) * 4;
  23368. byteArray[index + 2] = srcData[srcPos];
  23369. byteArray[index + 1] = srcData[srcPos + 1];
  23370. byteArray[index] = srcData[srcPos + 2];
  23371. byteArray[index + 3] = srcData[srcPos + 3];
  23372. index += 4;
  23373. }
  23374. }
  23375. return byteArray;
  23376. };
  23377. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23378. var byteArray = new Uint8Array(dataLength);
  23379. var srcData = new Uint8Array(arrayBuffer);
  23380. var index = 0;
  23381. for (var y = height - 1; y >= 0; y--) {
  23382. for (var x = 0; x < width; x++) {
  23383. var srcPos = dataOffset + (x + y * width) * 3;
  23384. byteArray[index + 2] = srcData[srcPos];
  23385. byteArray[index + 1] = srcData[srcPos + 1];
  23386. byteArray[index] = srcData[srcPos + 2];
  23387. index += 3;
  23388. }
  23389. }
  23390. return byteArray;
  23391. };
  23392. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23393. var byteArray = new Uint8Array(dataLength);
  23394. var srcData = new Uint8Array(arrayBuffer);
  23395. var index = 0;
  23396. for (var y = height - 1; y >= 0; y--) {
  23397. for (var x = 0; x < width; x++) {
  23398. var srcPos = dataOffset + (x + y * width);
  23399. byteArray[index] = srcData[srcPos];
  23400. index++;
  23401. }
  23402. }
  23403. return byteArray;
  23404. };
  23405. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23406. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23407. if (header[off_magic] != DDS_MAGIC) {
  23408. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23409. return;
  23410. }
  23411. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23412. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23413. return;
  23414. }
  23415. if (info.isFourCC) {
  23416. fourCC = header[off_pfFourCC];
  23417. switch (fourCC) {
  23418. case FOURCC_DXT1:
  23419. blockBytes = 8;
  23420. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23421. break;
  23422. case FOURCC_DXT3:
  23423. blockBytes = 16;
  23424. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23425. break;
  23426. case FOURCC_DXT5:
  23427. blockBytes = 16;
  23428. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23429. break;
  23430. default:
  23431. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23432. return;
  23433. }
  23434. }
  23435. mipmapCount = 1;
  23436. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23437. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23438. }
  23439. var bpp = header[off_RGBbpp];
  23440. for (var face = 0; face < faces; face++) {
  23441. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23442. width = header[off_width];
  23443. height = header[off_height];
  23444. dataOffset = header[off_size] + 4;
  23445. for (i = 0; i < mipmapCount; ++i) {
  23446. if (info.isRGB) {
  23447. if (bpp == 24) {
  23448. dataLength = width * height * 3;
  23449. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23450. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23451. }
  23452. else {
  23453. dataLength = width * height * 4;
  23454. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23455. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23456. }
  23457. }
  23458. else if (info.isLuminance) {
  23459. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23460. var unpaddedRowSize = width;
  23461. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23462. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23463. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23464. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23465. }
  23466. else {
  23467. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23468. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23469. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23470. }
  23471. dataOffset += dataLength;
  23472. width *= 0.5;
  23473. height *= 0.5;
  23474. width = Math.max(1.0, width);
  23475. height = Math.max(1.0, height);
  23476. }
  23477. }
  23478. };
  23479. return DDSTools;
  23480. })();
  23481. Internals.DDSTools = DDSTools;
  23482. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23483. })(BABYLON || (BABYLON = {}));
  23484. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23485. (function (BABYLON) {
  23486. var SmartArray = (function () {
  23487. function SmartArray(capacity) {
  23488. this.length = 0;
  23489. this._duplicateId = 0;
  23490. this.data = new Array(capacity);
  23491. this._id = SmartArray._GlobalId++;
  23492. }
  23493. SmartArray.prototype.push = function (value) {
  23494. this.data[this.length++] = value;
  23495. if (this.length > this.data.length) {
  23496. this.data.length *= 2;
  23497. }
  23498. if (!value.__smartArrayFlags) {
  23499. value.__smartArrayFlags = {};
  23500. }
  23501. value.__smartArrayFlags[this._id] = this._duplicateId;
  23502. };
  23503. SmartArray.prototype.pushNoDuplicate = function (value) {
  23504. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23505. return;
  23506. }
  23507. this.push(value);
  23508. };
  23509. SmartArray.prototype.sort = function (compareFn) {
  23510. this.data.sort(compareFn);
  23511. };
  23512. SmartArray.prototype.reset = function () {
  23513. this.length = 0;
  23514. this._duplicateId++;
  23515. };
  23516. SmartArray.prototype.concat = function (array) {
  23517. if (array.length === 0) {
  23518. return;
  23519. }
  23520. if (this.length + array.length > this.data.length) {
  23521. this.data.length = (this.length + array.length) * 2;
  23522. }
  23523. for (var index = 0; index < array.length; index++) {
  23524. this.data[this.length++] = (array.data || array)[index];
  23525. }
  23526. };
  23527. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23528. if (array.length === 0) {
  23529. return;
  23530. }
  23531. if (this.length + array.length > this.data.length) {
  23532. this.data.length = (this.length + array.length) * 2;
  23533. }
  23534. for (var index = 0; index < array.length; index++) {
  23535. var item = (array.data || array)[index];
  23536. this.pushNoDuplicate(item);
  23537. }
  23538. };
  23539. SmartArray.prototype.indexOf = function (value) {
  23540. var position = this.data.indexOf(value);
  23541. if (position >= this.length) {
  23542. return -1;
  23543. }
  23544. return position;
  23545. };
  23546. // Statics
  23547. SmartArray._GlobalId = 0;
  23548. return SmartArray;
  23549. })();
  23550. BABYLON.SmartArray = SmartArray;
  23551. })(BABYLON || (BABYLON = {}));
  23552. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23553. (function (BABYLON) {
  23554. var CannonJSPlugin = (function () {
  23555. function CannonJSPlugin() {
  23556. this._registeredMeshes = [];
  23557. this._physicsMaterials = [];
  23558. this.updateBodyPosition = function (mesh) {
  23559. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23560. var registeredMesh = this._registeredMeshes[index];
  23561. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23562. var body = registeredMesh.body;
  23563. var center = mesh.getBoundingInfo().boundingBox.center;
  23564. body.position.set(center.x, center.z, center.y);
  23565. body.quaternion.x = mesh.rotationQuaternion.x;
  23566. body.quaternion.z = mesh.rotationQuaternion.y;
  23567. body.quaternion.y = mesh.rotationQuaternion.z;
  23568. body.quaternion.w = -mesh.rotationQuaternion.w;
  23569. return;
  23570. }
  23571. }
  23572. };
  23573. }
  23574. CannonJSPlugin.prototype.initialize = function (iterations) {
  23575. if (iterations === void 0) { iterations = 10; }
  23576. this._world = new CANNON.World();
  23577. this._world.broadphase = new CANNON.NaiveBroadphase();
  23578. this._world.solver.iterations = iterations;
  23579. };
  23580. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23581. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23582. };
  23583. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23584. this._world.step(delta);
  23585. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23586. var registeredMesh = this._registeredMeshes[index];
  23587. if (registeredMesh.isChild) {
  23588. continue;
  23589. }
  23590. // Body position
  23591. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23592. var deltaPos = registeredMesh.delta;
  23593. if (deltaPos) {
  23594. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23595. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23596. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23597. }
  23598. else {
  23599. registeredMesh.mesh.position.x = bodyX;
  23600. registeredMesh.mesh.position.y = bodyZ;
  23601. registeredMesh.mesh.position.z = bodyY;
  23602. }
  23603. if (!registeredMesh.mesh.rotationQuaternion) {
  23604. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23605. }
  23606. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23607. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23608. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23609. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23610. }
  23611. };
  23612. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23613. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23614. };
  23615. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23616. this.unregisterMesh(mesh);
  23617. mesh.computeWorldMatrix(true);
  23618. switch (impostor) {
  23619. case BABYLON.PhysicsEngine.SphereImpostor:
  23620. var bbox = mesh.getBoundingInfo().boundingBox;
  23621. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23622. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23623. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23624. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23625. case BABYLON.PhysicsEngine.BoxImpostor:
  23626. bbox = mesh.getBoundingInfo().boundingBox;
  23627. var min = bbox.minimumWorld;
  23628. var max = bbox.maximumWorld;
  23629. var box = max.subtract(min).scale(0.5);
  23630. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23631. case BABYLON.PhysicsEngine.PlaneImpostor:
  23632. return this._createPlane(mesh, options);
  23633. case BABYLON.PhysicsEngine.MeshImpostor:
  23634. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23635. var rawFaces = mesh.getIndices();
  23636. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23637. }
  23638. return null;
  23639. };
  23640. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23641. var shape = new CANNON.Sphere(radius);
  23642. if (!options) {
  23643. return shape;
  23644. }
  23645. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23646. };
  23647. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23648. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23649. if (!options) {
  23650. return shape;
  23651. }
  23652. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23653. };
  23654. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23655. var shape = new CANNON.Plane();
  23656. if (!options) {
  23657. return shape;
  23658. }
  23659. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23660. };
  23661. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23662. var verts = [], faces = [];
  23663. mesh.computeWorldMatrix(true);
  23664. for (var i = 0; i < rawVerts.length; i += 3) {
  23665. var transformed = BABYLON.Vector3.Zero();
  23666. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23667. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23668. }
  23669. for (var j = 0; j < rawFaces.length; j += 3) {
  23670. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23671. }
  23672. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23673. if (!options) {
  23674. return shape;
  23675. }
  23676. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23677. };
  23678. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23679. var index;
  23680. var mat;
  23681. for (index = 0; index < this._physicsMaterials.length; index++) {
  23682. mat = this._physicsMaterials[index];
  23683. if (mat.friction === friction && mat.restitution === restitution) {
  23684. return mat;
  23685. }
  23686. }
  23687. var currentMat = new CANNON.Material();
  23688. currentMat.friction = friction;
  23689. currentMat.restitution = restitution;
  23690. this._physicsMaterials.push(currentMat);
  23691. for (index = 0; index < this._physicsMaterials.length; index++) {
  23692. mat = this._physicsMaterials[index];
  23693. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23694. contactMaterial.contactEquationStiffness = 1e10;
  23695. contactMaterial.contactEquationRegularizationTime = 10;
  23696. this._world.addContactMaterial(contactMaterial);
  23697. }
  23698. return currentMat;
  23699. };
  23700. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23701. var initialRotation = null;
  23702. if (mesh.rotationQuaternion) {
  23703. initialRotation = mesh.rotationQuaternion.clone();
  23704. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23705. }
  23706. // The delta between the mesh position and the mesh bounding box center
  23707. var bbox = mesh.getBoundingInfo().boundingBox;
  23708. var deltaPosition = mesh.position.subtract(bbox.center);
  23709. var material = this._addMaterial(friction, restitution);
  23710. var body = new CANNON.RigidBody(mass, shape, material);
  23711. if (initialRotation) {
  23712. body.quaternion.x = initialRotation.x;
  23713. body.quaternion.z = initialRotation.y;
  23714. body.quaternion.y = initialRotation.z;
  23715. body.quaternion.w = -initialRotation.w;
  23716. }
  23717. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23718. this._world.add(body);
  23719. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23720. return body;
  23721. };
  23722. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23723. var compoundShape = new CANNON.Compound();
  23724. for (var index = 0; index < parts.length; index++) {
  23725. var mesh = parts[index].mesh;
  23726. var shape = this.registerMesh(mesh, parts[index].impostor);
  23727. if (index == 0) {
  23728. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23729. }
  23730. else {
  23731. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23732. }
  23733. }
  23734. var initialMesh = parts[0].mesh;
  23735. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23736. body.parts = parts;
  23737. return body;
  23738. };
  23739. CannonJSPlugin.prototype._unbindBody = function (body) {
  23740. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23741. var registeredMesh = this._registeredMeshes[index];
  23742. if (registeredMesh.body === body) {
  23743. registeredMesh.body = null;
  23744. registeredMesh.delta = 0;
  23745. }
  23746. }
  23747. };
  23748. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23749. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23750. var registeredMesh = this._registeredMeshes[index];
  23751. if (registeredMesh.mesh === mesh) {
  23752. // Remove body
  23753. if (registeredMesh.body) {
  23754. this._world.remove(registeredMesh.body);
  23755. this._unbindBody(registeredMesh.body);
  23756. }
  23757. this._registeredMeshes.splice(index, 1);
  23758. return;
  23759. }
  23760. }
  23761. };
  23762. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23763. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23764. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23765. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23766. var registeredMesh = this._registeredMeshes[index];
  23767. if (registeredMesh.mesh === mesh) {
  23768. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23769. return;
  23770. }
  23771. }
  23772. };
  23773. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23774. var body1 = null, body2 = null;
  23775. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23776. var registeredMesh = this._registeredMeshes[index];
  23777. if (registeredMesh.mesh === mesh1) {
  23778. body1 = registeredMesh.body;
  23779. }
  23780. else if (registeredMesh.mesh === mesh2) {
  23781. body2 = registeredMesh.body;
  23782. }
  23783. }
  23784. if (!body1 || !body2) {
  23785. return false;
  23786. }
  23787. 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));
  23788. this._world.addConstraint(constraint);
  23789. return true;
  23790. };
  23791. CannonJSPlugin.prototype.dispose = function () {
  23792. while (this._registeredMeshes.length) {
  23793. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23794. }
  23795. };
  23796. CannonJSPlugin.prototype.isSupported = function () {
  23797. return window.CANNON !== undefined;
  23798. };
  23799. return CannonJSPlugin;
  23800. })();
  23801. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23802. })(BABYLON || (BABYLON = {}));
  23803. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23804. var BABYLON;
  23805. (function (BABYLON) {
  23806. var Condition = (function () {
  23807. function Condition(actionManager) {
  23808. this._actionManager = actionManager;
  23809. }
  23810. Condition.prototype.isValid = function () {
  23811. return true;
  23812. };
  23813. Condition.prototype._getProperty = function (propertyPath) {
  23814. return this._actionManager._getProperty(propertyPath);
  23815. };
  23816. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23817. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23818. };
  23819. return Condition;
  23820. })();
  23821. BABYLON.Condition = Condition;
  23822. var ValueCondition = (function (_super) {
  23823. __extends(ValueCondition, _super);
  23824. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23825. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23826. _super.call(this, actionManager);
  23827. this.propertyPath = propertyPath;
  23828. this.value = value;
  23829. this.operator = operator;
  23830. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23831. this._property = this._getProperty(this.propertyPath);
  23832. }
  23833. Object.defineProperty(ValueCondition, "IsEqual", {
  23834. get: function () {
  23835. return ValueCondition._IsEqual;
  23836. },
  23837. enumerable: true,
  23838. configurable: true
  23839. });
  23840. Object.defineProperty(ValueCondition, "IsDifferent", {
  23841. get: function () {
  23842. return ValueCondition._IsDifferent;
  23843. },
  23844. enumerable: true,
  23845. configurable: true
  23846. });
  23847. Object.defineProperty(ValueCondition, "IsGreater", {
  23848. get: function () {
  23849. return ValueCondition._IsGreater;
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. Object.defineProperty(ValueCondition, "IsLesser", {
  23855. get: function () {
  23856. return ValueCondition._IsLesser;
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. // Methods
  23862. ValueCondition.prototype.isValid = function () {
  23863. switch (this.operator) {
  23864. case ValueCondition.IsGreater:
  23865. return this._target[this._property] > this.value;
  23866. case ValueCondition.IsLesser:
  23867. return this._target[this._property] < this.value;
  23868. case ValueCondition.IsEqual:
  23869. case ValueCondition.IsDifferent:
  23870. var check;
  23871. if (this.value.equals) {
  23872. check = this.value.equals(this._target[this._property]);
  23873. }
  23874. else {
  23875. check = this.value === this._target[this._property];
  23876. }
  23877. return this.operator === ValueCondition.IsEqual ? check : !check;
  23878. }
  23879. return false;
  23880. };
  23881. // Statics
  23882. ValueCondition._IsEqual = 0;
  23883. ValueCondition._IsDifferent = 1;
  23884. ValueCondition._IsGreater = 2;
  23885. ValueCondition._IsLesser = 3;
  23886. return ValueCondition;
  23887. })(Condition);
  23888. BABYLON.ValueCondition = ValueCondition;
  23889. var PredicateCondition = (function (_super) {
  23890. __extends(PredicateCondition, _super);
  23891. function PredicateCondition(actionManager, predicate) {
  23892. _super.call(this, actionManager);
  23893. this.predicate = predicate;
  23894. }
  23895. PredicateCondition.prototype.isValid = function () {
  23896. return this.predicate();
  23897. };
  23898. return PredicateCondition;
  23899. })(Condition);
  23900. BABYLON.PredicateCondition = PredicateCondition;
  23901. var StateCondition = (function (_super) {
  23902. __extends(StateCondition, _super);
  23903. function StateCondition(actionManager, target, value) {
  23904. _super.call(this, actionManager);
  23905. this.value = value;
  23906. this._target = target;
  23907. }
  23908. // Methods
  23909. StateCondition.prototype.isValid = function () {
  23910. return this._target.state === this.value;
  23911. };
  23912. return StateCondition;
  23913. })(Condition);
  23914. BABYLON.StateCondition = StateCondition;
  23915. })(BABYLON || (BABYLON = {}));
  23916. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23917. (function (BABYLON) {
  23918. var Action = (function () {
  23919. function Action(triggerOptions, condition) {
  23920. this.triggerOptions = triggerOptions;
  23921. if (triggerOptions.parameter) {
  23922. this.trigger = triggerOptions.trigger;
  23923. this._triggerParameter = triggerOptions.parameter;
  23924. }
  23925. else {
  23926. this.trigger = triggerOptions;
  23927. }
  23928. this._nextActiveAction = this;
  23929. this._condition = condition;
  23930. }
  23931. // Methods
  23932. Action.prototype._prepare = function () {
  23933. };
  23934. Action.prototype.getTriggerParameter = function () {
  23935. return this._triggerParameter;
  23936. };
  23937. Action.prototype._executeCurrent = function (evt) {
  23938. if (this._nextActiveAction._condition) {
  23939. var condition = this._nextActiveAction._condition;
  23940. var currentRenderId = this._actionManager.getScene().getRenderId();
  23941. // We cache the current evaluation for the current frame
  23942. if (condition._evaluationId === currentRenderId) {
  23943. if (!condition._currentResult) {
  23944. return;
  23945. }
  23946. }
  23947. else {
  23948. condition._evaluationId = currentRenderId;
  23949. if (!condition.isValid()) {
  23950. condition._currentResult = false;
  23951. return;
  23952. }
  23953. condition._currentResult = true;
  23954. }
  23955. }
  23956. this._nextActiveAction.execute(evt);
  23957. if (this._nextActiveAction._child) {
  23958. if (!this._nextActiveAction._child._actionManager) {
  23959. this._nextActiveAction._child._actionManager = this._actionManager;
  23960. }
  23961. this._nextActiveAction = this._nextActiveAction._child;
  23962. }
  23963. else {
  23964. this._nextActiveAction = this;
  23965. }
  23966. };
  23967. Action.prototype.execute = function (evt) {
  23968. };
  23969. Action.prototype.then = function (action) {
  23970. this._child = action;
  23971. action._actionManager = this._actionManager;
  23972. action._prepare();
  23973. return action;
  23974. };
  23975. Action.prototype._getProperty = function (propertyPath) {
  23976. return this._actionManager._getProperty(propertyPath);
  23977. };
  23978. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23979. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23980. };
  23981. return Action;
  23982. })();
  23983. BABYLON.Action = Action;
  23984. })(BABYLON || (BABYLON = {}));
  23985. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23986. (function (BABYLON) {
  23987. /**
  23988. * ActionEvent is the event beint sent when an action is triggered.
  23989. */
  23990. var ActionEvent = (function () {
  23991. /**
  23992. * @constructor
  23993. * @param source The mesh that triggered the action.
  23994. * @param pointerX the X mouse cursor position at the time of the event
  23995. * @param pointerY the Y mouse cursor position at the time of the event
  23996. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23997. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23998. */
  23999. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24000. this.source = source;
  24001. this.pointerX = pointerX;
  24002. this.pointerY = pointerY;
  24003. this.meshUnderPointer = meshUnderPointer;
  24004. this.sourceEvent = sourceEvent;
  24005. }
  24006. /**
  24007. * Helper function to auto-create an ActionEvent from a source mesh.
  24008. * @param source the source mesh that triggered the event
  24009. * @param evt {Event} The original (browser) event
  24010. */
  24011. ActionEvent.CreateNew = function (source, evt) {
  24012. var scene = source.getScene();
  24013. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24014. };
  24015. /**
  24016. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24017. * @param scene the scene where the event occurred
  24018. * @param evt {Event} The original (browser) event
  24019. */
  24020. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24021. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24022. };
  24023. return ActionEvent;
  24024. })();
  24025. BABYLON.ActionEvent = ActionEvent;
  24026. /**
  24027. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24028. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24029. */
  24030. var ActionManager = (function () {
  24031. function ActionManager(scene) {
  24032. // Members
  24033. this.actions = new Array();
  24034. this._scene = scene;
  24035. scene._actionManagers.push(this);
  24036. }
  24037. Object.defineProperty(ActionManager, "NothingTrigger", {
  24038. get: function () {
  24039. return ActionManager._NothingTrigger;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24045. get: function () {
  24046. return ActionManager._OnPickTrigger;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24052. get: function () {
  24053. return ActionManager._OnLeftPickTrigger;
  24054. },
  24055. enumerable: true,
  24056. configurable: true
  24057. });
  24058. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24059. get: function () {
  24060. return ActionManager._OnRightPickTrigger;
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24066. get: function () {
  24067. return ActionManager._OnCenterPickTrigger;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24073. get: function () {
  24074. return ActionManager._OnPointerOverTrigger;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24080. get: function () {
  24081. return ActionManager._OnPointerOutTrigger;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24087. get: function () {
  24088. return ActionManager._OnEveryFrameTrigger;
  24089. },
  24090. enumerable: true,
  24091. configurable: true
  24092. });
  24093. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24094. get: function () {
  24095. return ActionManager._OnIntersectionEnterTrigger;
  24096. },
  24097. enumerable: true,
  24098. configurable: true
  24099. });
  24100. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24101. get: function () {
  24102. return ActionManager._OnIntersectionExitTrigger;
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24108. get: function () {
  24109. return ActionManager._OnKeyDownTrigger;
  24110. },
  24111. enumerable: true,
  24112. configurable: true
  24113. });
  24114. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24115. get: function () {
  24116. return ActionManager._OnKeyUpTrigger;
  24117. },
  24118. enumerable: true,
  24119. configurable: true
  24120. });
  24121. // Methods
  24122. ActionManager.prototype.dispose = function () {
  24123. var index = this._scene._actionManagers.indexOf(this);
  24124. if (index > -1) {
  24125. this._scene._actionManagers.splice(index, 1);
  24126. }
  24127. };
  24128. ActionManager.prototype.getScene = function () {
  24129. return this._scene;
  24130. };
  24131. /**
  24132. * Does this action manager handles actions of any of the given triggers
  24133. * @param {number[]} triggers - the triggers to be tested
  24134. * @return {boolean} whether one (or more) of the triggers is handeled
  24135. */
  24136. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24137. for (var index = 0; index < this.actions.length; index++) {
  24138. var action = this.actions[index];
  24139. if (triggers.indexOf(action.trigger) > -1) {
  24140. return true;
  24141. }
  24142. }
  24143. return false;
  24144. };
  24145. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24146. /**
  24147. * Does this action manager has pointer triggers
  24148. * @return {boolean} whether or not it has pointer triggers
  24149. */
  24150. get: function () {
  24151. for (var index = 0; index < this.actions.length; index++) {
  24152. var action = this.actions[index];
  24153. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24154. return true;
  24155. }
  24156. }
  24157. return false;
  24158. },
  24159. enumerable: true,
  24160. configurable: true
  24161. });
  24162. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24163. /**
  24164. * Does this action manager has pick triggers
  24165. * @return {boolean} whether or not it has pick triggers
  24166. */
  24167. get: function () {
  24168. for (var index = 0; index < this.actions.length; index++) {
  24169. var action = this.actions[index];
  24170. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24171. return true;
  24172. }
  24173. }
  24174. return false;
  24175. },
  24176. enumerable: true,
  24177. configurable: true
  24178. });
  24179. /**
  24180. * Registers an action to this action manager
  24181. * @param {BABYLON.Action} action - the action to be registered
  24182. * @return {BABYLON.Action} the action amended (prepared) after registration
  24183. */
  24184. ActionManager.prototype.registerAction = function (action) {
  24185. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24186. if (this.getScene().actionManager !== this) {
  24187. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24188. return null;
  24189. }
  24190. }
  24191. this.actions.push(action);
  24192. action._actionManager = this;
  24193. action._prepare();
  24194. return action;
  24195. };
  24196. /**
  24197. * Process a specific trigger
  24198. * @param {number} trigger - the trigger to process
  24199. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24200. */
  24201. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24202. for (var index = 0; index < this.actions.length; index++) {
  24203. var action = this.actions[index];
  24204. if (action.trigger === trigger) {
  24205. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24206. var parameter = action.getTriggerParameter();
  24207. if (parameter) {
  24208. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24209. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24210. if (actualkey !== parameter.toLowerCase()) {
  24211. continue;
  24212. }
  24213. }
  24214. }
  24215. action._executeCurrent(evt);
  24216. }
  24217. }
  24218. };
  24219. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24220. var properties = propertyPath.split(".");
  24221. for (var index = 0; index < properties.length - 1; index++) {
  24222. target = target[properties[index]];
  24223. }
  24224. return target;
  24225. };
  24226. ActionManager.prototype._getProperty = function (propertyPath) {
  24227. var properties = propertyPath.split(".");
  24228. return properties[properties.length - 1];
  24229. };
  24230. // Statics
  24231. ActionManager._NothingTrigger = 0;
  24232. ActionManager._OnPickTrigger = 1;
  24233. ActionManager._OnLeftPickTrigger = 2;
  24234. ActionManager._OnRightPickTrigger = 3;
  24235. ActionManager._OnCenterPickTrigger = 4;
  24236. ActionManager._OnPointerOverTrigger = 5;
  24237. ActionManager._OnPointerOutTrigger = 6;
  24238. ActionManager._OnEveryFrameTrigger = 7;
  24239. ActionManager._OnIntersectionEnterTrigger = 8;
  24240. ActionManager._OnIntersectionExitTrigger = 9;
  24241. ActionManager._OnKeyDownTrigger = 10;
  24242. ActionManager._OnKeyUpTrigger = 11;
  24243. return ActionManager;
  24244. })();
  24245. BABYLON.ActionManager = ActionManager;
  24246. })(BABYLON || (BABYLON = {}));
  24247. //# sourceMappingURL=babylon.actionManager.js.map
  24248. var BABYLON;
  24249. (function (BABYLON) {
  24250. var InterpolateValueAction = (function (_super) {
  24251. __extends(InterpolateValueAction, _super);
  24252. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24253. if (duration === void 0) { duration = 1000; }
  24254. _super.call(this, triggerOptions, condition);
  24255. this.propertyPath = propertyPath;
  24256. this.value = value;
  24257. this.duration = duration;
  24258. this.stopOtherAnimations = stopOtherAnimations;
  24259. this._target = target;
  24260. }
  24261. InterpolateValueAction.prototype._prepare = function () {
  24262. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24263. this._property = this._getProperty(this.propertyPath);
  24264. };
  24265. InterpolateValueAction.prototype.execute = function () {
  24266. var scene = this._actionManager.getScene();
  24267. var keys = [
  24268. {
  24269. frame: 0,
  24270. value: this._target[this._property]
  24271. },
  24272. {
  24273. frame: 100,
  24274. value: this.value
  24275. }
  24276. ];
  24277. var dataType;
  24278. if (typeof this.value === "number") {
  24279. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24280. }
  24281. else if (this.value instanceof BABYLON.Color3) {
  24282. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24283. }
  24284. else if (this.value instanceof BABYLON.Vector3) {
  24285. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24286. }
  24287. else if (this.value instanceof BABYLON.Matrix) {
  24288. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24289. }
  24290. else if (this.value instanceof BABYLON.Quaternion) {
  24291. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24292. }
  24293. else {
  24294. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24295. return;
  24296. }
  24297. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24298. animation.setKeys(keys);
  24299. if (this.stopOtherAnimations) {
  24300. scene.stopAnimation(this._target);
  24301. }
  24302. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24303. };
  24304. return InterpolateValueAction;
  24305. })(BABYLON.Action);
  24306. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24307. })(BABYLON || (BABYLON = {}));
  24308. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24309. var BABYLON;
  24310. (function (BABYLON) {
  24311. var SwitchBooleanAction = (function (_super) {
  24312. __extends(SwitchBooleanAction, _super);
  24313. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24314. _super.call(this, triggerOptions, condition);
  24315. this.propertyPath = propertyPath;
  24316. this._target = target;
  24317. }
  24318. SwitchBooleanAction.prototype._prepare = function () {
  24319. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24320. this._property = this._getProperty(this.propertyPath);
  24321. };
  24322. SwitchBooleanAction.prototype.execute = function () {
  24323. this._target[this._property] = !this._target[this._property];
  24324. };
  24325. return SwitchBooleanAction;
  24326. })(BABYLON.Action);
  24327. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24328. var SetStateAction = (function (_super) {
  24329. __extends(SetStateAction, _super);
  24330. function SetStateAction(triggerOptions, target, value, condition) {
  24331. _super.call(this, triggerOptions, condition);
  24332. this.value = value;
  24333. this._target = target;
  24334. }
  24335. SetStateAction.prototype.execute = function () {
  24336. this._target.state = this.value;
  24337. };
  24338. return SetStateAction;
  24339. })(BABYLON.Action);
  24340. BABYLON.SetStateAction = SetStateAction;
  24341. var SetValueAction = (function (_super) {
  24342. __extends(SetValueAction, _super);
  24343. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24344. _super.call(this, triggerOptions, condition);
  24345. this.propertyPath = propertyPath;
  24346. this.value = value;
  24347. this._target = target;
  24348. }
  24349. SetValueAction.prototype._prepare = function () {
  24350. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24351. this._property = this._getProperty(this.propertyPath);
  24352. };
  24353. SetValueAction.prototype.execute = function () {
  24354. this._target[this._property] = this.value;
  24355. };
  24356. return SetValueAction;
  24357. })(BABYLON.Action);
  24358. BABYLON.SetValueAction = SetValueAction;
  24359. var IncrementValueAction = (function (_super) {
  24360. __extends(IncrementValueAction, _super);
  24361. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24362. _super.call(this, triggerOptions, condition);
  24363. this.propertyPath = propertyPath;
  24364. this.value = value;
  24365. this._target = target;
  24366. }
  24367. IncrementValueAction.prototype._prepare = function () {
  24368. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24369. this._property = this._getProperty(this.propertyPath);
  24370. if (typeof this._target[this._property] !== "number") {
  24371. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24372. }
  24373. };
  24374. IncrementValueAction.prototype.execute = function () {
  24375. this._target[this._property] += this.value;
  24376. };
  24377. return IncrementValueAction;
  24378. })(BABYLON.Action);
  24379. BABYLON.IncrementValueAction = IncrementValueAction;
  24380. var PlayAnimationAction = (function (_super) {
  24381. __extends(PlayAnimationAction, _super);
  24382. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24383. _super.call(this, triggerOptions, condition);
  24384. this.from = from;
  24385. this.to = to;
  24386. this.loop = loop;
  24387. this._target = target;
  24388. }
  24389. PlayAnimationAction.prototype._prepare = function () {
  24390. };
  24391. PlayAnimationAction.prototype.execute = function () {
  24392. var scene = this._actionManager.getScene();
  24393. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24394. };
  24395. return PlayAnimationAction;
  24396. })(BABYLON.Action);
  24397. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24398. var StopAnimationAction = (function (_super) {
  24399. __extends(StopAnimationAction, _super);
  24400. function StopAnimationAction(triggerOptions, target, condition) {
  24401. _super.call(this, triggerOptions, condition);
  24402. this._target = target;
  24403. }
  24404. StopAnimationAction.prototype._prepare = function () {
  24405. };
  24406. StopAnimationAction.prototype.execute = function () {
  24407. var scene = this._actionManager.getScene();
  24408. scene.stopAnimation(this._target);
  24409. };
  24410. return StopAnimationAction;
  24411. })(BABYLON.Action);
  24412. BABYLON.StopAnimationAction = StopAnimationAction;
  24413. var DoNothingAction = (function (_super) {
  24414. __extends(DoNothingAction, _super);
  24415. function DoNothingAction(triggerOptions, condition) {
  24416. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24417. _super.call(this, triggerOptions, condition);
  24418. }
  24419. DoNothingAction.prototype.execute = function () {
  24420. };
  24421. return DoNothingAction;
  24422. })(BABYLON.Action);
  24423. BABYLON.DoNothingAction = DoNothingAction;
  24424. var CombineAction = (function (_super) {
  24425. __extends(CombineAction, _super);
  24426. function CombineAction(triggerOptions, children, condition) {
  24427. _super.call(this, triggerOptions, condition);
  24428. this.children = children;
  24429. }
  24430. CombineAction.prototype._prepare = function () {
  24431. for (var index = 0; index < this.children.length; index++) {
  24432. this.children[index]._actionManager = this._actionManager;
  24433. this.children[index]._prepare();
  24434. }
  24435. };
  24436. CombineAction.prototype.execute = function (evt) {
  24437. for (var index = 0; index < this.children.length; index++) {
  24438. this.children[index].execute(evt);
  24439. }
  24440. };
  24441. return CombineAction;
  24442. })(BABYLON.Action);
  24443. BABYLON.CombineAction = CombineAction;
  24444. var ExecuteCodeAction = (function (_super) {
  24445. __extends(ExecuteCodeAction, _super);
  24446. function ExecuteCodeAction(triggerOptions, func, condition) {
  24447. _super.call(this, triggerOptions, condition);
  24448. this.func = func;
  24449. }
  24450. ExecuteCodeAction.prototype.execute = function (evt) {
  24451. this.func(evt);
  24452. };
  24453. return ExecuteCodeAction;
  24454. })(BABYLON.Action);
  24455. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24456. var SetParentAction = (function (_super) {
  24457. __extends(SetParentAction, _super);
  24458. function SetParentAction(triggerOptions, target, parent, condition) {
  24459. _super.call(this, triggerOptions, condition);
  24460. this._target = target;
  24461. this._parent = parent;
  24462. }
  24463. SetParentAction.prototype._prepare = function () {
  24464. };
  24465. SetParentAction.prototype.execute = function () {
  24466. if (this._target.parent === this._parent) {
  24467. return;
  24468. }
  24469. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24470. invertParentWorldMatrix.invert();
  24471. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24472. this._target.parent = this._parent;
  24473. };
  24474. return SetParentAction;
  24475. })(BABYLON.Action);
  24476. BABYLON.SetParentAction = SetParentAction;
  24477. var PlaySoundAction = (function (_super) {
  24478. __extends(PlaySoundAction, _super);
  24479. function PlaySoundAction(triggerOptions, sound, condition) {
  24480. _super.call(this, triggerOptions, condition);
  24481. this._sound = sound;
  24482. }
  24483. PlaySoundAction.prototype._prepare = function () {
  24484. };
  24485. PlaySoundAction.prototype.execute = function () {
  24486. if (this._sound !== undefined)
  24487. this._sound.play();
  24488. };
  24489. return PlaySoundAction;
  24490. })(BABYLON.Action);
  24491. BABYLON.PlaySoundAction = PlaySoundAction;
  24492. var StopSoundAction = (function (_super) {
  24493. __extends(StopSoundAction, _super);
  24494. function StopSoundAction(triggerOptions, sound, condition) {
  24495. _super.call(this, triggerOptions, condition);
  24496. this._sound = sound;
  24497. }
  24498. StopSoundAction.prototype._prepare = function () {
  24499. };
  24500. StopSoundAction.prototype.execute = function () {
  24501. if (this._sound !== undefined)
  24502. this._sound.stop();
  24503. };
  24504. return StopSoundAction;
  24505. })(BABYLON.Action);
  24506. BABYLON.StopSoundAction = StopSoundAction;
  24507. })(BABYLON || (BABYLON = {}));
  24508. //# sourceMappingURL=babylon.directActions.js.map
  24509. var BABYLON;
  24510. (function (BABYLON) {
  24511. var Geometry = (function () {
  24512. function Geometry(id, scene, vertexData, updatable, mesh) {
  24513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24514. this._totalVertices = 0;
  24515. this._indices = [];
  24516. this.id = id;
  24517. this._engine = scene.getEngine();
  24518. this._meshes = [];
  24519. this._scene = scene;
  24520. // vertexData
  24521. if (vertexData) {
  24522. this.setAllVerticesData(vertexData, updatable);
  24523. }
  24524. else {
  24525. this._totalVertices = 0;
  24526. this._indices = [];
  24527. }
  24528. // applyToMesh
  24529. if (mesh) {
  24530. this.applyToMesh(mesh);
  24531. mesh.computeWorldMatrix(true);
  24532. }
  24533. }
  24534. Geometry.prototype.getScene = function () {
  24535. return this._scene;
  24536. };
  24537. Geometry.prototype.getEngine = function () {
  24538. return this._engine;
  24539. };
  24540. Geometry.prototype.isReady = function () {
  24541. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24542. };
  24543. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24544. vertexData.applyToGeometry(this, updatable);
  24545. };
  24546. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24547. this._vertexBuffers = this._vertexBuffers || {};
  24548. if (this._vertexBuffers[kind]) {
  24549. this._vertexBuffers[kind].dispose();
  24550. }
  24551. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24552. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24553. stride = this._vertexBuffers[kind].getStrideSize();
  24554. this._totalVertices = data.length / stride;
  24555. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24556. var meshes = this._meshes;
  24557. var numOfMeshes = meshes.length;
  24558. for (var index = 0; index < numOfMeshes; index++) {
  24559. var mesh = meshes[index];
  24560. mesh._resetPointsArrayCache();
  24561. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24562. mesh._createGlobalSubMesh();
  24563. mesh.computeWorldMatrix(true);
  24564. }
  24565. }
  24566. };
  24567. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24568. var vertexBuffer = this.getVertexBuffer(kind);
  24569. if (!vertexBuffer) {
  24570. return;
  24571. }
  24572. vertexBuffer.updateDirectly(data, offset);
  24573. };
  24574. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24575. var vertexBuffer = this.getVertexBuffer(kind);
  24576. if (!vertexBuffer) {
  24577. return;
  24578. }
  24579. vertexBuffer.update(data);
  24580. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24581. var extend;
  24582. var stride = vertexBuffer.getStrideSize();
  24583. this._totalVertices = data.length / stride;
  24584. if (updateExtends) {
  24585. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24586. }
  24587. var meshes = this._meshes;
  24588. var numOfMeshes = meshes.length;
  24589. for (var index = 0; index < numOfMeshes; index++) {
  24590. var mesh = meshes[index];
  24591. mesh._resetPointsArrayCache();
  24592. if (updateExtends) {
  24593. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24594. }
  24595. }
  24596. }
  24597. };
  24598. Geometry.prototype.getTotalVertices = function () {
  24599. if (!this.isReady()) {
  24600. return 0;
  24601. }
  24602. return this._totalVertices;
  24603. };
  24604. Geometry.prototype.getVerticesData = function (kind) {
  24605. var vertexBuffer = this.getVertexBuffer(kind);
  24606. if (!vertexBuffer) {
  24607. return null;
  24608. }
  24609. return vertexBuffer.getData();
  24610. };
  24611. Geometry.prototype.getVertexBuffer = function (kind) {
  24612. if (!this.isReady()) {
  24613. return null;
  24614. }
  24615. return this._vertexBuffers[kind];
  24616. };
  24617. Geometry.prototype.getVertexBuffers = function () {
  24618. if (!this.isReady()) {
  24619. return null;
  24620. }
  24621. return this._vertexBuffers;
  24622. };
  24623. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24624. if (!this._vertexBuffers) {
  24625. if (this._delayInfo) {
  24626. return this._delayInfo.indexOf(kind) !== -1;
  24627. }
  24628. return false;
  24629. }
  24630. return this._vertexBuffers[kind] !== undefined;
  24631. };
  24632. Geometry.prototype.getVerticesDataKinds = function () {
  24633. var result = [];
  24634. if (!this._vertexBuffers && this._delayInfo) {
  24635. for (var kind in this._delayInfo) {
  24636. result.push(kind);
  24637. }
  24638. }
  24639. else {
  24640. for (kind in this._vertexBuffers) {
  24641. result.push(kind);
  24642. }
  24643. }
  24644. return result;
  24645. };
  24646. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24647. if (this._indexBuffer) {
  24648. this._engine._releaseBuffer(this._indexBuffer);
  24649. }
  24650. this._indices = indices;
  24651. if (this._meshes.length !== 0 && this._indices) {
  24652. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24653. }
  24654. if (totalVertices !== undefined) {
  24655. this._totalVertices = totalVertices;
  24656. }
  24657. var meshes = this._meshes;
  24658. var numOfMeshes = meshes.length;
  24659. for (var index = 0; index < numOfMeshes; index++) {
  24660. meshes[index]._createGlobalSubMesh();
  24661. }
  24662. };
  24663. Geometry.prototype.getTotalIndices = function () {
  24664. if (!this.isReady()) {
  24665. return 0;
  24666. }
  24667. return this._indices.length;
  24668. };
  24669. Geometry.prototype.getIndices = function () {
  24670. if (!this.isReady()) {
  24671. return null;
  24672. }
  24673. return this._indices;
  24674. };
  24675. Geometry.prototype.getIndexBuffer = function () {
  24676. if (!this.isReady()) {
  24677. return null;
  24678. }
  24679. return this._indexBuffer;
  24680. };
  24681. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24682. var meshes = this._meshes;
  24683. var index = meshes.indexOf(mesh);
  24684. if (index === -1) {
  24685. return;
  24686. }
  24687. for (var kind in this._vertexBuffers) {
  24688. this._vertexBuffers[kind].dispose();
  24689. }
  24690. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24691. this._indexBuffer = null;
  24692. }
  24693. meshes.splice(index, 1);
  24694. mesh._geometry = null;
  24695. if (meshes.length === 0 && shouldDispose) {
  24696. this.dispose();
  24697. }
  24698. };
  24699. Geometry.prototype.applyToMesh = function (mesh) {
  24700. if (mesh._geometry === this) {
  24701. return;
  24702. }
  24703. var previousGeometry = mesh._geometry;
  24704. if (previousGeometry) {
  24705. previousGeometry.releaseForMesh(mesh);
  24706. }
  24707. var meshes = this._meshes;
  24708. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24709. mesh._geometry = this;
  24710. this._scene.pushGeometry(this);
  24711. meshes.push(mesh);
  24712. if (this.isReady()) {
  24713. this._applyToMesh(mesh);
  24714. }
  24715. else {
  24716. mesh._boundingInfo = this._boundingInfo;
  24717. }
  24718. };
  24719. Geometry.prototype._applyToMesh = function (mesh) {
  24720. var numOfMeshes = this._meshes.length;
  24721. for (var kind in this._vertexBuffers) {
  24722. if (numOfMeshes === 1) {
  24723. this._vertexBuffers[kind].create();
  24724. }
  24725. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24726. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24727. mesh._resetPointsArrayCache();
  24728. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24729. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24730. mesh._createGlobalSubMesh();
  24731. //bounding info was just created again, world matrix should be applied again.
  24732. mesh._updateBoundingInfo();
  24733. }
  24734. }
  24735. // indexBuffer
  24736. if (numOfMeshes === 1 && this._indices) {
  24737. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24738. }
  24739. if (this._indexBuffer) {
  24740. this._indexBuffer.references = numOfMeshes;
  24741. }
  24742. };
  24743. Geometry.prototype.load = function (scene, onLoaded) {
  24744. var _this = this;
  24745. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24746. return;
  24747. }
  24748. if (this.isReady()) {
  24749. if (onLoaded) {
  24750. onLoaded();
  24751. }
  24752. return;
  24753. }
  24754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24755. scene._addPendingData(this);
  24756. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24757. _this._delayLoadingFunction(JSON.parse(data), _this);
  24758. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24759. _this._delayInfo = [];
  24760. scene._removePendingData(_this);
  24761. var meshes = _this._meshes;
  24762. var numOfMeshes = meshes.length;
  24763. for (var index = 0; index < numOfMeshes; index++) {
  24764. _this._applyToMesh(meshes[index]);
  24765. }
  24766. if (onLoaded) {
  24767. onLoaded();
  24768. }
  24769. }, function () {
  24770. }, scene.database);
  24771. };
  24772. Geometry.prototype.dispose = function () {
  24773. var meshes = this._meshes;
  24774. var numOfMeshes = meshes.length;
  24775. var index;
  24776. for (index = 0; index < numOfMeshes; index++) {
  24777. this.releaseForMesh(meshes[index]);
  24778. }
  24779. this._meshes = [];
  24780. for (var kind in this._vertexBuffers) {
  24781. this._vertexBuffers[kind].dispose();
  24782. }
  24783. this._vertexBuffers = [];
  24784. this._totalVertices = 0;
  24785. if (this._indexBuffer) {
  24786. this._engine._releaseBuffer(this._indexBuffer);
  24787. }
  24788. this._indexBuffer = null;
  24789. this._indices = [];
  24790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24791. this.delayLoadingFile = null;
  24792. this._delayLoadingFunction = null;
  24793. this._delayInfo = [];
  24794. this._boundingInfo = null; // todo: .dispose()
  24795. var geometries = this._scene.getGeometries();
  24796. index = geometries.indexOf(this);
  24797. if (index > -1) {
  24798. geometries.splice(index, 1);
  24799. }
  24800. };
  24801. Geometry.prototype.copy = function (id) {
  24802. var vertexData = new BABYLON.VertexData();
  24803. vertexData.indices = [];
  24804. var indices = this.getIndices();
  24805. for (var index = 0; index < indices.length; index++) {
  24806. vertexData.indices.push(indices[index]);
  24807. }
  24808. var updatable = false;
  24809. var stopChecking = false;
  24810. for (var kind in this._vertexBuffers) {
  24811. vertexData.set(this.getVerticesData(kind), kind);
  24812. if (!stopChecking) {
  24813. updatable = this.getVertexBuffer(kind).isUpdatable();
  24814. stopChecking = !updatable;
  24815. }
  24816. }
  24817. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24818. geometry.delayLoadState = this.delayLoadState;
  24819. geometry.delayLoadingFile = this.delayLoadingFile;
  24820. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24821. for (kind in this._delayInfo) {
  24822. geometry._delayInfo = geometry._delayInfo || [];
  24823. geometry._delayInfo.push(kind);
  24824. }
  24825. // Bounding info
  24826. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24827. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24828. return geometry;
  24829. };
  24830. // Statics
  24831. Geometry.ExtractFromMesh = function (mesh, id) {
  24832. var geometry = mesh._geometry;
  24833. if (!geometry) {
  24834. return null;
  24835. }
  24836. return geometry.copy(id);
  24837. };
  24838. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24839. // be aware Math.random() could cause collisions
  24840. Geometry.RandomId = function () {
  24841. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24842. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24843. return v.toString(16);
  24844. });
  24845. };
  24846. return Geometry;
  24847. })();
  24848. BABYLON.Geometry = Geometry;
  24849. /////// Primitives //////////////////////////////////////////////
  24850. var Geometry;
  24851. (function (Geometry) {
  24852. var Primitives;
  24853. (function (Primitives) {
  24854. /// Abstract class
  24855. var _Primitive = (function (_super) {
  24856. __extends(_Primitive, _super);
  24857. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24858. this._beingRegenerated = true;
  24859. this._canBeRegenerated = canBeRegenerated;
  24860. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24861. this._beingRegenerated = false;
  24862. }
  24863. _Primitive.prototype.canBeRegenerated = function () {
  24864. return this._canBeRegenerated;
  24865. };
  24866. _Primitive.prototype.regenerate = function () {
  24867. if (!this._canBeRegenerated) {
  24868. return;
  24869. }
  24870. this._beingRegenerated = true;
  24871. this.setAllVerticesData(this._regenerateVertexData(), false);
  24872. this._beingRegenerated = false;
  24873. };
  24874. _Primitive.prototype.asNewGeometry = function (id) {
  24875. return _super.prototype.copy.call(this, id);
  24876. };
  24877. // overrides
  24878. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24879. if (!this._beingRegenerated) {
  24880. return;
  24881. }
  24882. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24883. };
  24884. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24885. if (!this._beingRegenerated) {
  24886. return;
  24887. }
  24888. _super.prototype.setVerticesData.call(this, kind, data, false);
  24889. };
  24890. // to override
  24891. // protected
  24892. _Primitive.prototype._regenerateVertexData = function () {
  24893. throw new Error("Abstract method");
  24894. };
  24895. _Primitive.prototype.copy = function (id) {
  24896. throw new Error("Must be overriden in sub-classes.");
  24897. };
  24898. return _Primitive;
  24899. })(Geometry);
  24900. Primitives._Primitive = _Primitive;
  24901. var Ribbon = (function (_super) {
  24902. __extends(Ribbon, _super);
  24903. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24904. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24905. this.pathArray = pathArray;
  24906. this.closeArray = closeArray;
  24907. this.closePath = closePath;
  24908. this.offset = offset;
  24909. this.side = side;
  24910. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24911. }
  24912. Ribbon.prototype._regenerateVertexData = function () {
  24913. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24914. };
  24915. Ribbon.prototype.copy = function (id) {
  24916. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24917. };
  24918. return Ribbon;
  24919. })(_Primitive);
  24920. Primitives.Ribbon = Ribbon;
  24921. var Box = (function (_super) {
  24922. __extends(Box, _super);
  24923. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24924. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24925. this.size = size;
  24926. this.side = side;
  24927. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24928. }
  24929. Box.prototype._regenerateVertexData = function () {
  24930. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24931. };
  24932. Box.prototype.copy = function (id) {
  24933. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24934. };
  24935. return Box;
  24936. })(_Primitive);
  24937. Primitives.Box = Box;
  24938. var Sphere = (function (_super) {
  24939. __extends(Sphere, _super);
  24940. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24942. this.segments = segments;
  24943. this.diameter = diameter;
  24944. this.side = side;
  24945. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24946. }
  24947. Sphere.prototype._regenerateVertexData = function () {
  24948. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24949. };
  24950. Sphere.prototype.copy = function (id) {
  24951. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24952. };
  24953. return Sphere;
  24954. })(_Primitive);
  24955. Primitives.Sphere = Sphere;
  24956. var Cylinder = (function (_super) {
  24957. __extends(Cylinder, _super);
  24958. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24959. if (subdivisions === void 0) { subdivisions = 1; }
  24960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24961. this.height = height;
  24962. this.diameterTop = diameterTop;
  24963. this.diameterBottom = diameterBottom;
  24964. this.tessellation = tessellation;
  24965. this.subdivisions = subdivisions;
  24966. this.side = side;
  24967. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24968. }
  24969. Cylinder.prototype._regenerateVertexData = function () {
  24970. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24971. };
  24972. Cylinder.prototype.copy = function (id) {
  24973. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24974. };
  24975. return Cylinder;
  24976. })(_Primitive);
  24977. Primitives.Cylinder = Cylinder;
  24978. var Torus = (function (_super) {
  24979. __extends(Torus, _super);
  24980. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24982. this.diameter = diameter;
  24983. this.thickness = thickness;
  24984. this.tessellation = tessellation;
  24985. this.side = side;
  24986. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24987. }
  24988. Torus.prototype._regenerateVertexData = function () {
  24989. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24990. };
  24991. Torus.prototype.copy = function (id) {
  24992. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24993. };
  24994. return Torus;
  24995. })(_Primitive);
  24996. Primitives.Torus = Torus;
  24997. var Ground = (function (_super) {
  24998. __extends(Ground, _super);
  24999. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25000. this.width = width;
  25001. this.height = height;
  25002. this.subdivisions = subdivisions;
  25003. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25004. }
  25005. Ground.prototype._regenerateVertexData = function () {
  25006. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25007. };
  25008. Ground.prototype.copy = function (id) {
  25009. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25010. };
  25011. return Ground;
  25012. })(_Primitive);
  25013. Primitives.Ground = Ground;
  25014. var TiledGround = (function (_super) {
  25015. __extends(TiledGround, _super);
  25016. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25017. this.xmin = xmin;
  25018. this.zmin = zmin;
  25019. this.xmax = xmax;
  25020. this.zmax = zmax;
  25021. this.subdivisions = subdivisions;
  25022. this.precision = precision;
  25023. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25024. }
  25025. TiledGround.prototype._regenerateVertexData = function () {
  25026. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25027. };
  25028. TiledGround.prototype.copy = function (id) {
  25029. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25030. };
  25031. return TiledGround;
  25032. })(_Primitive);
  25033. Primitives.TiledGround = TiledGround;
  25034. var Plane = (function (_super) {
  25035. __extends(Plane, _super);
  25036. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25038. this.size = size;
  25039. this.side = side;
  25040. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25041. }
  25042. Plane.prototype._regenerateVertexData = function () {
  25043. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25044. };
  25045. Plane.prototype.copy = function (id) {
  25046. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25047. };
  25048. return Plane;
  25049. })(_Primitive);
  25050. Primitives.Plane = Plane;
  25051. var TorusKnot = (function (_super) {
  25052. __extends(TorusKnot, _super);
  25053. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25054. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25055. this.radius = radius;
  25056. this.tube = tube;
  25057. this.radialSegments = radialSegments;
  25058. this.tubularSegments = tubularSegments;
  25059. this.p = p;
  25060. this.q = q;
  25061. this.side = side;
  25062. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25063. }
  25064. TorusKnot.prototype._regenerateVertexData = function () {
  25065. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25066. };
  25067. TorusKnot.prototype.copy = function (id) {
  25068. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25069. };
  25070. return TorusKnot;
  25071. })(_Primitive);
  25072. Primitives.TorusKnot = TorusKnot;
  25073. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25074. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25075. })(BABYLON || (BABYLON = {}));
  25076. //# sourceMappingURL=babylon.geometry.js.map
  25077. var BABYLON;
  25078. (function (BABYLON) {
  25079. var Gamepads = (function () {
  25080. function Gamepads(ongamedpadconnected) {
  25081. var _this = this;
  25082. this.babylonGamepads = [];
  25083. this.oneGamepadConnected = false;
  25084. this.isMonitoring = false;
  25085. this.gamepadEventSupported = 'GamepadEvent' in window;
  25086. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25087. 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=";
  25088. this._callbackGamepadConnected = ongamedpadconnected;
  25089. if (this.gamepadSupportAvailable) {
  25090. // Checking if the gamepad connected event is supported (like in Firefox)
  25091. if (this.gamepadEventSupported) {
  25092. window.addEventListener('gamepadconnected', function (evt) {
  25093. _this._onGamepadConnected(evt);
  25094. }, false);
  25095. window.addEventListener('gamepaddisconnected', function (evt) {
  25096. _this._onGamepadDisconnected(evt);
  25097. }, false);
  25098. }
  25099. else {
  25100. this._startMonitoringGamepads();
  25101. }
  25102. if (!this.oneGamepadConnected) {
  25103. this._insertGamepadDOMInstructions();
  25104. }
  25105. }
  25106. else {
  25107. this._insertGamepadDOMNotSupported();
  25108. }
  25109. }
  25110. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25111. Gamepads.gamepadDOMInfo = document.createElement("div");
  25112. var buttonAImage = document.createElement("img");
  25113. buttonAImage.src = this.buttonADataURL;
  25114. var spanMessage = document.createElement("span");
  25115. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25116. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25117. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25118. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25119. Gamepads.gamepadDOMInfo.style.width = "100%";
  25120. Gamepads.gamepadDOMInfo.style.height = "48px";
  25121. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25122. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25123. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25124. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25125. buttonAImage.style.position = "relative";
  25126. buttonAImage.style.bottom = "8px";
  25127. spanMessage.style.position = "relative";
  25128. spanMessage.style.fontSize = "32px";
  25129. spanMessage.style.bottom = "32px";
  25130. spanMessage.style.color = "green";
  25131. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25132. };
  25133. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25134. Gamepads.gamepadDOMInfo = document.createElement("div");
  25135. var spanMessage = document.createElement("span");
  25136. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25137. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25138. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25139. Gamepads.gamepadDOMInfo.style.width = "100%";
  25140. Gamepads.gamepadDOMInfo.style.height = "40px";
  25141. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25142. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25143. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25144. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25145. spanMessage.style.position = "relative";
  25146. spanMessage.style.fontSize = "32px";
  25147. spanMessage.style.color = "red";
  25148. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25149. };
  25150. Gamepads.prototype.dispose = function () {
  25151. if (Gamepads.gamepadDOMInfo) {
  25152. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25153. }
  25154. };
  25155. Gamepads.prototype._onGamepadConnected = function (evt) {
  25156. var newGamepad = this._addNewGamepad(evt.gamepad);
  25157. if (this._callbackGamepadConnected)
  25158. this._callbackGamepadConnected(newGamepad);
  25159. this._startMonitoringGamepads();
  25160. };
  25161. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25162. if (!this.oneGamepadConnected) {
  25163. this.oneGamepadConnected = true;
  25164. if (Gamepads.gamepadDOMInfo) {
  25165. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25166. Gamepads.gamepadDOMInfo = null;
  25167. }
  25168. }
  25169. var newGamepad;
  25170. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25171. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25172. }
  25173. else {
  25174. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25175. }
  25176. this.babylonGamepads.push(newGamepad);
  25177. return newGamepad;
  25178. };
  25179. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25180. for (var i in this.babylonGamepads) {
  25181. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25182. this.babylonGamepads.splice(i, 1);
  25183. break;
  25184. }
  25185. }
  25186. // If no gamepads are left, stop the polling loop.
  25187. if (this.babylonGamepads.length == 0) {
  25188. this._stopMonitoringGamepads();
  25189. }
  25190. };
  25191. Gamepads.prototype._startMonitoringGamepads = function () {
  25192. if (!this.isMonitoring) {
  25193. this.isMonitoring = true;
  25194. this._checkGamepadsStatus();
  25195. }
  25196. };
  25197. Gamepads.prototype._stopMonitoringGamepads = function () {
  25198. this.isMonitoring = false;
  25199. };
  25200. Gamepads.prototype._checkGamepadsStatus = function () {
  25201. var _this = this;
  25202. // updating gamepad objects
  25203. this._updateGamepadObjects();
  25204. for (var i in this.babylonGamepads) {
  25205. this.babylonGamepads[i].update();
  25206. }
  25207. if (this.isMonitoring) {
  25208. if (window.requestAnimationFrame) {
  25209. window.requestAnimationFrame(function () {
  25210. _this._checkGamepadsStatus();
  25211. });
  25212. }
  25213. else if (window.mozRequestAnimationFrame) {
  25214. window.mozRequestAnimationFrame(function () {
  25215. _this._checkGamepadsStatus();
  25216. });
  25217. }
  25218. else if (window.webkitRequestAnimationFrame) {
  25219. window.webkitRequestAnimationFrame(function () {
  25220. _this._checkGamepadsStatus();
  25221. });
  25222. }
  25223. }
  25224. };
  25225. // This function is called only on Chrome, which does not yet support
  25226. // connection/disconnection events, but requires you to monitor
  25227. // an array for changes.
  25228. Gamepads.prototype._updateGamepadObjects = function () {
  25229. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25230. for (var i = 0; i < gamepads.length; i++) {
  25231. if (gamepads[i]) {
  25232. if (!(gamepads[i].index in this.babylonGamepads)) {
  25233. var newGamepad = this._addNewGamepad(gamepads[i]);
  25234. if (this._callbackGamepadConnected) {
  25235. this._callbackGamepadConnected(newGamepad);
  25236. }
  25237. }
  25238. else {
  25239. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25240. }
  25241. }
  25242. }
  25243. };
  25244. return Gamepads;
  25245. })();
  25246. BABYLON.Gamepads = Gamepads;
  25247. var StickValues = (function () {
  25248. function StickValues(x, y) {
  25249. this.x = x;
  25250. this.y = y;
  25251. }
  25252. return StickValues;
  25253. })();
  25254. BABYLON.StickValues = StickValues;
  25255. var Gamepad = (function () {
  25256. function Gamepad(id, index, browserGamepad) {
  25257. this.id = id;
  25258. this.index = index;
  25259. this.browserGamepad = browserGamepad;
  25260. if (this.browserGamepad.axes.length >= 2) {
  25261. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25262. }
  25263. if (this.browserGamepad.axes.length >= 4) {
  25264. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25265. }
  25266. }
  25267. Gamepad.prototype.onleftstickchanged = function (callback) {
  25268. this._onleftstickchanged = callback;
  25269. };
  25270. Gamepad.prototype.onrightstickchanged = function (callback) {
  25271. this._onrightstickchanged = callback;
  25272. };
  25273. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25274. get: function () {
  25275. return this._leftStick;
  25276. },
  25277. set: function (newValues) {
  25278. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25279. this._onleftstickchanged(newValues);
  25280. }
  25281. this._leftStick = newValues;
  25282. },
  25283. enumerable: true,
  25284. configurable: true
  25285. });
  25286. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25287. get: function () {
  25288. return this._rightStick;
  25289. },
  25290. set: function (newValues) {
  25291. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25292. this._onrightstickchanged(newValues);
  25293. }
  25294. this._rightStick = newValues;
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. Gamepad.prototype.update = function () {
  25300. if (this._leftStick) {
  25301. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25302. }
  25303. if (this._rightStick) {
  25304. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25305. }
  25306. };
  25307. return Gamepad;
  25308. })();
  25309. BABYLON.Gamepad = Gamepad;
  25310. var GenericPad = (function (_super) {
  25311. __extends(GenericPad, _super);
  25312. function GenericPad(id, index, gamepad) {
  25313. _super.call(this, id, index, gamepad);
  25314. this.id = id;
  25315. this.index = index;
  25316. this.gamepad = gamepad;
  25317. this._buttons = new Array(gamepad.buttons.length);
  25318. }
  25319. GenericPad.prototype.onbuttondown = function (callback) {
  25320. this._onbuttondown = callback;
  25321. };
  25322. GenericPad.prototype.onbuttonup = function (callback) {
  25323. this._onbuttonup = callback;
  25324. };
  25325. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25326. if (newValue !== currentValue) {
  25327. if (this._onbuttondown && newValue === 1) {
  25328. this._onbuttondown(buttonIndex);
  25329. }
  25330. if (this._onbuttonup && newValue === 0) {
  25331. this._onbuttonup(buttonIndex);
  25332. }
  25333. }
  25334. return newValue;
  25335. };
  25336. GenericPad.prototype.update = function () {
  25337. _super.prototype.update.call(this);
  25338. for (var index = 0; index < this._buttons.length; index++) {
  25339. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25340. }
  25341. };
  25342. return GenericPad;
  25343. })(Gamepad);
  25344. BABYLON.GenericPad = GenericPad;
  25345. (function (Xbox360Button) {
  25346. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25347. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25348. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25349. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25350. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25351. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25352. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25353. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25354. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25355. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25356. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25357. var Xbox360Button = BABYLON.Xbox360Button;
  25358. (function (Xbox360Dpad) {
  25359. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25360. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25361. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25362. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25363. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25364. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25365. var Xbox360Pad = (function (_super) {
  25366. __extends(Xbox360Pad, _super);
  25367. function Xbox360Pad() {
  25368. _super.apply(this, arguments);
  25369. this._leftTrigger = 0;
  25370. this._rightTrigger = 0;
  25371. this._buttonA = 0;
  25372. this._buttonB = 0;
  25373. this._buttonX = 0;
  25374. this._buttonY = 0;
  25375. this._buttonBack = 0;
  25376. this._buttonStart = 0;
  25377. this._buttonLB = 0;
  25378. this._buttonRB = 0;
  25379. this._buttonLeftStick = 0;
  25380. this._buttonRightStick = 0;
  25381. this._dPadUp = 0;
  25382. this._dPadDown = 0;
  25383. this._dPadLeft = 0;
  25384. this._dPadRight = 0;
  25385. }
  25386. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25387. this._onlefttriggerchanged = callback;
  25388. };
  25389. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25390. this._onrighttriggerchanged = callback;
  25391. };
  25392. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25393. get: function () {
  25394. return this._leftTrigger;
  25395. },
  25396. set: function (newValue) {
  25397. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25398. this._onlefttriggerchanged(newValue);
  25399. }
  25400. this._leftTrigger = newValue;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25406. get: function () {
  25407. return this._rightTrigger;
  25408. },
  25409. set: function (newValue) {
  25410. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25411. this._onrighttriggerchanged(newValue);
  25412. }
  25413. this._rightTrigger = newValue;
  25414. },
  25415. enumerable: true,
  25416. configurable: true
  25417. });
  25418. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25419. this._onbuttondown = callback;
  25420. };
  25421. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25422. this._onbuttonup = callback;
  25423. };
  25424. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25425. this._ondpaddown = callback;
  25426. };
  25427. Xbox360Pad.prototype.ondpadup = function (callback) {
  25428. this._ondpadup = callback;
  25429. };
  25430. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25431. if (newValue !== currentValue) {
  25432. if (this._onbuttondown && newValue === 1) {
  25433. this._onbuttondown(buttonType);
  25434. }
  25435. if (this._onbuttonup && newValue === 0) {
  25436. this._onbuttonup(buttonType);
  25437. }
  25438. }
  25439. return newValue;
  25440. };
  25441. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25442. if (newValue !== currentValue) {
  25443. if (this._ondpaddown && newValue === 1) {
  25444. this._ondpaddown(buttonType);
  25445. }
  25446. if (this._ondpadup && newValue === 0) {
  25447. this._ondpadup(buttonType);
  25448. }
  25449. }
  25450. return newValue;
  25451. };
  25452. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25453. get: function () {
  25454. return this._buttonA;
  25455. },
  25456. set: function (value) {
  25457. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25458. },
  25459. enumerable: true,
  25460. configurable: true
  25461. });
  25462. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25463. get: function () {
  25464. return this._buttonB;
  25465. },
  25466. set: function (value) {
  25467. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25468. },
  25469. enumerable: true,
  25470. configurable: true
  25471. });
  25472. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25473. get: function () {
  25474. return this._buttonX;
  25475. },
  25476. set: function (value) {
  25477. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25478. },
  25479. enumerable: true,
  25480. configurable: true
  25481. });
  25482. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25483. get: function () {
  25484. return this._buttonY;
  25485. },
  25486. set: function (value) {
  25487. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25488. },
  25489. enumerable: true,
  25490. configurable: true
  25491. });
  25492. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25493. get: function () {
  25494. return this._buttonStart;
  25495. },
  25496. set: function (value) {
  25497. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25498. },
  25499. enumerable: true,
  25500. configurable: true
  25501. });
  25502. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25503. get: function () {
  25504. return this._buttonBack;
  25505. },
  25506. set: function (value) {
  25507. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25508. },
  25509. enumerable: true,
  25510. configurable: true
  25511. });
  25512. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25513. get: function () {
  25514. return this._buttonLB;
  25515. },
  25516. set: function (value) {
  25517. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25518. },
  25519. enumerable: true,
  25520. configurable: true
  25521. });
  25522. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25523. get: function () {
  25524. return this._buttonRB;
  25525. },
  25526. set: function (value) {
  25527. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25528. },
  25529. enumerable: true,
  25530. configurable: true
  25531. });
  25532. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25533. get: function () {
  25534. return this._buttonLeftStick;
  25535. },
  25536. set: function (value) {
  25537. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25538. },
  25539. enumerable: true,
  25540. configurable: true
  25541. });
  25542. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25543. get: function () {
  25544. return this._buttonRightStick;
  25545. },
  25546. set: function (value) {
  25547. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25548. },
  25549. enumerable: true,
  25550. configurable: true
  25551. });
  25552. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25553. get: function () {
  25554. return this._dPadUp;
  25555. },
  25556. set: function (value) {
  25557. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25563. get: function () {
  25564. return this._dPadDown;
  25565. },
  25566. set: function (value) {
  25567. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25568. },
  25569. enumerable: true,
  25570. configurable: true
  25571. });
  25572. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25573. get: function () {
  25574. return this._dPadLeft;
  25575. },
  25576. set: function (value) {
  25577. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25578. },
  25579. enumerable: true,
  25580. configurable: true
  25581. });
  25582. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25583. get: function () {
  25584. return this._dPadRight;
  25585. },
  25586. set: function (value) {
  25587. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25588. },
  25589. enumerable: true,
  25590. configurable: true
  25591. });
  25592. Xbox360Pad.prototype.update = function () {
  25593. _super.prototype.update.call(this);
  25594. this.buttonA = this.browserGamepad.buttons[0].value;
  25595. this.buttonB = this.browserGamepad.buttons[1].value;
  25596. this.buttonX = this.browserGamepad.buttons[2].value;
  25597. this.buttonY = this.browserGamepad.buttons[3].value;
  25598. this.buttonLB = this.browserGamepad.buttons[4].value;
  25599. this.buttonRB = this.browserGamepad.buttons[5].value;
  25600. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25601. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25602. this.buttonBack = this.browserGamepad.buttons[8].value;
  25603. this.buttonStart = this.browserGamepad.buttons[9].value;
  25604. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25605. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25606. this.dPadUp = this.browserGamepad.buttons[12].value;
  25607. this.dPadDown = this.browserGamepad.buttons[13].value;
  25608. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25609. this.dPadRight = this.browserGamepad.buttons[15].value;
  25610. };
  25611. return Xbox360Pad;
  25612. })(Gamepad);
  25613. BABYLON.Xbox360Pad = Xbox360Pad;
  25614. })(BABYLON || (BABYLON = {}));
  25615. //# sourceMappingURL=babylon.gamepads.js.map
  25616. var BABYLON;
  25617. (function (BABYLON) {
  25618. // We're mainly based on the logic defined into the FreeCamera code
  25619. var GamepadCamera = (function (_super) {
  25620. __extends(GamepadCamera, _super);
  25621. function GamepadCamera(name, position, scene) {
  25622. var _this = this;
  25623. _super.call(this, name, position, scene);
  25624. this.angularSensibility = 200;
  25625. this.moveSensibility = 75;
  25626. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25627. _this._onNewGameConnected(gamepad);
  25628. });
  25629. }
  25630. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25631. // Only the first gamepad can control the camera
  25632. if (gamepad.index === 0) {
  25633. this._gamepad = gamepad;
  25634. }
  25635. };
  25636. GamepadCamera.prototype._checkInputs = function () {
  25637. if (!this._gamepad) {
  25638. return;
  25639. }
  25640. var LSValues = this._gamepad.leftStick;
  25641. var normalizedLX = LSValues.x / this.moveSensibility;
  25642. var normalizedLY = LSValues.y / this.moveSensibility;
  25643. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25644. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25645. var RSValues = this._gamepad.rightStick;
  25646. var normalizedRX = RSValues.x / this.angularSensibility;
  25647. var normalizedRY = RSValues.y / this.angularSensibility;
  25648. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25649. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25650. ;
  25651. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25652. var speed = this._computeLocalCameraSpeed() * 50.0;
  25653. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25654. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25655. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25656. };
  25657. GamepadCamera.prototype.dispose = function () {
  25658. this._gamepads.dispose();
  25659. _super.prototype.dispose.call(this);
  25660. };
  25661. return GamepadCamera;
  25662. })(BABYLON.FreeCamera);
  25663. BABYLON.GamepadCamera = GamepadCamera;
  25664. })(BABYLON || (BABYLON = {}));
  25665. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25666. var BABYLON;
  25667. (function (BABYLON) {
  25668. var LinesMesh = (function (_super) {
  25669. __extends(LinesMesh, _super);
  25670. function LinesMesh(name, scene, updatable) {
  25671. if (updatable === void 0) { updatable = false; }
  25672. _super.call(this, name, scene);
  25673. this.color = new BABYLON.Color3(1, 1, 1);
  25674. this.alpha = 1;
  25675. this._indices = new Array();
  25676. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25677. attributes: ["position"],
  25678. uniforms: ["worldViewProjection", "color"],
  25679. needAlphaBlending: true
  25680. });
  25681. }
  25682. Object.defineProperty(LinesMesh.prototype, "material", {
  25683. get: function () {
  25684. return this._colorShader;
  25685. },
  25686. enumerable: true,
  25687. configurable: true
  25688. });
  25689. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25690. get: function () {
  25691. return false;
  25692. },
  25693. enumerable: true,
  25694. configurable: true
  25695. });
  25696. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25697. get: function () {
  25698. return false;
  25699. },
  25700. enumerable: true,
  25701. configurable: true
  25702. });
  25703. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25704. var engine = this.getScene().getEngine();
  25705. var indexToBind = this._geometry.getIndexBuffer();
  25706. // VBOs
  25707. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25708. // Color
  25709. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25710. };
  25711. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25712. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25713. return;
  25714. }
  25715. var engine = this.getScene().getEngine();
  25716. // Draw order
  25717. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25718. };
  25719. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25720. return null;
  25721. };
  25722. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25723. this._colorShader.dispose();
  25724. _super.prototype.dispose.call(this, doNotRecurse);
  25725. };
  25726. return LinesMesh;
  25727. })(BABYLON.Mesh);
  25728. BABYLON.LinesMesh = LinesMesh;
  25729. })(BABYLON || (BABYLON = {}));
  25730. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25731. (function (BABYLON) {
  25732. var OutlineRenderer = (function () {
  25733. function OutlineRenderer(scene) {
  25734. this._scene = scene;
  25735. }
  25736. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25737. var _this = this;
  25738. if (useOverlay === void 0) { useOverlay = false; }
  25739. var scene = this._scene;
  25740. var engine = this._scene.getEngine();
  25741. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25742. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25743. return;
  25744. }
  25745. var mesh = subMesh.getRenderingMesh();
  25746. var material = subMesh.getMaterial();
  25747. engine.enableEffect(this._effect);
  25748. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25749. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25750. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25751. // Bones
  25752. if (mesh.useBones) {
  25753. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25754. }
  25755. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25756. // Alpha test
  25757. if (material && material.needAlphaTesting()) {
  25758. var alphaTexture = material.getAlphaTestTexture();
  25759. this._effect.setTexture("diffuseSampler", alphaTexture);
  25760. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25761. }
  25762. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25763. _this._effect.setMatrix("world", world);
  25764. });
  25765. };
  25766. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25767. var defines = [];
  25768. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25769. var mesh = subMesh.getMesh();
  25770. var material = subMesh.getMaterial();
  25771. // Alpha test
  25772. if (material && material.needAlphaTesting()) {
  25773. defines.push("#define ALPHATEST");
  25774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25775. attribs.push(BABYLON.VertexBuffer.UVKind);
  25776. defines.push("#define UV1");
  25777. }
  25778. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25779. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25780. defines.push("#define UV2");
  25781. }
  25782. }
  25783. // Bones
  25784. if (mesh.useBones) {
  25785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25787. defines.push("#define BONES");
  25788. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25789. }
  25790. // Instances
  25791. if (useInstances) {
  25792. defines.push("#define INSTANCES");
  25793. attribs.push("world0");
  25794. attribs.push("world1");
  25795. attribs.push("world2");
  25796. attribs.push("world3");
  25797. }
  25798. // Get correct effect
  25799. var join = defines.join("\n");
  25800. if (this._cachedDefines !== join) {
  25801. this._cachedDefines = join;
  25802. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25803. }
  25804. return this._effect.isReady();
  25805. };
  25806. return OutlineRenderer;
  25807. })();
  25808. BABYLON.OutlineRenderer = OutlineRenderer;
  25809. })(BABYLON || (BABYLON = {}));
  25810. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25811. (function (BABYLON) {
  25812. var MeshAssetTask = (function () {
  25813. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25814. this.name = name;
  25815. this.meshesNames = meshesNames;
  25816. this.rootUrl = rootUrl;
  25817. this.sceneFilename = sceneFilename;
  25818. this.isCompleted = false;
  25819. }
  25820. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25821. var _this = this;
  25822. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25823. _this.loadedMeshes = meshes;
  25824. _this.loadedParticleSystems = particleSystems;
  25825. _this.loadedSkeletons = skeletons;
  25826. _this.isCompleted = true;
  25827. if (_this.onSuccess) {
  25828. _this.onSuccess(_this);
  25829. }
  25830. onSuccess();
  25831. }, null, function () {
  25832. if (_this.onError) {
  25833. _this.onError(_this);
  25834. }
  25835. onError();
  25836. });
  25837. };
  25838. return MeshAssetTask;
  25839. })();
  25840. BABYLON.MeshAssetTask = MeshAssetTask;
  25841. var TextFileAssetTask = (function () {
  25842. function TextFileAssetTask(name, url) {
  25843. this.name = name;
  25844. this.url = url;
  25845. this.isCompleted = false;
  25846. }
  25847. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25848. var _this = this;
  25849. BABYLON.Tools.LoadFile(this.url, function (data) {
  25850. _this.text = data;
  25851. _this.isCompleted = true;
  25852. if (_this.onSuccess) {
  25853. _this.onSuccess(_this);
  25854. }
  25855. onSuccess();
  25856. }, null, scene.database, false, function () {
  25857. if (_this.onError) {
  25858. _this.onError(_this);
  25859. }
  25860. onError();
  25861. });
  25862. };
  25863. return TextFileAssetTask;
  25864. })();
  25865. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25866. var BinaryFileAssetTask = (function () {
  25867. function BinaryFileAssetTask(name, url) {
  25868. this.name = name;
  25869. this.url = url;
  25870. this.isCompleted = false;
  25871. }
  25872. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25873. var _this = this;
  25874. BABYLON.Tools.LoadFile(this.url, function (data) {
  25875. _this.data = data;
  25876. _this.isCompleted = true;
  25877. if (_this.onSuccess) {
  25878. _this.onSuccess(_this);
  25879. }
  25880. onSuccess();
  25881. }, null, scene.database, true, function () {
  25882. if (_this.onError) {
  25883. _this.onError(_this);
  25884. }
  25885. onError();
  25886. });
  25887. };
  25888. return BinaryFileAssetTask;
  25889. })();
  25890. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25891. var ImageAssetTask = (function () {
  25892. function ImageAssetTask(name, url) {
  25893. this.name = name;
  25894. this.url = url;
  25895. this.isCompleted = false;
  25896. }
  25897. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25898. var _this = this;
  25899. var img = new Image();
  25900. img.onload = function () {
  25901. _this.image = img;
  25902. _this.isCompleted = true;
  25903. if (_this.onSuccess) {
  25904. _this.onSuccess(_this);
  25905. }
  25906. onSuccess();
  25907. };
  25908. img.onerror = function () {
  25909. if (_this.onError) {
  25910. _this.onError(_this);
  25911. }
  25912. onError();
  25913. };
  25914. img.src = this.url;
  25915. };
  25916. return ImageAssetTask;
  25917. })();
  25918. BABYLON.ImageAssetTask = ImageAssetTask;
  25919. var TextureAssetTask = (function () {
  25920. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25922. this.name = name;
  25923. this.url = url;
  25924. this.noMipmap = noMipmap;
  25925. this.invertY = invertY;
  25926. this.samplingMode = samplingMode;
  25927. this.isCompleted = false;
  25928. }
  25929. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25930. var _this = this;
  25931. var onload = function () {
  25932. _this.isCompleted = true;
  25933. if (_this.onSuccess) {
  25934. _this.onSuccess(_this);
  25935. }
  25936. onSuccess();
  25937. };
  25938. var onerror = function () {
  25939. if (_this.onError) {
  25940. _this.onError(_this);
  25941. }
  25942. onError();
  25943. };
  25944. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25945. };
  25946. return TextureAssetTask;
  25947. })();
  25948. BABYLON.TextureAssetTask = TextureAssetTask;
  25949. var AssetsManager = (function () {
  25950. function AssetsManager(scene) {
  25951. this._tasks = new Array();
  25952. this._waitingTasksCount = 0;
  25953. this.useDefaultLoadingScreen = true;
  25954. this._scene = scene;
  25955. }
  25956. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25957. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25958. this._tasks.push(task);
  25959. return task;
  25960. };
  25961. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25962. var task = new TextFileAssetTask(taskName, url);
  25963. this._tasks.push(task);
  25964. return task;
  25965. };
  25966. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25967. var task = new BinaryFileAssetTask(taskName, url);
  25968. this._tasks.push(task);
  25969. return task;
  25970. };
  25971. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25972. var task = new ImageAssetTask(taskName, url);
  25973. this._tasks.push(task);
  25974. return task;
  25975. };
  25976. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25978. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25979. this._tasks.push(task);
  25980. return task;
  25981. };
  25982. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25983. this._waitingTasksCount--;
  25984. if (this._waitingTasksCount === 0) {
  25985. if (this.onFinish) {
  25986. this.onFinish(this._tasks);
  25987. }
  25988. this._scene.getEngine().hideLoadingUI();
  25989. }
  25990. };
  25991. AssetsManager.prototype._runTask = function (task) {
  25992. var _this = this;
  25993. task.run(this._scene, function () {
  25994. if (_this.onTaskSuccess) {
  25995. _this.onTaskSuccess(task);
  25996. }
  25997. _this._decreaseWaitingTasksCount();
  25998. }, function () {
  25999. if (_this.onTaskError) {
  26000. _this.onTaskError(task);
  26001. }
  26002. _this._decreaseWaitingTasksCount();
  26003. });
  26004. };
  26005. AssetsManager.prototype.reset = function () {
  26006. this._tasks = new Array();
  26007. return this;
  26008. };
  26009. AssetsManager.prototype.load = function () {
  26010. this._waitingTasksCount = this._tasks.length;
  26011. if (this._waitingTasksCount === 0) {
  26012. if (this.onFinish) {
  26013. this.onFinish(this._tasks);
  26014. }
  26015. return this;
  26016. }
  26017. if (this.useDefaultLoadingScreen) {
  26018. this._scene.getEngine().displayLoadingUI();
  26019. }
  26020. for (var index = 0; index < this._tasks.length; index++) {
  26021. var task = this._tasks[index];
  26022. this._runTask(task);
  26023. }
  26024. return this;
  26025. };
  26026. return AssetsManager;
  26027. })();
  26028. BABYLON.AssetsManager = AssetsManager;
  26029. })(BABYLON || (BABYLON = {}));
  26030. //# sourceMappingURL=babylon.assetsManager.js.map
  26031. var BABYLON;
  26032. (function (BABYLON) {
  26033. var VRDeviceOrientationCamera = (function (_super) {
  26034. __extends(VRDeviceOrientationCamera, _super);
  26035. function VRDeviceOrientationCamera(name, position, scene) {
  26036. _super.call(this, name, position, scene);
  26037. this._alpha = 0;
  26038. this._beta = 0;
  26039. this._gamma = 0;
  26040. }
  26041. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26042. this._alpha = +evt.alpha | 0;
  26043. this._beta = +evt.beta | 0;
  26044. this._gamma = +evt.gamma | 0;
  26045. if (this._gamma < 0) {
  26046. this._gamma = 90 + this._gamma;
  26047. }
  26048. else {
  26049. // Incline it in the correct angle.
  26050. this._gamma = 270 - this._gamma;
  26051. }
  26052. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26053. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26054. this.rotation.z = this._beta / 180.0 * Math.PI;
  26055. };
  26056. return VRDeviceOrientationCamera;
  26057. })(BABYLON.OculusCamera);
  26058. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26059. })(BABYLON || (BABYLON = {}));
  26060. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26061. var BABYLON;
  26062. (function (BABYLON) {
  26063. var WebVRCamera = (function (_super) {
  26064. __extends(WebVRCamera, _super);
  26065. function WebVRCamera(name, position, scene) {
  26066. _super.call(this, name, position, scene);
  26067. this._hmdDevice = null;
  26068. this._sensorDevice = null;
  26069. this._cacheState = null;
  26070. this._cacheQuaternion = new BABYLON.Quaternion();
  26071. this._cacheRotation = BABYLON.Vector3.Zero();
  26072. this._vrEnabled = false;
  26073. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26074. }
  26075. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26076. var size = devices.length;
  26077. var i = 0;
  26078. // Reset devices.
  26079. this._sensorDevice = null;
  26080. this._hmdDevice = null;
  26081. while (i < size && this._hmdDevice === null) {
  26082. if (devices[i] instanceof HMDVRDevice) {
  26083. this._hmdDevice = devices[i];
  26084. }
  26085. i++;
  26086. }
  26087. i = 0;
  26088. while (i < size && this._sensorDevice === null) {
  26089. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26090. this._sensorDevice = devices[i];
  26091. }
  26092. i++;
  26093. }
  26094. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26095. };
  26096. WebVRCamera.prototype._update = function () {
  26097. if (this._vrEnabled) {
  26098. this._cacheState = this._sensorDevice.getState();
  26099. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26100. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26101. this.rotation.x = -this._cacheRotation.z;
  26102. this.rotation.y = -this._cacheRotation.y;
  26103. this.rotation.z = this._cacheRotation.x;
  26104. }
  26105. _super.prototype._update.call(this);
  26106. };
  26107. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26108. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26109. if (navigator.getVRDevices) {
  26110. navigator.getVRDevices().then(this._getWebVRDevices);
  26111. }
  26112. else if (navigator.mozGetVRDevices) {
  26113. navigator.mozGetVRDevices(this._getWebVRDevices);
  26114. }
  26115. };
  26116. WebVRCamera.prototype.detachControl = function (element) {
  26117. _super.prototype.detachControl.call(this, element);
  26118. this._vrEnabled = false;
  26119. };
  26120. return WebVRCamera;
  26121. })(BABYLON.OculusCamera);
  26122. BABYLON.WebVRCamera = WebVRCamera;
  26123. })(BABYLON || (BABYLON = {}));
  26124. //# sourceMappingURL=babylon.webVRCamera.js.map
  26125. var BABYLON;
  26126. (function (BABYLON) {
  26127. // Standard optimizations
  26128. var SceneOptimization = (function () {
  26129. function SceneOptimization(priority) {
  26130. if (priority === void 0) { priority = 0; }
  26131. this.priority = priority;
  26132. this.apply = function (scene) {
  26133. return true; // Return true if everything that can be done was applied
  26134. };
  26135. }
  26136. return SceneOptimization;
  26137. })();
  26138. BABYLON.SceneOptimization = SceneOptimization;
  26139. var TextureOptimization = (function (_super) {
  26140. __extends(TextureOptimization, _super);
  26141. function TextureOptimization(priority, maximumSize) {
  26142. var _this = this;
  26143. if (priority === void 0) { priority = 0; }
  26144. if (maximumSize === void 0) { maximumSize = 1024; }
  26145. _super.call(this, priority);
  26146. this.priority = priority;
  26147. this.maximumSize = maximumSize;
  26148. this.apply = function (scene) {
  26149. var allDone = true;
  26150. for (var index = 0; index < scene.textures.length; index++) {
  26151. var texture = scene.textures[index];
  26152. if (!texture.canRescale) {
  26153. continue;
  26154. }
  26155. var currentSize = texture.getSize();
  26156. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26157. if (maxDimension > _this.maximumSize) {
  26158. texture.scale(0.5);
  26159. allDone = false;
  26160. }
  26161. }
  26162. return allDone;
  26163. };
  26164. }
  26165. return TextureOptimization;
  26166. })(SceneOptimization);
  26167. BABYLON.TextureOptimization = TextureOptimization;
  26168. var HardwareScalingOptimization = (function (_super) {
  26169. __extends(HardwareScalingOptimization, _super);
  26170. function HardwareScalingOptimization(priority, maximumScale) {
  26171. var _this = this;
  26172. if (priority === void 0) { priority = 0; }
  26173. if (maximumScale === void 0) { maximumScale = 2; }
  26174. _super.call(this, priority);
  26175. this.priority = priority;
  26176. this.maximumScale = maximumScale;
  26177. this._currentScale = 1;
  26178. this.apply = function (scene) {
  26179. _this._currentScale++;
  26180. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26181. return _this._currentScale >= _this.maximumScale;
  26182. };
  26183. }
  26184. return HardwareScalingOptimization;
  26185. })(SceneOptimization);
  26186. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26187. var ShadowsOptimization = (function (_super) {
  26188. __extends(ShadowsOptimization, _super);
  26189. function ShadowsOptimization() {
  26190. _super.apply(this, arguments);
  26191. this.apply = function (scene) {
  26192. scene.shadowsEnabled = false;
  26193. return true;
  26194. };
  26195. }
  26196. return ShadowsOptimization;
  26197. })(SceneOptimization);
  26198. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26199. var PostProcessesOptimization = (function (_super) {
  26200. __extends(PostProcessesOptimization, _super);
  26201. function PostProcessesOptimization() {
  26202. _super.apply(this, arguments);
  26203. this.apply = function (scene) {
  26204. scene.postProcessesEnabled = false;
  26205. return true;
  26206. };
  26207. }
  26208. return PostProcessesOptimization;
  26209. })(SceneOptimization);
  26210. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26211. var LensFlaresOptimization = (function (_super) {
  26212. __extends(LensFlaresOptimization, _super);
  26213. function LensFlaresOptimization() {
  26214. _super.apply(this, arguments);
  26215. this.apply = function (scene) {
  26216. scene.lensFlaresEnabled = false;
  26217. return true;
  26218. };
  26219. }
  26220. return LensFlaresOptimization;
  26221. })(SceneOptimization);
  26222. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26223. var ParticlesOptimization = (function (_super) {
  26224. __extends(ParticlesOptimization, _super);
  26225. function ParticlesOptimization() {
  26226. _super.apply(this, arguments);
  26227. this.apply = function (scene) {
  26228. scene.particlesEnabled = false;
  26229. return true;
  26230. };
  26231. }
  26232. return ParticlesOptimization;
  26233. })(SceneOptimization);
  26234. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26235. var RenderTargetsOptimization = (function (_super) {
  26236. __extends(RenderTargetsOptimization, _super);
  26237. function RenderTargetsOptimization() {
  26238. _super.apply(this, arguments);
  26239. this.apply = function (scene) {
  26240. scene.renderTargetsEnabled = false;
  26241. return true;
  26242. };
  26243. }
  26244. return RenderTargetsOptimization;
  26245. })(SceneOptimization);
  26246. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26247. var MergeMeshesOptimization = (function (_super) {
  26248. __extends(MergeMeshesOptimization, _super);
  26249. function MergeMeshesOptimization() {
  26250. var _this = this;
  26251. _super.apply(this, arguments);
  26252. this._canBeMerged = function (abstractMesh) {
  26253. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26254. return false;
  26255. }
  26256. var mesh = abstractMesh;
  26257. if (!mesh.isVisible || !mesh.isEnabled()) {
  26258. return false;
  26259. }
  26260. if (mesh.instances.length > 0) {
  26261. return false;
  26262. }
  26263. if (mesh.skeleton || mesh.hasLODLevels) {
  26264. return false;
  26265. }
  26266. return true;
  26267. };
  26268. this.apply = function (scene) {
  26269. var globalPool = scene.meshes.slice(0);
  26270. var globalLength = globalPool.length;
  26271. for (var index = 0; index < globalLength; index++) {
  26272. var currentPool = new Array();
  26273. var current = globalPool[index];
  26274. // Checks
  26275. if (!_this._canBeMerged(current)) {
  26276. continue;
  26277. }
  26278. currentPool.push(current);
  26279. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26280. var otherMesh = globalPool[subIndex];
  26281. if (!_this._canBeMerged(otherMesh)) {
  26282. continue;
  26283. }
  26284. if (otherMesh.material !== current.material) {
  26285. continue;
  26286. }
  26287. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26288. continue;
  26289. }
  26290. currentPool.push(otherMesh);
  26291. globalLength--;
  26292. globalPool.splice(subIndex, 1);
  26293. subIndex--;
  26294. }
  26295. if (currentPool.length < 2) {
  26296. continue;
  26297. }
  26298. // Merge meshes
  26299. BABYLON.Mesh.MergeMeshes(currentPool);
  26300. }
  26301. return true;
  26302. };
  26303. }
  26304. return MergeMeshesOptimization;
  26305. })(SceneOptimization);
  26306. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26307. // Options
  26308. var SceneOptimizerOptions = (function () {
  26309. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26310. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26311. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26312. this.targetFrameRate = targetFrameRate;
  26313. this.trackerDuration = trackerDuration;
  26314. this.optimizations = new Array();
  26315. }
  26316. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26317. var result = new SceneOptimizerOptions(targetFrameRate);
  26318. var priority = 0;
  26319. result.optimizations.push(new MergeMeshesOptimization(priority));
  26320. result.optimizations.push(new ShadowsOptimization(priority));
  26321. result.optimizations.push(new LensFlaresOptimization(priority));
  26322. // Next priority
  26323. priority++;
  26324. result.optimizations.push(new PostProcessesOptimization(priority));
  26325. result.optimizations.push(new ParticlesOptimization(priority));
  26326. // Next priority
  26327. priority++;
  26328. result.optimizations.push(new TextureOptimization(priority, 1024));
  26329. return result;
  26330. };
  26331. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26332. var result = new SceneOptimizerOptions(targetFrameRate);
  26333. var priority = 0;
  26334. result.optimizations.push(new MergeMeshesOptimization(priority));
  26335. result.optimizations.push(new ShadowsOptimization(priority));
  26336. result.optimizations.push(new LensFlaresOptimization(priority));
  26337. // Next priority
  26338. priority++;
  26339. result.optimizations.push(new PostProcessesOptimization(priority));
  26340. result.optimizations.push(new ParticlesOptimization(priority));
  26341. // Next priority
  26342. priority++;
  26343. result.optimizations.push(new TextureOptimization(priority, 512));
  26344. // Next priority
  26345. priority++;
  26346. result.optimizations.push(new RenderTargetsOptimization(priority));
  26347. // Next priority
  26348. priority++;
  26349. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26350. return result;
  26351. };
  26352. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26353. var result = new SceneOptimizerOptions(targetFrameRate);
  26354. var priority = 0;
  26355. result.optimizations.push(new MergeMeshesOptimization(priority));
  26356. result.optimizations.push(new ShadowsOptimization(priority));
  26357. result.optimizations.push(new LensFlaresOptimization(priority));
  26358. // Next priority
  26359. priority++;
  26360. result.optimizations.push(new PostProcessesOptimization(priority));
  26361. result.optimizations.push(new ParticlesOptimization(priority));
  26362. // Next priority
  26363. priority++;
  26364. result.optimizations.push(new TextureOptimization(priority, 256));
  26365. // Next priority
  26366. priority++;
  26367. result.optimizations.push(new RenderTargetsOptimization(priority));
  26368. // Next priority
  26369. priority++;
  26370. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26371. return result;
  26372. };
  26373. return SceneOptimizerOptions;
  26374. })();
  26375. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26376. // Scene optimizer tool
  26377. var SceneOptimizer = (function () {
  26378. function SceneOptimizer() {
  26379. }
  26380. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26381. // TODO: add an epsilon
  26382. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26383. if (onSuccess) {
  26384. onSuccess();
  26385. }
  26386. return;
  26387. }
  26388. // Apply current level of optimizations
  26389. var allDone = true;
  26390. var noOptimizationApplied = true;
  26391. for (var index = 0; index < options.optimizations.length; index++) {
  26392. var optimization = options.optimizations[index];
  26393. if (optimization.priority === currentPriorityLevel) {
  26394. noOptimizationApplied = false;
  26395. allDone = allDone && optimization.apply(scene);
  26396. }
  26397. }
  26398. // If no optimization was applied, this is a failure :(
  26399. if (noOptimizationApplied) {
  26400. if (onFailure) {
  26401. onFailure();
  26402. }
  26403. return;
  26404. }
  26405. // If all optimizations were done, move to next level
  26406. if (allDone) {
  26407. currentPriorityLevel++;
  26408. }
  26409. // Let's the system running for a specific amount of time before checking FPS
  26410. scene.executeWhenReady(function () {
  26411. setTimeout(function () {
  26412. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26413. }, options.trackerDuration);
  26414. });
  26415. };
  26416. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26417. if (!options) {
  26418. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26419. }
  26420. // Let's the system running for a specific amount of time before checking FPS
  26421. scene.executeWhenReady(function () {
  26422. setTimeout(function () {
  26423. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26424. }, options.trackerDuration);
  26425. });
  26426. };
  26427. return SceneOptimizer;
  26428. })();
  26429. BABYLON.SceneOptimizer = SceneOptimizer;
  26430. })(BABYLON || (BABYLON = {}));
  26431. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26432. (function (BABYLON) {
  26433. var Internals;
  26434. (function (Internals) {
  26435. var MeshLODLevel = (function () {
  26436. function MeshLODLevel(distance, mesh) {
  26437. this.distance = distance;
  26438. this.mesh = mesh;
  26439. }
  26440. return MeshLODLevel;
  26441. })();
  26442. Internals.MeshLODLevel = MeshLODLevel;
  26443. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26444. })(BABYLON || (BABYLON = {}));
  26445. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26446. (function (BABYLON) {
  26447. var AudioEngine = (function () {
  26448. function AudioEngine() {
  26449. this.audioContext = null;
  26450. this.canUseWebAudio = false;
  26451. this.WarnedWebAudioUnsupported = false;
  26452. try {
  26453. if (typeof AudioContext !== 'undefined') {
  26454. this.audioContext = new AudioContext();
  26455. this.canUseWebAudio = true;
  26456. }
  26457. else if (typeof webkitAudioContext !== 'undefined') {
  26458. this.audioContext = new webkitAudioContext();
  26459. this.canUseWebAudio = true;
  26460. }
  26461. }
  26462. catch (e) {
  26463. this.canUseWebAudio = false;
  26464. BABYLON.Tools.Error("Web Audio: " + e.message);
  26465. }
  26466. // create a global volume gain node
  26467. if (this.canUseWebAudio) {
  26468. this.masterGain = this.audioContext.createGain();
  26469. this.masterGain.gain.value = 1;
  26470. this.masterGain.connect(this.audioContext.destination);
  26471. }
  26472. }
  26473. AudioEngine.prototype.dispose = function () {
  26474. if (this.canUseWebAudio) {
  26475. if (this._connectedAnalyser) {
  26476. this._connectedAnalyser.stopDebugCanvas();
  26477. this._connectedAnalyser.dispose();
  26478. this.masterGain.disconnect();
  26479. this.masterGain.connect(this.audioContext.destination);
  26480. this._connectedAnalyser = null;
  26481. }
  26482. this.masterGain.gain.value = 1;
  26483. }
  26484. this.WarnedWebAudioUnsupported = false;
  26485. };
  26486. AudioEngine.prototype.getGlobalVolume = function () {
  26487. if (this.canUseWebAudio) {
  26488. return this.masterGain.gain.value;
  26489. }
  26490. else {
  26491. return -1;
  26492. }
  26493. };
  26494. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26495. if (this.canUseWebAudio) {
  26496. this.masterGain.gain.value = newVolume;
  26497. }
  26498. };
  26499. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26500. if (this._connectedAnalyser) {
  26501. this._connectedAnalyser.stopDebugCanvas();
  26502. }
  26503. this._connectedAnalyser = analyser;
  26504. if (this.canUseWebAudio) {
  26505. this.masterGain.disconnect();
  26506. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26507. }
  26508. };
  26509. return AudioEngine;
  26510. })();
  26511. BABYLON.AudioEngine = AudioEngine;
  26512. })(BABYLON || (BABYLON = {}));
  26513. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26514. (function (BABYLON) {
  26515. var Sound = (function () {
  26516. /**
  26517. * Create a sound and attach it to a scene
  26518. * @param name Name of your sound
  26519. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26520. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26521. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26522. */
  26523. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26524. var _this = this;
  26525. this.autoplay = false;
  26526. this.loop = false;
  26527. this.useCustomAttenuation = false;
  26528. this.spatialSound = false;
  26529. this.refDistance = 1;
  26530. this.rolloffFactor = 1;
  26531. this.maxDistance = 100;
  26532. this.distanceModel = "linear";
  26533. this.panningModel = "HRTF";
  26534. this._playbackRate = 1;
  26535. this._startTime = 0;
  26536. this._startOffset = 0;
  26537. this._position = BABYLON.Vector3.Zero();
  26538. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26539. this._volume = 1;
  26540. this._isLoaded = false;
  26541. this._isReadyToPlay = false;
  26542. this.isPlaying = false;
  26543. this.isPaused = false;
  26544. this._isDirectional = false;
  26545. // Used if you'd like to create a directional sound.
  26546. // If not set, the sound will be omnidirectional
  26547. this._coneInnerAngle = 360;
  26548. this._coneOuterAngle = 360;
  26549. this._coneOuterGain = 0;
  26550. this.name = name;
  26551. this._scene = scene;
  26552. this._readyToPlayCallback = readyToPlayCallback;
  26553. // Default custom attenuation function is a linear attenuation
  26554. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26555. if (currentDistance < maxDistance) {
  26556. return currentVolume * (1 - currentDistance / maxDistance);
  26557. }
  26558. else {
  26559. return 0;
  26560. }
  26561. };
  26562. if (options) {
  26563. this.autoplay = options.autoplay || false;
  26564. this.loop = options.loop || false;
  26565. // if volume === 0, we need another way to check this option
  26566. if (options.volume !== undefined) {
  26567. this._volume = options.volume;
  26568. }
  26569. this.spatialSound = options.spatialSound || false;
  26570. this.maxDistance = options.maxDistance || 100;
  26571. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26572. this.rolloffFactor = options.rolloffFactor || 1;
  26573. this.refDistance = options.refDistance || 1;
  26574. this.distanceModel = options.distanceModel || "linear";
  26575. this.panningModel = options.panningModel || "HRTF";
  26576. this._playbackRate = options.playbackRate || 1;
  26577. }
  26578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26579. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26580. this._soundGain.gain.value = this._volume;
  26581. this._inputAudioNode = this._soundGain;
  26582. this._ouputAudioNode = this._soundGain;
  26583. if (this.spatialSound) {
  26584. this._createSpatialParameters();
  26585. }
  26586. this._scene.mainSoundTrack.AddSound(this);
  26587. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26588. if (urlOrArrayBuffer) {
  26589. // If it's an URL
  26590. if (typeof (urlOrArrayBuffer) === "string") {
  26591. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26592. _this._soundLoaded(data);
  26593. }, null, null, true);
  26594. }
  26595. else {
  26596. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26597. this._soundLoaded(urlOrArrayBuffer);
  26598. }
  26599. else {
  26600. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26601. }
  26602. }
  26603. }
  26604. }
  26605. else {
  26606. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26607. this._scene.mainSoundTrack.AddSound(this);
  26608. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26609. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26610. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26611. }
  26612. }
  26613. }
  26614. Sound.prototype.dispose = function () {
  26615. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26616. if (this.isPlaying) {
  26617. this.stop();
  26618. }
  26619. this._isReadyToPlay = false;
  26620. if (this.soundTrackId === -1) {
  26621. this._scene.mainSoundTrack.RemoveSound(this);
  26622. }
  26623. else {
  26624. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26625. }
  26626. if (this._soundGain) {
  26627. this._soundGain.disconnect();
  26628. this._soundGain = null;
  26629. }
  26630. if (this._soundPanner) {
  26631. this._soundPanner.disconnect();
  26632. this._soundPanner = null;
  26633. }
  26634. if (this._soundSource) {
  26635. this._soundSource.disconnect();
  26636. this._soundSource = null;
  26637. }
  26638. this._audioBuffer = null;
  26639. if (this._connectedMesh) {
  26640. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26641. this._connectedMesh = null;
  26642. }
  26643. }
  26644. };
  26645. Sound.prototype._soundLoaded = function (audioData) {
  26646. var _this = this;
  26647. this._isLoaded = true;
  26648. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26649. _this._audioBuffer = buffer;
  26650. _this._isReadyToPlay = true;
  26651. if (_this.autoplay) {
  26652. _this.play();
  26653. }
  26654. if (_this._readyToPlayCallback) {
  26655. _this._readyToPlayCallback();
  26656. }
  26657. }, function (error) {
  26658. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26659. });
  26660. };
  26661. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26663. this._audioBuffer = audioBuffer;
  26664. this._isReadyToPlay = true;
  26665. }
  26666. };
  26667. Sound.prototype.updateOptions = function (options) {
  26668. if (options) {
  26669. this.loop = options.loop || this.loop;
  26670. this.maxDistance = options.maxDistance || this.maxDistance;
  26671. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26672. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26673. this.refDistance = options.refDistance || this.refDistance;
  26674. this.distanceModel = options.distanceModel || this.distanceModel;
  26675. this.panningModel = options.panningModel || this.panningModel;
  26676. this._playbackRate = options.playbackRate || this._playbackRate;
  26677. }
  26678. };
  26679. Sound.prototype._createSpatialParameters = function () {
  26680. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26681. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26682. if (this.useCustomAttenuation) {
  26683. // Tricks to disable in a way embedded Web Audio attenuation
  26684. this._soundPanner.distanceModel = "linear";
  26685. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26686. this._soundPanner.refDistance = 1;
  26687. this._soundPanner.rolloffFactor = 1;
  26688. this._soundPanner.panningModel = "HRTF";
  26689. }
  26690. else {
  26691. this._soundPanner.distanceModel = this.distanceModel;
  26692. this._soundPanner.maxDistance = this.maxDistance;
  26693. this._soundPanner.refDistance = this.refDistance;
  26694. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26695. this._soundPanner.panningModel = this.panningModel;
  26696. }
  26697. this._soundPanner.connect(this._ouputAudioNode);
  26698. this._inputAudioNode = this._soundPanner;
  26699. }
  26700. };
  26701. Sound.prototype.switchPanningModelToHRTF = function () {
  26702. this._switchPanningModel("HRTF");
  26703. };
  26704. Sound.prototype.switchPanningModelToEqualPower = function () {
  26705. this._switchPanningModel("equalpower");
  26706. };
  26707. Sound.prototype._switchPanningModel = function (newModel) {
  26708. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26709. this._soundPanner.panningModel = newModel;
  26710. }
  26711. };
  26712. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26713. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26714. this._ouputAudioNode.disconnect();
  26715. this._ouputAudioNode.connect(soundTrackAudioNode);
  26716. }
  26717. };
  26718. /**
  26719. * Transform this sound into a directional source
  26720. * @param coneInnerAngle Size of the inner cone in degree
  26721. * @param coneOuterAngle Size of the outer cone in degree
  26722. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26723. */
  26724. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26725. if (coneOuterAngle < coneInnerAngle) {
  26726. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26727. return;
  26728. }
  26729. this._coneInnerAngle = coneInnerAngle;
  26730. this._coneOuterAngle = coneOuterAngle;
  26731. this._coneOuterGain = coneOuterGain;
  26732. this._isDirectional = true;
  26733. if (this.isPlaying && this.loop) {
  26734. this.stop();
  26735. this.play();
  26736. }
  26737. };
  26738. Sound.prototype.setPosition = function (newPosition) {
  26739. this._position = newPosition;
  26740. if (this.isPlaying && this.spatialSound) {
  26741. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26742. }
  26743. };
  26744. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26745. this._localDirection = newLocalDirection;
  26746. if (this._connectedMesh && this.isPlaying) {
  26747. this._updateDirection();
  26748. }
  26749. };
  26750. Sound.prototype._updateDirection = function () {
  26751. var mat = this._connectedMesh.getWorldMatrix();
  26752. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26753. direction.normalize();
  26754. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26755. };
  26756. Sound.prototype.updateDistanceFromListener = function () {
  26757. if (this._connectedMesh && this.useCustomAttenuation) {
  26758. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26759. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26760. }
  26761. };
  26762. Sound.prototype.setAttenuationFunction = function (callback) {
  26763. this._customAttenuationFunction = callback;
  26764. };
  26765. /**
  26766. * Play the sound
  26767. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26768. */
  26769. Sound.prototype.play = function (time) {
  26770. var _this = this;
  26771. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26772. try {
  26773. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26774. if (!this._soundSource) {
  26775. if (this.spatialSound) {
  26776. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26777. if (this._isDirectional) {
  26778. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26779. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26780. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26781. if (this._connectedMesh) {
  26782. this._updateDirection();
  26783. }
  26784. else {
  26785. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26786. }
  26787. }
  26788. }
  26789. }
  26790. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26791. this._soundSource.buffer = this._audioBuffer;
  26792. this._soundSource.connect(this._inputAudioNode);
  26793. this._soundSource.loop = this.loop;
  26794. this._soundSource.playbackRate.value = this._playbackRate;
  26795. this._startTime = startTime;
  26796. this._soundSource.onended = function () {
  26797. _this._onended();
  26798. };
  26799. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26800. this.isPlaying = true;
  26801. this.isPaused = false;
  26802. }
  26803. catch (ex) {
  26804. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26805. }
  26806. }
  26807. };
  26808. Sound.prototype._onended = function () {
  26809. this.isPlaying = false;
  26810. if (this.onended) {
  26811. this.onended();
  26812. }
  26813. };
  26814. /**
  26815. * Stop the sound
  26816. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26817. */
  26818. Sound.prototype.stop = function (time) {
  26819. if (this.isPlaying) {
  26820. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26821. this._soundSource.stop(stopTime);
  26822. this.isPlaying = false;
  26823. }
  26824. };
  26825. Sound.prototype.pause = function () {
  26826. if (this.isPlaying) {
  26827. this.stop(0);
  26828. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26829. this.isPaused = true;
  26830. }
  26831. };
  26832. Sound.prototype.setVolume = function (newVolume, time) {
  26833. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26834. if (time) {
  26835. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26836. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26837. }
  26838. else {
  26839. this._soundGain.gain.value = newVolume;
  26840. }
  26841. }
  26842. this._volume = newVolume;
  26843. };
  26844. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26845. this._playbackRate = newPlaybackRate;
  26846. if (this.isPlaying) {
  26847. this._soundSource.playbackRate.value = this._playbackRate;
  26848. }
  26849. };
  26850. Sound.prototype.getVolume = function () {
  26851. return this._volume;
  26852. };
  26853. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26854. var _this = this;
  26855. this._connectedMesh = meshToConnectTo;
  26856. if (!this.spatialSound) {
  26857. this._createSpatialParameters();
  26858. this.spatialSound = true;
  26859. if (this.isPlaying && this.loop) {
  26860. this.stop();
  26861. this.play();
  26862. }
  26863. }
  26864. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26865. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26866. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26867. };
  26868. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26869. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26870. if (this._isDirectional && this.isPlaying) {
  26871. this._updateDirection();
  26872. }
  26873. };
  26874. return Sound;
  26875. })();
  26876. BABYLON.Sound = Sound;
  26877. })(BABYLON || (BABYLON = {}));
  26878. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26879. (function (BABYLON) {
  26880. var SoundTrack = (function () {
  26881. function SoundTrack(scene, options) {
  26882. this.id = -1;
  26883. this._isMainTrack = false;
  26884. this._scene = scene;
  26885. this._audioEngine = BABYLON.Engine.audioEngine;
  26886. this.soundCollection = new Array();
  26887. if (this._audioEngine.canUseWebAudio) {
  26888. this._trackGain = this._audioEngine.audioContext.createGain();
  26889. this._trackGain.connect(this._audioEngine.masterGain);
  26890. if (options) {
  26891. if (options.volume) {
  26892. this._trackGain.gain.value = options.volume;
  26893. }
  26894. if (options.mainTrack) {
  26895. this._isMainTrack = options.mainTrack;
  26896. }
  26897. }
  26898. }
  26899. if (!this._isMainTrack) {
  26900. this._scene.soundTracks.push(this);
  26901. this.id = this._scene.soundTracks.length - 1;
  26902. }
  26903. }
  26904. SoundTrack.prototype.dispose = function () {
  26905. if (this._audioEngine.canUseWebAudio) {
  26906. if (this._connectedAnalyser) {
  26907. this._connectedAnalyser.stopDebugCanvas();
  26908. }
  26909. while (this.soundCollection.length) {
  26910. this.soundCollection[0].dispose();
  26911. }
  26912. this._trackGain.disconnect();
  26913. this._trackGain = null;
  26914. }
  26915. };
  26916. SoundTrack.prototype.AddSound = function (sound) {
  26917. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26918. sound.connectToSoundTrackAudioNode(this._trackGain);
  26919. }
  26920. if (sound.soundTrackId) {
  26921. if (sound.soundTrackId === -1) {
  26922. this._scene.mainSoundTrack.RemoveSound(sound);
  26923. }
  26924. else {
  26925. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26926. }
  26927. }
  26928. this.soundCollection.push(sound);
  26929. sound.soundTrackId = this.id;
  26930. };
  26931. SoundTrack.prototype.RemoveSound = function (sound) {
  26932. var index = this.soundCollection.indexOf(sound);
  26933. if (index !== -1) {
  26934. this.soundCollection.splice(index, 1);
  26935. }
  26936. };
  26937. SoundTrack.prototype.setVolume = function (newVolume) {
  26938. if (this._audioEngine.canUseWebAudio) {
  26939. this._trackGain.gain.value = newVolume;
  26940. }
  26941. };
  26942. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26944. for (var i = 0; i < this.soundCollection.length; i++) {
  26945. this.soundCollection[i].switchPanningModelToHRTF();
  26946. }
  26947. }
  26948. };
  26949. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26950. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26951. for (var i = 0; i < this.soundCollection.length; i++) {
  26952. this.soundCollection[i].switchPanningModelToEqualPower();
  26953. }
  26954. }
  26955. };
  26956. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26957. if (this._connectedAnalyser) {
  26958. this._connectedAnalyser.stopDebugCanvas();
  26959. }
  26960. this._connectedAnalyser = analyser;
  26961. if (this._audioEngine.canUseWebAudio) {
  26962. this._trackGain.disconnect();
  26963. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26964. }
  26965. };
  26966. return SoundTrack;
  26967. })();
  26968. BABYLON.SoundTrack = SoundTrack;
  26969. })(BABYLON || (BABYLON = {}));
  26970. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26971. (function (BABYLON) {
  26972. var DebugLayer = (function () {
  26973. function DebugLayer(scene) {
  26974. var _this = this;
  26975. this._transformationMatrix = BABYLON.Matrix.Identity();
  26976. this._enabled = false;
  26977. this._labelsEnabled = false;
  26978. this._displayStatistics = true;
  26979. this._displayTree = false;
  26980. this._displayLogs = false;
  26981. this._identityMatrix = BABYLON.Matrix.Identity();
  26982. this.axisRatio = 0.02;
  26983. this.accentColor = "orange";
  26984. this._scene = scene;
  26985. this._syncPositions = function () {
  26986. var engine = _this._scene.getEngine();
  26987. var canvasRect = engine.getRenderingCanvasClientRect();
  26988. if (_this._showUI) {
  26989. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26990. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26991. _this._statsDiv.style.width = "400px";
  26992. _this._statsDiv.style.height = "auto";
  26993. _this._statsSubsetDiv.style.maxHeight = "240px";
  26994. _this._optionsDiv.style.left = "0px";
  26995. _this._optionsDiv.style.top = "10px";
  26996. _this._optionsDiv.style.width = "200px";
  26997. _this._optionsDiv.style.height = "auto";
  26998. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26999. _this._logDiv.style.left = "0px";
  27000. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27001. _this._logDiv.style.width = "600px";
  27002. _this._logDiv.style.height = "160px";
  27003. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27004. _this._treeDiv.style.top = "10px";
  27005. _this._treeDiv.style.width = "300px";
  27006. _this._treeDiv.style.height = "auto";
  27007. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27008. }
  27009. _this._globalDiv.style.left = canvasRect.left + "px";
  27010. _this._globalDiv.style.top = canvasRect.top + "px";
  27011. _this._drawingCanvas.style.left = "0px";
  27012. _this._drawingCanvas.style.top = "0px";
  27013. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27014. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27015. var devicePixelRatio = window.devicePixelRatio || 1;
  27016. var context = _this._drawingContext;
  27017. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27018. _this._ratio = devicePixelRatio / backingStoreRatio;
  27019. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27020. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27021. };
  27022. this._onCanvasClick = function (evt) {
  27023. _this._clickPosition = {
  27024. x: evt.clientX * _this._ratio,
  27025. y: evt.clientY * _this._ratio
  27026. };
  27027. };
  27028. this._syncUI = function () {
  27029. if (_this._showUI) {
  27030. if (_this._displayStatistics) {
  27031. _this._displayStats();
  27032. _this._statsDiv.style.display = "";
  27033. }
  27034. else {
  27035. _this._statsDiv.style.display = "none";
  27036. }
  27037. if (_this._displayLogs) {
  27038. _this._logDiv.style.display = "";
  27039. }
  27040. else {
  27041. _this._logDiv.style.display = "none";
  27042. }
  27043. if (_this._displayTree) {
  27044. _this._treeDiv.style.display = "";
  27045. if (_this._needToRefreshMeshesTree) {
  27046. _this._needToRefreshMeshesTree = false;
  27047. _this._refreshMeshesTreeContent();
  27048. }
  27049. }
  27050. else {
  27051. _this._treeDiv.style.display = "none";
  27052. }
  27053. }
  27054. };
  27055. this._syncData = function () {
  27056. if (_this._labelsEnabled || !_this._showUI) {
  27057. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27058. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27059. var engine = _this._scene.getEngine();
  27060. var viewport = _this._camera.viewport;
  27061. var globalViewport = viewport.toGlobal(engine);
  27062. // Meshes
  27063. var meshes = _this._camera.getActiveMeshes();
  27064. for (var index = 0; index < meshes.length; index++) {
  27065. var mesh = meshes.data[index];
  27066. var position = mesh.getBoundingInfo().boundingSphere.center;
  27067. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27068. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27069. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27070. }
  27071. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27072. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27073. mesh.renderOverlay = !mesh.renderOverlay;
  27074. }, function () {
  27075. return mesh.renderOverlay ? 'red' : 'black';
  27076. });
  27077. }
  27078. }
  27079. // Cameras
  27080. var cameras = _this._scene.cameras;
  27081. for (index = 0; index < cameras.length; index++) {
  27082. var camera = cameras[index];
  27083. if (camera === _this._camera) {
  27084. continue;
  27085. }
  27086. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27087. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27088. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27089. _this._camera.detachControl(engine.getRenderingCanvas());
  27090. _this._camera = camera;
  27091. _this._camera.attachControl(engine.getRenderingCanvas());
  27092. }, function () {
  27093. return "purple";
  27094. });
  27095. }
  27096. }
  27097. // Lights
  27098. var lights = _this._scene.lights;
  27099. for (index = 0; index < lights.length; index++) {
  27100. var light = lights[index];
  27101. if (light.position) {
  27102. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27103. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27104. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27105. light.setEnabled(!light.isEnabled());
  27106. }, function () {
  27107. return light.isEnabled() ? "orange" : "gray";
  27108. });
  27109. }
  27110. }
  27111. }
  27112. }
  27113. _this._clickPosition = undefined;
  27114. };
  27115. }
  27116. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27117. while (this._treeSubsetDiv.hasChildNodes()) {
  27118. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27119. }
  27120. // Add meshes
  27121. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27122. sortedArray.sort(function (a, b) {
  27123. if (a.name === b.name) {
  27124. return 0;
  27125. }
  27126. return (a.name > b.name) ? 1 : -1;
  27127. });
  27128. for (var index = 0; index < sortedArray.length; index++) {
  27129. var mesh = sortedArray[index];
  27130. if (!mesh.isEnabled()) {
  27131. continue;
  27132. }
  27133. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27134. m.isVisible = element.checked;
  27135. }, mesh);
  27136. }
  27137. };
  27138. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27139. this._drawingContext.beginPath();
  27140. this._drawingContext.moveTo(zero.x, zero.y);
  27141. this._drawingContext.lineTo(unit.x, unit.y);
  27142. this._drawingContext.strokeStyle = color;
  27143. this._drawingContext.lineWidth = 4;
  27144. this._drawingContext.stroke();
  27145. this._drawingContext.font = "normal 14px Segoe UI";
  27146. this._drawingContext.fillStyle = color;
  27147. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27148. };
  27149. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27150. var position = mesh.getBoundingInfo().boundingSphere.center;
  27151. var worldMatrix = mesh.getWorldMatrix();
  27152. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27153. var unit = (unprojectedVector.subtract(position)).length();
  27154. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27155. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27156. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27157. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27158. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27159. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27160. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27161. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27162. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27163. };
  27164. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27165. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27166. this._drawingContext.font = "normal 12px Segoe UI";
  27167. var textMetrics = this._drawingContext.measureText(text);
  27168. var centerX = projectedPosition.x - textMetrics.width / 2;
  27169. var centerY = projectedPosition.y;
  27170. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27171. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27172. onClick();
  27173. }
  27174. this._drawingContext.beginPath();
  27175. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27176. this._drawingContext.fillStyle = getFillStyle();
  27177. this._drawingContext.globalAlpha = 0.5;
  27178. this._drawingContext.fill();
  27179. this._drawingContext.globalAlpha = 1.0;
  27180. this._drawingContext.strokeStyle = '#FFFFFF';
  27181. this._drawingContext.lineWidth = 1;
  27182. this._drawingContext.stroke();
  27183. this._drawingContext.fillStyle = "#FFFFFF";
  27184. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27185. this._drawingContext.beginPath();
  27186. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27187. this._drawingContext.fill();
  27188. }
  27189. };
  27190. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27191. if (!this._clickPosition) {
  27192. return false;
  27193. }
  27194. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27195. return false;
  27196. }
  27197. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27198. return false;
  27199. }
  27200. return true;
  27201. };
  27202. DebugLayer.prototype.isVisible = function () {
  27203. return this._enabled;
  27204. };
  27205. DebugLayer.prototype.hide = function () {
  27206. if (!this._enabled) {
  27207. return;
  27208. }
  27209. this._enabled = false;
  27210. var engine = this._scene.getEngine();
  27211. this._scene.unregisterBeforeRender(this._syncData);
  27212. this._scene.unregisterAfterRender(this._syncUI);
  27213. document.body.removeChild(this._globalDiv);
  27214. window.removeEventListener("resize", this._syncPositions);
  27215. this._scene.forceShowBoundingBoxes = false;
  27216. this._scene.forceWireframe = false;
  27217. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27218. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27219. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27220. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27221. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27222. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27223. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27224. this._scene.shadowsEnabled = true;
  27225. this._scene.particlesEnabled = true;
  27226. this._scene.postProcessesEnabled = true;
  27227. this._scene.collisionsEnabled = true;
  27228. this._scene.lightsEnabled = true;
  27229. this._scene.texturesEnabled = true;
  27230. this._scene.lensFlaresEnabled = true;
  27231. this._scene.proceduralTexturesEnabled = true;
  27232. this._scene.renderTargetsEnabled = true;
  27233. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27234. };
  27235. DebugLayer.prototype.show = function (showUI, camera) {
  27236. if (showUI === void 0) { showUI = true; }
  27237. if (camera === void 0) { camera = null; }
  27238. if (this._enabled) {
  27239. return;
  27240. }
  27241. if (camera) {
  27242. this._camera = camera;
  27243. }
  27244. else {
  27245. this._camera = this._scene.activeCamera;
  27246. }
  27247. this._enabled = true;
  27248. this._showUI = showUI;
  27249. var engine = this._scene.getEngine();
  27250. this._globalDiv = document.createElement("div");
  27251. document.body.appendChild(this._globalDiv);
  27252. this._generateDOMelements();
  27253. window.addEventListener("resize", this._syncPositions);
  27254. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27255. this._syncPositions();
  27256. this._scene.registerBeforeRender(this._syncData);
  27257. this._scene.registerAfterRender(this._syncUI);
  27258. };
  27259. DebugLayer.prototype._clearLabels = function () {
  27260. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27261. for (var index = 0; index < this._scene.meshes.length; index++) {
  27262. var mesh = this._scene.meshes[index];
  27263. mesh.renderOverlay = false;
  27264. }
  27265. };
  27266. DebugLayer.prototype._generateheader = function (root, text) {
  27267. var header = document.createElement("div");
  27268. header.innerHTML = text + "&nbsp;";
  27269. header.style.textAlign = "right";
  27270. header.style.width = "100%";
  27271. header.style.color = "white";
  27272. header.style.backgroundColor = "Black";
  27273. header.style.padding = "5px 5px 4px 0px";
  27274. header.style.marginLeft = "-5px";
  27275. header.style.fontWeight = "bold";
  27276. root.appendChild(header);
  27277. };
  27278. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27279. var label = document.createElement("label");
  27280. label.innerHTML = title;
  27281. label.style.color = color;
  27282. root.appendChild(label);
  27283. root.appendChild(document.createElement("br"));
  27284. };
  27285. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27286. if (tag === void 0) { tag = null; }
  27287. var label = document.createElement("label");
  27288. var boundingBoxesCheckbox = document.createElement("input");
  27289. boundingBoxesCheckbox.type = "checkbox";
  27290. boundingBoxesCheckbox.checked = initialState;
  27291. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27292. task(evt.target, tag);
  27293. });
  27294. label.appendChild(boundingBoxesCheckbox);
  27295. var container = document.createElement("span");
  27296. var leftPart = document.createElement("span");
  27297. var rightPart = document.createElement("span");
  27298. rightPart.style.cssFloat = "right";
  27299. leftPart.innerHTML = leftTitle;
  27300. rightPart.innerHTML = rightTitle;
  27301. rightPart.style.fontSize = "12px";
  27302. rightPart.style.maxWidth = "200px";
  27303. container.appendChild(leftPart);
  27304. container.appendChild(rightPart);
  27305. label.appendChild(container);
  27306. root.appendChild(label);
  27307. root.appendChild(document.createElement("br"));
  27308. };
  27309. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27310. if (tag === void 0) { tag = null; }
  27311. var label = document.createElement("label");
  27312. var checkBox = document.createElement("input");
  27313. checkBox.type = "checkbox";
  27314. checkBox.checked = initialState;
  27315. checkBox.addEventListener("change", function (evt) {
  27316. task(evt.target, tag);
  27317. });
  27318. label.appendChild(checkBox);
  27319. label.appendChild(document.createTextNode(title));
  27320. root.appendChild(label);
  27321. root.appendChild(document.createElement("br"));
  27322. };
  27323. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27324. if (tag === void 0) { tag = null; }
  27325. var button = document.createElement("button");
  27326. button.innerHTML = title;
  27327. button.style.height = "24px";
  27328. button.style.color = "#444444";
  27329. button.style.border = "1px solid white";
  27330. button.className = "debugLayerButton";
  27331. button.addEventListener("click", function (evt) {
  27332. task(evt.target, tag);
  27333. });
  27334. root.appendChild(button);
  27335. root.appendChild(document.createElement("br"));
  27336. };
  27337. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27338. if (tag === void 0) { tag = null; }
  27339. var label = document.createElement("label");
  27340. var boundingBoxesRadio = document.createElement("input");
  27341. boundingBoxesRadio.type = "radio";
  27342. boundingBoxesRadio.name = name;
  27343. boundingBoxesRadio.checked = initialState;
  27344. boundingBoxesRadio.addEventListener("change", function (evt) {
  27345. task(evt.target, tag);
  27346. });
  27347. label.appendChild(boundingBoxesRadio);
  27348. label.appendChild(document.createTextNode(title));
  27349. root.appendChild(label);
  27350. root.appendChild(document.createElement("br"));
  27351. };
  27352. DebugLayer.prototype._generateDOMelements = function () {
  27353. var _this = this;
  27354. this._globalDiv.id = "DebugLayer";
  27355. this._globalDiv.style.position = "absolute";
  27356. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27357. this._globalDiv.style.fontSize = "14px";
  27358. this._globalDiv.style.color = "white";
  27359. // Drawing canvas
  27360. this._drawingCanvas = document.createElement("canvas");
  27361. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27362. this._drawingCanvas.style.position = "absolute";
  27363. this._drawingCanvas.style.pointerEvents = "none";
  27364. this._drawingContext = this._drawingCanvas.getContext("2d");
  27365. this._globalDiv.appendChild(this._drawingCanvas);
  27366. if (this._showUI) {
  27367. var background = "rgba(128, 128, 128, 0.4)";
  27368. var border = "rgb(180, 180, 180) solid 1px";
  27369. // Stats
  27370. this._statsDiv = document.createElement("div");
  27371. this._statsDiv.id = "DebugLayerStats";
  27372. this._statsDiv.style.border = border;
  27373. this._statsDiv.style.position = "absolute";
  27374. this._statsDiv.style.background = background;
  27375. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27376. this._generateheader(this._statsDiv, "STATISTICS");
  27377. this._statsSubsetDiv = document.createElement("div");
  27378. this._statsSubsetDiv.style.paddingTop = "5px";
  27379. this._statsSubsetDiv.style.paddingBottom = "5px";
  27380. this._statsSubsetDiv.style.overflowY = "auto";
  27381. this._statsDiv.appendChild(this._statsSubsetDiv);
  27382. // Tree
  27383. this._treeDiv = document.createElement("div");
  27384. this._treeDiv.id = "DebugLayerTree";
  27385. this._treeDiv.style.border = border;
  27386. this._treeDiv.style.position = "absolute";
  27387. this._treeDiv.style.background = background;
  27388. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27389. this._treeDiv.style.display = "none";
  27390. this._generateheader(this._treeDiv, "MESHES TREE");
  27391. this._treeSubsetDiv = document.createElement("div");
  27392. this._treeSubsetDiv.style.paddingTop = "5px";
  27393. this._treeSubsetDiv.style.paddingRight = "5px";
  27394. this._treeSubsetDiv.style.overflowY = "auto";
  27395. this._treeSubsetDiv.style.maxHeight = "300px";
  27396. this._treeDiv.appendChild(this._treeSubsetDiv);
  27397. this._needToRefreshMeshesTree = true;
  27398. // Logs
  27399. this._logDiv = document.createElement("div");
  27400. this._logDiv.style.border = border;
  27401. this._logDiv.id = "DebugLayerLogs";
  27402. this._logDiv.style.position = "absolute";
  27403. this._logDiv.style.background = background;
  27404. this._logDiv.style.padding = "0px 0px 0px 5px";
  27405. this._logDiv.style.display = "none";
  27406. this._generateheader(this._logDiv, "LOGS");
  27407. this._logSubsetDiv = document.createElement("div");
  27408. this._logSubsetDiv.style.height = "127px";
  27409. this._logSubsetDiv.style.paddingTop = "5px";
  27410. this._logSubsetDiv.style.overflowY = "auto";
  27411. this._logSubsetDiv.style.fontSize = "12px";
  27412. this._logSubsetDiv.style.fontFamily = "consolas";
  27413. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27414. this._logDiv.appendChild(this._logSubsetDiv);
  27415. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27416. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27417. };
  27418. // Options
  27419. this._optionsDiv = document.createElement("div");
  27420. this._optionsDiv.id = "DebugLayerOptions";
  27421. this._optionsDiv.style.border = border;
  27422. this._optionsDiv.style.position = "absolute";
  27423. this._optionsDiv.style.background = background;
  27424. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27425. this._optionsDiv.style.overflowY = "auto";
  27426. this._generateheader(this._optionsDiv, "OPTIONS");
  27427. this._optionsSubsetDiv = document.createElement("div");
  27428. this._optionsSubsetDiv.style.paddingTop = "5px";
  27429. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27430. this._optionsSubsetDiv.style.overflowY = "auto";
  27431. this._optionsSubsetDiv.style.maxHeight = "200px";
  27432. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27433. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27434. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27435. _this._displayStatistics = element.checked;
  27436. });
  27437. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27438. _this._displayLogs = element.checked;
  27439. });
  27440. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27441. _this._displayTree = element.checked;
  27442. _this._needToRefreshMeshesTree = true;
  27443. });
  27444. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27445. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27446. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27447. _this._scene.forceShowBoundingBoxes = element.checked;
  27448. });
  27449. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27450. _this._labelsEnabled = element.checked;
  27451. if (!_this._labelsEnabled) {
  27452. _this._clearLabels();
  27453. }
  27454. });
  27455. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27456. if (element.checked) {
  27457. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27458. }
  27459. else {
  27460. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27461. }
  27462. });
  27463. ;
  27464. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27465. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27466. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27467. if (element.checked) {
  27468. _this._scene.forceWireframe = false;
  27469. _this._scene.forcePointsCloud = false;
  27470. }
  27471. });
  27472. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27473. if (element.checked) {
  27474. _this._scene.forceWireframe = true;
  27475. _this._scene.forcePointsCloud = false;
  27476. }
  27477. });
  27478. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27479. if (element.checked) {
  27480. _this._scene.forceWireframe = false;
  27481. _this._scene.forcePointsCloud = true;
  27482. }
  27483. });
  27484. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27485. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27486. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27487. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27488. });
  27489. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27490. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27491. });
  27492. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27493. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27494. });
  27495. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27496. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27497. });
  27498. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27499. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27500. });
  27501. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27502. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27503. });
  27504. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27505. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27506. });
  27507. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27508. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27509. });
  27510. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27511. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27512. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27513. _this._scene.animationsEnabled = element.checked;
  27514. });
  27515. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27516. _this._scene.collisionsEnabled = element.checked;
  27517. });
  27518. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27519. _this._scene.fogEnabled = element.checked;
  27520. });
  27521. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27522. _this._scene.lensFlaresEnabled = element.checked;
  27523. });
  27524. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27525. _this._scene.lightsEnabled = element.checked;
  27526. });
  27527. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27528. _this._scene.particlesEnabled = element.checked;
  27529. });
  27530. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27531. _this._scene.postProcessesEnabled = element.checked;
  27532. });
  27533. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27534. _this._scene.proceduralTexturesEnabled = element.checked;
  27535. });
  27536. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27537. _this._scene.renderTargetsEnabled = element.checked;
  27538. });
  27539. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27540. _this._scene.shadowsEnabled = element.checked;
  27541. });
  27542. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27543. _this._scene.skeletonsEnabled = element.checked;
  27544. });
  27545. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27546. _this._scene.spritesEnabled = element.checked;
  27547. });
  27548. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27549. _this._scene.texturesEnabled = element.checked;
  27550. });
  27551. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27552. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27553. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27554. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", true, function (element) {
  27555. if (element.checked) {
  27556. _this._scene.switchAudioModeForHeadphones();
  27557. }
  27558. });
  27559. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", false, function (element) {
  27560. if (element.checked) {
  27561. _this._scene.switchAudioModeForNormalSpeakers();
  27562. }
  27563. });
  27564. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27565. _this._scene.audioEnabled = !element.checked;
  27566. });
  27567. }
  27568. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27569. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27570. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27571. _this._scene.dumpNextRenderTargets = true;
  27572. });
  27573. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27574. this._globalDiv.appendChild(this._statsDiv);
  27575. this._globalDiv.appendChild(this._logDiv);
  27576. this._globalDiv.appendChild(this._optionsDiv);
  27577. this._globalDiv.appendChild(this._treeDiv);
  27578. }
  27579. };
  27580. DebugLayer.prototype._displayStats = function () {
  27581. var scene = this._scene;
  27582. var engine = scene.getEngine();
  27583. var glInfo = engine.getGlInfo();
  27584. 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>";
  27585. if (this.customStatsFunction) {
  27586. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27587. }
  27588. };
  27589. return DebugLayer;
  27590. })();
  27591. BABYLON.DebugLayer = DebugLayer;
  27592. })(BABYLON || (BABYLON = {}));
  27593. //# sourceMappingURL=babylon.debugLayer.js.map
  27594. var BABYLON;
  27595. (function (BABYLON) {
  27596. var RawTexture = (function (_super) {
  27597. __extends(RawTexture, _super);
  27598. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27600. if (invertY === void 0) { invertY = false; }
  27601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27602. _super.call(this, null, scene, !generateMipMaps, invertY);
  27603. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27604. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27605. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27606. }
  27607. // Statics
  27608. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27609. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27610. if (invertY === void 0) { invertY = false; }
  27611. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27612. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27613. };
  27614. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27615. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27616. if (invertY === void 0) { invertY = false; }
  27617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27618. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27619. };
  27620. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27621. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27622. if (invertY === void 0) { invertY = false; }
  27623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27625. };
  27626. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27628. if (invertY === void 0) { invertY = false; }
  27629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27630. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27631. };
  27632. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27633. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27634. if (invertY === void 0) { invertY = false; }
  27635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27636. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27637. };
  27638. return RawTexture;
  27639. })(BABYLON.Texture);
  27640. BABYLON.RawTexture = RawTexture;
  27641. })(BABYLON || (BABYLON = {}));
  27642. //# sourceMappingURL=babylon.rawTexture.js.map
  27643. var BABYLON;
  27644. (function (BABYLON) {
  27645. var IndexedVector2 = (function (_super) {
  27646. __extends(IndexedVector2, _super);
  27647. function IndexedVector2(original, index) {
  27648. _super.call(this, original.x, original.y);
  27649. this.index = index;
  27650. }
  27651. return IndexedVector2;
  27652. })(BABYLON.Vector2);
  27653. var PolygonPoints = (function () {
  27654. function PolygonPoints() {
  27655. this.elements = new Array();
  27656. }
  27657. PolygonPoints.prototype.add = function (originalPoints) {
  27658. var _this = this;
  27659. var result = new Array();
  27660. originalPoints.forEach(function (point) {
  27661. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27662. var newPoint = new IndexedVector2(point, _this.elements.length);
  27663. result.push(newPoint);
  27664. _this.elements.push(newPoint);
  27665. }
  27666. });
  27667. return result;
  27668. };
  27669. PolygonPoints.prototype.computeBounds = function () {
  27670. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27671. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27672. this.elements.forEach(function (point) {
  27673. // x
  27674. if (point.x < lmin.x) {
  27675. lmin.x = point.x;
  27676. }
  27677. else if (point.x > lmax.x) {
  27678. lmax.x = point.x;
  27679. }
  27680. // y
  27681. if (point.y < lmin.y) {
  27682. lmin.y = point.y;
  27683. }
  27684. else if (point.y > lmax.y) {
  27685. lmax.y = point.y;
  27686. }
  27687. });
  27688. return {
  27689. min: lmin,
  27690. max: lmax,
  27691. width: lmax.x - lmin.x,
  27692. height: lmax.y - lmin.y
  27693. };
  27694. };
  27695. return PolygonPoints;
  27696. })();
  27697. var Polygon = (function () {
  27698. function Polygon() {
  27699. }
  27700. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27701. return [
  27702. new BABYLON.Vector2(xmin, ymin),
  27703. new BABYLON.Vector2(xmax, ymin),
  27704. new BABYLON.Vector2(xmax, ymax),
  27705. new BABYLON.Vector2(xmin, ymax)
  27706. ];
  27707. };
  27708. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27709. if (cx === void 0) { cx = 0; }
  27710. if (cy === void 0) { cy = 0; }
  27711. if (numberOfSides === void 0) { numberOfSides = 32; }
  27712. var result = new Array();
  27713. var angle = 0;
  27714. var increment = (Math.PI * 2) / numberOfSides;
  27715. for (var i = 0; i < numberOfSides; i++) {
  27716. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27717. angle -= increment;
  27718. }
  27719. return result;
  27720. };
  27721. Polygon.Parse = function (input) {
  27722. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27723. var i, result = [];
  27724. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27725. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27726. }
  27727. return result;
  27728. };
  27729. Polygon.StartingAt = function (x, y) {
  27730. return BABYLON.Path2.StartingAt(x, y);
  27731. };
  27732. return Polygon;
  27733. })();
  27734. BABYLON.Polygon = Polygon;
  27735. var PolygonMeshBuilder = (function () {
  27736. function PolygonMeshBuilder(name, contours, scene) {
  27737. this._points = new PolygonPoints();
  27738. if (!("poly2tri" in window)) {
  27739. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27740. }
  27741. this._name = name;
  27742. this._scene = scene;
  27743. var points;
  27744. if (contours instanceof BABYLON.Path2) {
  27745. points = contours.getPoints();
  27746. }
  27747. else {
  27748. points = contours;
  27749. }
  27750. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27751. }
  27752. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27753. this._swctx.addHole(this._points.add(hole));
  27754. return this;
  27755. };
  27756. PolygonMeshBuilder.prototype.build = function (updatable) {
  27757. if (updatable === void 0) { updatable = false; }
  27758. var result = new BABYLON.Mesh(this._name, this._scene);
  27759. var normals = [];
  27760. var positions = [];
  27761. var uvs = [];
  27762. var bounds = this._points.computeBounds();
  27763. this._points.elements.forEach(function (p) {
  27764. normals.push(0, 1.0, 0);
  27765. positions.push(p.x, 0, p.y);
  27766. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27767. });
  27768. var indices = [];
  27769. this._swctx.triangulate();
  27770. this._swctx.getTriangles().forEach(function (triangle) {
  27771. triangle.getPoints().forEach(function (point) {
  27772. indices.push(point.index);
  27773. });
  27774. });
  27775. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27776. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27777. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27778. result.setIndices(indices);
  27779. return result;
  27780. };
  27781. return PolygonMeshBuilder;
  27782. })();
  27783. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27784. })(BABYLON || (BABYLON = {}));
  27785. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27786. (function (BABYLON) {
  27787. var SimplificationSettings = (function () {
  27788. function SimplificationSettings(quality, distance) {
  27789. this.quality = quality;
  27790. this.distance = distance;
  27791. }
  27792. return SimplificationSettings;
  27793. })();
  27794. BABYLON.SimplificationSettings = SimplificationSettings;
  27795. var SimplificationQueue = (function () {
  27796. function SimplificationQueue() {
  27797. this.running = false;
  27798. this._simplificationArray = [];
  27799. }
  27800. SimplificationQueue.prototype.addTask = function (task) {
  27801. this._simplificationArray.push(task);
  27802. };
  27803. SimplificationQueue.prototype.executeNext = function () {
  27804. var task = this._simplificationArray.pop();
  27805. if (task) {
  27806. this.running = true;
  27807. this.runSimplification(task);
  27808. }
  27809. else {
  27810. this.running = false;
  27811. }
  27812. };
  27813. SimplificationQueue.prototype.runSimplification = function (task) {
  27814. var _this = this;
  27815. function setLODLevel(distance, mesh) {
  27816. }
  27817. if (task.parallelProcessing) {
  27818. //parallel simplifier
  27819. task.settings.forEach(function (setting) {
  27820. var simplifier = _this.getSimplifier(task);
  27821. simplifier.simplify(setting, function (newMesh) {
  27822. task.mesh.addLODLevel(setting.distance, newMesh);
  27823. //check if it is the last
  27824. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27825. //all done, run the success callback.
  27826. task.successCallback();
  27827. }
  27828. _this.executeNext();
  27829. });
  27830. });
  27831. }
  27832. else {
  27833. //single simplifier.
  27834. var simplifier = this.getSimplifier(task);
  27835. var runDecimation = function (setting, callback) {
  27836. simplifier.simplify(setting, function (newMesh) {
  27837. task.mesh.addLODLevel(setting.distance, newMesh);
  27838. //run the next quality level
  27839. callback();
  27840. });
  27841. };
  27842. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27843. runDecimation(task.settings[loop.index], function () {
  27844. loop.executeNext();
  27845. });
  27846. }, function () {
  27847. //execution ended, run the success callback.
  27848. if (task.successCallback) {
  27849. task.successCallback();
  27850. }
  27851. _this.executeNext();
  27852. });
  27853. }
  27854. };
  27855. SimplificationQueue.prototype.getSimplifier = function (task) {
  27856. switch (task.simplificationType) {
  27857. case 0 /* QUADRATIC */:
  27858. default:
  27859. return new QuadraticErrorSimplification(task.mesh);
  27860. }
  27861. };
  27862. return SimplificationQueue;
  27863. })();
  27864. BABYLON.SimplificationQueue = SimplificationQueue;
  27865. /**
  27866. * The implemented types of simplification.
  27867. * At the moment only Quadratic Error Decimation is implemented.
  27868. */
  27869. (function (SimplificationType) {
  27870. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27871. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27872. var SimplificationType = BABYLON.SimplificationType;
  27873. var DecimationTriangle = (function () {
  27874. function DecimationTriangle(vertices) {
  27875. this.vertices = vertices;
  27876. this.error = new Array(4);
  27877. this.deleted = false;
  27878. this.isDirty = false;
  27879. this.borderFactor = 0;
  27880. }
  27881. return DecimationTriangle;
  27882. })();
  27883. BABYLON.DecimationTriangle = DecimationTriangle;
  27884. var DecimationVertex = (function () {
  27885. function DecimationVertex(position, normal, uv, id) {
  27886. this.position = position;
  27887. this.normal = normal;
  27888. this.uv = uv;
  27889. this.id = id;
  27890. this.isBorder = true;
  27891. this.q = new QuadraticMatrix();
  27892. this.triangleCount = 0;
  27893. this.triangleStart = 0;
  27894. }
  27895. return DecimationVertex;
  27896. })();
  27897. BABYLON.DecimationVertex = DecimationVertex;
  27898. var QuadraticMatrix = (function () {
  27899. function QuadraticMatrix(data) {
  27900. this.data = new Array(10);
  27901. for (var i = 0; i < 10; ++i) {
  27902. if (data && data[i]) {
  27903. this.data[i] = data[i];
  27904. }
  27905. else {
  27906. this.data[i] = 0;
  27907. }
  27908. }
  27909. }
  27910. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27911. 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];
  27912. return det;
  27913. };
  27914. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27915. for (var i = 0; i < 10; ++i) {
  27916. this.data[i] += matrix.data[i];
  27917. }
  27918. };
  27919. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27920. for (var i = 0; i < 10; ++i) {
  27921. this.data[i] += data[i];
  27922. }
  27923. };
  27924. QuadraticMatrix.prototype.add = function (matrix) {
  27925. var m = new QuadraticMatrix();
  27926. for (var i = 0; i < 10; ++i) {
  27927. m.data[i] = this.data[i] + matrix.data[i];
  27928. }
  27929. return m;
  27930. };
  27931. QuadraticMatrix.FromData = function (a, b, c, d) {
  27932. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27933. };
  27934. //returning an array to avoid garbage collection
  27935. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27936. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27937. };
  27938. return QuadraticMatrix;
  27939. })();
  27940. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27941. var Reference = (function () {
  27942. function Reference(vertexId, triangleId) {
  27943. this.vertexId = vertexId;
  27944. this.triangleId = triangleId;
  27945. }
  27946. return Reference;
  27947. })();
  27948. BABYLON.Reference = Reference;
  27949. /**
  27950. * An implementation of the Quadratic Error simplification algorithm.
  27951. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27952. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27953. * @author RaananW
  27954. */
  27955. var QuadraticErrorSimplification = (function () {
  27956. function QuadraticErrorSimplification(_mesh) {
  27957. this._mesh = _mesh;
  27958. this.initialised = false;
  27959. this.syncIterations = 5000;
  27960. this.aggressiveness = 7;
  27961. this.decimationIterations = 100;
  27962. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  27963. }
  27964. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27965. var _this = this;
  27966. this.initDecimatedMesh();
  27967. //iterating through the submeshes array, one after the other.
  27968. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  27969. _this.initWithMesh(_this._mesh, loop.index, function () {
  27970. _this.runDecimation(settings, loop.index, function () {
  27971. loop.executeNext();
  27972. });
  27973. });
  27974. }, function () {
  27975. setTimeout(function () {
  27976. _this._reconstructedMesh.isVisible = true;
  27977. successCallback(_this._reconstructedMesh);
  27978. }, 0);
  27979. });
  27980. };
  27981. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  27982. var _this = this;
  27983. var gCount = 0;
  27984. triangle.vertices.forEach(function (vId) {
  27985. var count = 0;
  27986. var vPos = _this.vertices[vId].position;
  27987. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  27988. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  27989. ++count;
  27990. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  27991. ++count;
  27992. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  27993. ++count;
  27994. if (count > 1) {
  27995. ++gCount;
  27996. }
  27997. ;
  27998. });
  27999. if (gCount > 1) {
  28000. console.log(triangle, gCount);
  28001. }
  28002. return gCount > 1;
  28003. };
  28004. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28005. var _this = this;
  28006. var targetCount = ~~(this.triangles.length * settings.quality);
  28007. var deletedTriangles = 0;
  28008. var triangleCount = this.triangles.length;
  28009. var iterationFunction = function (iteration, callback) {
  28010. setTimeout(function () {
  28011. if (iteration % 5 === 0) {
  28012. _this.updateMesh(iteration === 0);
  28013. }
  28014. for (var i = 0; i < _this.triangles.length; ++i) {
  28015. _this.triangles[i].isDirty = false;
  28016. }
  28017. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28018. var trianglesIterator = function (i) {
  28019. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28020. var t = _this.triangles[tIdx];
  28021. if (!t)
  28022. return;
  28023. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28024. return;
  28025. }
  28026. for (var j = 0; j < 3; ++j) {
  28027. if (t.error[j] < threshold) {
  28028. var deleted0 = [];
  28029. var deleted1 = [];
  28030. var i0 = t.vertices[j];
  28031. var i1 = t.vertices[(j + 1) % 3];
  28032. var v0 = _this.vertices[i0];
  28033. var v1 = _this.vertices[i1];
  28034. if (v0.isBorder !== v1.isBorder)
  28035. continue;
  28036. var p = BABYLON.Vector3.Zero();
  28037. var n = BABYLON.Vector3.Zero();
  28038. var uv = BABYLON.Vector2.Zero();
  28039. var color = new BABYLON.Color4(0, 0, 0, 1);
  28040. _this.calculateError(v0, v1, p, n, uv, color);
  28041. var delTr = [];
  28042. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28043. continue;
  28044. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28045. continue;
  28046. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  28047. continue;
  28048. }
  28049. v0.normal = n;
  28050. if (v0.uv)
  28051. v0.uv = uv;
  28052. else if (v0.color)
  28053. v0.color = color;
  28054. v0.q = v1.q.add(v0.q);
  28055. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28056. continue;
  28057. if (p.equals(v0.position))
  28058. continue;
  28059. v0.position = p;
  28060. var tStart = _this.references.length;
  28061. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28062. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28063. var tCount = _this.references.length - tStart;
  28064. if (tCount <= v0.triangleCount) {
  28065. if (tCount) {
  28066. for (var c = 0; c < tCount; c++) {
  28067. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28068. }
  28069. }
  28070. }
  28071. else {
  28072. v0.triangleStart = tStart;
  28073. }
  28074. v0.triangleCount = tCount;
  28075. break;
  28076. }
  28077. }
  28078. };
  28079. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28080. return (triangleCount - deletedTriangles <= targetCount);
  28081. });
  28082. }, 0);
  28083. };
  28084. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28085. if (triangleCount - deletedTriangles <= targetCount)
  28086. loop.breakLoop();
  28087. else {
  28088. iterationFunction(loop.index, function () {
  28089. loop.executeNext();
  28090. });
  28091. }
  28092. }, function () {
  28093. setTimeout(function () {
  28094. //reconstruct this part of the mesh
  28095. _this.reconstructMesh(submeshIndex);
  28096. successCallback();
  28097. }, 0);
  28098. });
  28099. };
  28100. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28101. var _this = this;
  28102. if (!mesh)
  28103. return;
  28104. this.vertices = [];
  28105. this.triangles = [];
  28106. this._mesh = mesh;
  28107. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28108. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28109. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28110. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28111. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28112. var indices = mesh.getIndices();
  28113. var submesh = mesh.subMeshes[submeshIndex];
  28114. var vertexInit = function (i) {
  28115. var offset = i + submesh.verticesStart;
  28116. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28117. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28118. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28119. }
  28120. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28121. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28122. }
  28123. _this.vertices.push(vertex);
  28124. };
  28125. //var totalVertices = mesh.getTotalVertices();
  28126. var totalVertices = submesh.verticesCount;
  28127. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28128. var indicesInit = function (i) {
  28129. var offset = (submesh.indexStart / 3) + i;
  28130. var pos = (offset * 3);
  28131. var i0 = indices[pos + 0] - submesh.verticesStart;
  28132. var i1 = indices[pos + 1] - submesh.verticesStart;
  28133. var i2 = indices[pos + 2] - submesh.verticesStart;
  28134. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28135. _this.triangles.push(triangle);
  28136. };
  28137. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28138. _this.init(callback);
  28139. });
  28140. });
  28141. };
  28142. QuadraticErrorSimplification.prototype.init = function (callback) {
  28143. var _this = this;
  28144. var triangleInit1 = function (i) {
  28145. var t = _this.triangles[i];
  28146. 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();
  28147. for (var j = 0; j < 3; j++) {
  28148. _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))));
  28149. }
  28150. };
  28151. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28152. var triangleInit2 = function (i) {
  28153. var t = _this.triangles[i];
  28154. for (var j = 0; j < 3; ++j) {
  28155. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28156. }
  28157. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28158. };
  28159. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28160. _this.initialised = true;
  28161. callback();
  28162. });
  28163. });
  28164. };
  28165. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28166. var newTriangles = [];
  28167. var i;
  28168. for (i = 0; i < this.vertices.length; ++i) {
  28169. this.vertices[i].triangleCount = 0;
  28170. }
  28171. var t;
  28172. var j;
  28173. for (i = 0; i < this.triangles.length; ++i) {
  28174. if (!this.triangles[i].deleted) {
  28175. t = this.triangles[i];
  28176. for (j = 0; j < 3; ++j) {
  28177. this.vertices[t.vertices[j]].triangleCount = 1;
  28178. }
  28179. newTriangles.push(t);
  28180. }
  28181. }
  28182. var newVerticesOrder = [];
  28183. //compact vertices, get the IDs of the vertices used.
  28184. var dst = 0;
  28185. for (i = 0; i < this.vertices.length; ++i) {
  28186. if (this.vertices[i].triangleCount) {
  28187. this.vertices[i].triangleStart = dst;
  28188. this.vertices[dst].position = this.vertices[i].position;
  28189. this.vertices[dst].normal = this.vertices[i].normal;
  28190. this.vertices[dst].uv = this.vertices[i].uv;
  28191. this.vertices[dst].color = this.vertices[i].color;
  28192. newVerticesOrder.push(i);
  28193. dst++;
  28194. }
  28195. }
  28196. for (i = 0; i < newTriangles.length; ++i) {
  28197. t = newTriangles[i];
  28198. for (j = 0; j < 3; ++j) {
  28199. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28200. }
  28201. }
  28202. this.vertices = this.vertices.slice(0, dst);
  28203. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28204. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28205. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28206. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28207. for (i = 0; i < newVerticesOrder.length; ++i) {
  28208. newPositionData.push(this.vertices[i].position.x);
  28209. newPositionData.push(this.vertices[i].position.y);
  28210. newPositionData.push(this.vertices[i].position.z);
  28211. newNormalData.push(this.vertices[i].normal.x);
  28212. newNormalData.push(this.vertices[i].normal.y);
  28213. newNormalData.push(this.vertices[i].normal.z);
  28214. if (this.vertices[i].uv) {
  28215. newUVsData.push(this.vertices[i].uv.x);
  28216. newUVsData.push(this.vertices[i].uv.y);
  28217. }
  28218. else if (this.vertices[i].color) {
  28219. newColorsData.push(this.vertices[i].color.r);
  28220. newColorsData.push(this.vertices[i].color.g);
  28221. newColorsData.push(this.vertices[i].color.b);
  28222. newColorsData.push(this.vertices[i].color.a);
  28223. }
  28224. }
  28225. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28226. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28227. var submeshesArray = this._reconstructedMesh.subMeshes;
  28228. this._reconstructedMesh.subMeshes = [];
  28229. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28230. for (i = 0; i < newTriangles.length; ++i) {
  28231. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28232. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28233. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28234. }
  28235. //overwriting the old vertex buffers and indices.
  28236. this._reconstructedMesh.setIndices(newIndicesArray);
  28237. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28238. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28239. if (newUVsData.length > 0)
  28240. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28241. if (newColorsData.length > 0)
  28242. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28243. //create submesh
  28244. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28245. if (submeshIndex > 0) {
  28246. this._reconstructedMesh.subMeshes = [];
  28247. submeshesArray.forEach(function (submesh) {
  28248. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28249. });
  28250. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28251. }
  28252. };
  28253. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28254. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28255. this._reconstructedMesh.material = this._mesh.material;
  28256. this._reconstructedMesh.parent = this._mesh.parent;
  28257. this._reconstructedMesh.isVisible = false;
  28258. };
  28259. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28260. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28261. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28262. if (t.deleted)
  28263. continue;
  28264. var s = this.references[vertex1.triangleStart + i].vertexId;
  28265. var id1 = t.vertices[(s + 1) % 3];
  28266. var id2 = t.vertices[(s + 2) % 3];
  28267. if ((id1 === index2 || id2 === index2)) {
  28268. deletedArray[i] = true;
  28269. delTr.push(t);
  28270. continue;
  28271. }
  28272. var d1 = this.vertices[id1].position.subtract(point);
  28273. d1 = d1.normalize();
  28274. var d2 = this.vertices[id2].position.subtract(point);
  28275. d2 = d2.normalize();
  28276. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28277. return true;
  28278. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28279. deletedArray[i] = false;
  28280. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28281. return true;
  28282. }
  28283. return false;
  28284. };
  28285. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28286. var newDeleted = deletedTriangles;
  28287. for (var i = 0; i < vertex.triangleCount; ++i) {
  28288. var ref = this.references[vertex.triangleStart + i];
  28289. var t = this.triangles[ref.triangleId];
  28290. if (t.deleted)
  28291. continue;
  28292. if (deletedArray[i]) {
  28293. t.deleted = true;
  28294. newDeleted++;
  28295. continue;
  28296. }
  28297. t.vertices[ref.vertexId] = vertexId;
  28298. t.isDirty = true;
  28299. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28300. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28301. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28302. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28303. this.references.push(ref);
  28304. }
  28305. return newDeleted;
  28306. };
  28307. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28308. for (var i = 0; i < this.vertices.length; ++i) {
  28309. var vCount = [];
  28310. var vId = [];
  28311. var v = this.vertices[i];
  28312. var j;
  28313. for (j = 0; j < v.triangleCount; ++j) {
  28314. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28315. for (var ii = 0; ii < 3; ii++) {
  28316. var ofs = 0;
  28317. var id = triangle.vertices[ii];
  28318. while (ofs < vCount.length) {
  28319. if (vId[ofs] === id)
  28320. break;
  28321. ++ofs;
  28322. }
  28323. if (ofs === vCount.length) {
  28324. vCount.push(1);
  28325. vId.push(id);
  28326. }
  28327. else {
  28328. vCount[ofs]++;
  28329. }
  28330. }
  28331. }
  28332. for (j = 0; j < vCount.length; ++j) {
  28333. if (vCount[j] === 1) {
  28334. this.vertices[vId[j]].isBorder = true;
  28335. }
  28336. else {
  28337. this.vertices[vId[j]].isBorder = false;
  28338. }
  28339. }
  28340. }
  28341. };
  28342. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28343. if (identifyBorders === void 0) { identifyBorders = false; }
  28344. var i;
  28345. if (!identifyBorders) {
  28346. var newTrianglesVector = [];
  28347. for (i = 0; i < this.triangles.length; ++i) {
  28348. if (!this.triangles[i].deleted) {
  28349. newTrianglesVector.push(this.triangles[i]);
  28350. }
  28351. }
  28352. this.triangles = newTrianglesVector;
  28353. }
  28354. for (i = 0; i < this.vertices.length; ++i) {
  28355. this.vertices[i].triangleCount = 0;
  28356. this.vertices[i].triangleStart = 0;
  28357. }
  28358. var t;
  28359. var j;
  28360. var v;
  28361. for (i = 0; i < this.triangles.length; ++i) {
  28362. t = this.triangles[i];
  28363. for (j = 0; j < 3; ++j) {
  28364. v = this.vertices[t.vertices[j]];
  28365. v.triangleCount++;
  28366. }
  28367. }
  28368. var tStart = 0;
  28369. for (i = 0; i < this.vertices.length; ++i) {
  28370. this.vertices[i].triangleStart = tStart;
  28371. tStart += this.vertices[i].triangleCount;
  28372. this.vertices[i].triangleCount = 0;
  28373. }
  28374. var newReferences = new Array(this.triangles.length * 3);
  28375. for (i = 0; i < this.triangles.length; ++i) {
  28376. t = this.triangles[i];
  28377. for (j = 0; j < 3; ++j) {
  28378. v = this.vertices[t.vertices[j]];
  28379. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28380. v.triangleCount++;
  28381. }
  28382. }
  28383. this.references = newReferences;
  28384. if (identifyBorders) {
  28385. this.identifyBorder();
  28386. }
  28387. };
  28388. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28389. var x = point.x;
  28390. var y = point.y;
  28391. var z = point.z;
  28392. 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];
  28393. };
  28394. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28395. var q = vertex1.q.add(vertex2.q);
  28396. var border = vertex1.isBorder && vertex2.isBorder;
  28397. var error = 0;
  28398. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28399. if (qDet !== 0 && !border) {
  28400. if (!pointResult) {
  28401. pointResult = BABYLON.Vector3.Zero();
  28402. }
  28403. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28404. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28405. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28406. error = this.vertexError(q, pointResult);
  28407. //TODO this should be correctly calculated
  28408. if (normalResult) {
  28409. normalResult.copyFrom(vertex1.normal);
  28410. if (vertex1.uv)
  28411. uvResult.copyFrom(vertex1.uv);
  28412. else if (vertex1.color)
  28413. colorResult.copyFrom(vertex1.color);
  28414. }
  28415. }
  28416. else {
  28417. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28418. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28419. var error1 = this.vertexError(q, vertex1.position);
  28420. var error2 = this.vertexError(q, vertex2.position);
  28421. var error3 = this.vertexError(q, p3);
  28422. error = Math.min(error1, error2, error3);
  28423. if (error === error1) {
  28424. if (pointResult) {
  28425. pointResult.copyFrom(vertex1.position);
  28426. normalResult.copyFrom(vertex1.normal);
  28427. if (vertex1.uv)
  28428. uvResult.copyFrom(vertex1.uv);
  28429. else if (vertex1.color)
  28430. colorResult.copyFrom(vertex1.color);
  28431. }
  28432. }
  28433. else if (error === error2) {
  28434. if (pointResult) {
  28435. pointResult.copyFrom(vertex2.position);
  28436. normalResult.copyFrom(vertex2.normal);
  28437. if (vertex2.uv)
  28438. uvResult.copyFrom(vertex2.uv);
  28439. else if (vertex2.color)
  28440. colorResult.copyFrom(vertex2.color);
  28441. }
  28442. }
  28443. else {
  28444. if (pointResult) {
  28445. pointResult.copyFrom(p3);
  28446. normalResult.copyFrom(vertex1.normal);
  28447. if (vertex1.uv)
  28448. uvResult.copyFrom(vertex1.uv);
  28449. else if (vertex1.color)
  28450. colorResult.copyFrom(vertex1.color);
  28451. }
  28452. }
  28453. }
  28454. return error;
  28455. };
  28456. return QuadraticErrorSimplification;
  28457. })();
  28458. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28459. })(BABYLON || (BABYLON = {}));
  28460. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28461. (function (BABYLON) {
  28462. var Analyser = (function () {
  28463. function Analyser(scene) {
  28464. this.SMOOTHING = 0.75;
  28465. this.FFT_SIZE = 512;
  28466. this.BARGRAPHAMPLITUDE = 256;
  28467. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28468. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28469. this._scene = scene;
  28470. this._audioEngine = BABYLON.Engine.audioEngine;
  28471. if (this._audioEngine.canUseWebAudio) {
  28472. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28473. this._webAudioAnalyser.minDecibels = -140;
  28474. this._webAudioAnalyser.maxDecibels = 0;
  28475. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28476. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28477. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28478. }
  28479. }
  28480. Analyser.prototype.getFrequencyBinCount = function () {
  28481. if (this._audioEngine.canUseWebAudio) {
  28482. return this._webAudioAnalyser.frequencyBinCount;
  28483. }
  28484. else {
  28485. return 0;
  28486. }
  28487. };
  28488. Analyser.prototype.getByteFrequencyData = function () {
  28489. if (this._audioEngine.canUseWebAudio) {
  28490. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28491. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28492. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28493. }
  28494. return this._byteFreqs;
  28495. };
  28496. Analyser.prototype.getByteTimeDomainData = function () {
  28497. if (this._audioEngine.canUseWebAudio) {
  28498. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28499. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28500. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28501. }
  28502. return this._byteTime;
  28503. };
  28504. Analyser.prototype.getFloatFrequencyData = function () {
  28505. if (this._audioEngine.canUseWebAudio) {
  28506. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28507. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28508. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28509. }
  28510. return this._floatFreqs;
  28511. };
  28512. Analyser.prototype.drawDebugCanvas = function () {
  28513. var _this = this;
  28514. if (this._audioEngine.canUseWebAudio) {
  28515. if (!this._debugCanvas) {
  28516. this._debugCanvas = document.createElement("canvas");
  28517. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28518. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28519. this._debugCanvas.style.position = "absolute";
  28520. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28521. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28522. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28523. document.body.appendChild(this._debugCanvas);
  28524. this._registerFunc = function () {
  28525. _this.drawDebugCanvas();
  28526. };
  28527. this._scene.registerBeforeRender(this._registerFunc);
  28528. }
  28529. if (this._registerFunc) {
  28530. var workingArray = this.getByteFrequencyData();
  28531. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28532. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28533. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28534. var value = workingArray[i];
  28535. var percent = value / this.BARGRAPHAMPLITUDE;
  28536. var height = this.DEBUGCANVASSIZE.height * percent;
  28537. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28538. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28539. var hue = i / this.getFrequencyBinCount() * 360;
  28540. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28541. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28542. }
  28543. }
  28544. }
  28545. };
  28546. Analyser.prototype.stopDebugCanvas = function () {
  28547. if (this._debugCanvas) {
  28548. this._scene.unregisterBeforeRender(this._registerFunc);
  28549. this._registerFunc = null;
  28550. document.body.removeChild(this._debugCanvas);
  28551. this._debugCanvas = null;
  28552. this._debugCanvasContext = null;
  28553. }
  28554. };
  28555. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28556. if (this._audioEngine.canUseWebAudio) {
  28557. inputAudioNode.connect(this._webAudioAnalyser);
  28558. this._webAudioAnalyser.connect(outputAudioNode);
  28559. }
  28560. };
  28561. Analyser.prototype.dispose = function () {
  28562. if (this._audioEngine.canUseWebAudio) {
  28563. this._webAudioAnalyser.disconnect();
  28564. }
  28565. };
  28566. return Analyser;
  28567. })();
  28568. BABYLON.Analyser = Analyser;
  28569. })(BABYLON || (BABYLON = {}));
  28570. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28571. (function (BABYLON) {
  28572. var DepthRenderer = (function () {
  28573. function DepthRenderer(scene, type) {
  28574. var _this = this;
  28575. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28576. this._viewMatrix = BABYLON.Matrix.Zero();
  28577. this._projectionMatrix = BABYLON.Matrix.Zero();
  28578. this._transformMatrix = BABYLON.Matrix.Zero();
  28579. this._worldViewProjection = BABYLON.Matrix.Zero();
  28580. this._scene = scene;
  28581. var engine = scene.getEngine();
  28582. // Render target
  28583. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28584. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28585. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28586. this._depthMap.refreshRate = 1;
  28587. this._depthMap.renderParticles = false;
  28588. this._depthMap.renderList = null;
  28589. // Custom render function
  28590. var renderSubMesh = function (subMesh) {
  28591. var mesh = subMesh.getRenderingMesh();
  28592. var scene = _this._scene;
  28593. var engine = scene.getEngine();
  28594. // Culling
  28595. engine.setState(subMesh.getMaterial().backFaceCulling);
  28596. // Managing instances
  28597. var batch = mesh._getInstancesRenderList(subMesh._id);
  28598. if (batch.mustReturn) {
  28599. return;
  28600. }
  28601. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28602. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28603. engine.enableEffect(_this._effect);
  28604. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28605. var material = subMesh.getMaterial();
  28606. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28607. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28608. // Alpha test
  28609. if (material && material.needAlphaTesting()) {
  28610. var alphaTexture = material.getAlphaTestTexture();
  28611. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28612. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28613. }
  28614. // Bones
  28615. if (mesh.useBones) {
  28616. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28617. }
  28618. // Draw
  28619. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28620. }
  28621. };
  28622. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28623. var index;
  28624. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28625. renderSubMesh(opaqueSubMeshes.data[index]);
  28626. }
  28627. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28628. renderSubMesh(alphaTestSubMeshes.data[index]);
  28629. }
  28630. };
  28631. }
  28632. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28633. var defines = [];
  28634. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28635. var mesh = subMesh.getMesh();
  28636. var scene = mesh.getScene();
  28637. var material = subMesh.getMaterial();
  28638. // Alpha test
  28639. if (material && material.needAlphaTesting()) {
  28640. defines.push("#define ALPHATEST");
  28641. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28642. attribs.push(BABYLON.VertexBuffer.UVKind);
  28643. defines.push("#define UV1");
  28644. }
  28645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28646. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28647. defines.push("#define UV2");
  28648. }
  28649. }
  28650. // Bones
  28651. if (mesh.useBones) {
  28652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28654. defines.push("#define BONES");
  28655. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28656. }
  28657. // Instances
  28658. if (useInstances) {
  28659. defines.push("#define INSTANCES");
  28660. attribs.push("world0");
  28661. attribs.push("world1");
  28662. attribs.push("world2");
  28663. attribs.push("world3");
  28664. }
  28665. // Get correct effect
  28666. var join = defines.join("\n");
  28667. if (this._cachedDefines !== join) {
  28668. this._cachedDefines = join;
  28669. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28670. }
  28671. return this._effect.isReady();
  28672. };
  28673. DepthRenderer.prototype.getDepthMap = function () {
  28674. return this._depthMap;
  28675. };
  28676. // Methods
  28677. DepthRenderer.prototype.dispose = function () {
  28678. this._depthMap.dispose();
  28679. };
  28680. return DepthRenderer;
  28681. })();
  28682. BABYLON.DepthRenderer = DepthRenderer;
  28683. })(BABYLON || (BABYLON = {}));
  28684. //# sourceMappingURL=babylon.depthRenderer.js.map
  28685. var BABYLON;
  28686. (function (BABYLON) {
  28687. var SSAORenderingPipeline = (function (_super) {
  28688. __extends(SSAORenderingPipeline, _super);
  28689. /**
  28690. * @constructor
  28691. * @param {string} name - The rendering pipeline name
  28692. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28693. * @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)
  28694. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28695. */
  28696. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28697. var _this = this;
  28698. _super.call(this, scene.getEngine(), name);
  28699. // Members
  28700. /**
  28701. * The PassPostProcess id in the pipeline that contains the original scene color
  28702. * @type {string}
  28703. */
  28704. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28705. /**
  28706. * The SSAO PostProcess id in the pipeline
  28707. * @type {string}
  28708. */
  28709. this.SSAORenderEffect = "SSAORenderEffect";
  28710. /**
  28711. * The horizontal blur PostProcess id in the pipeline
  28712. * @type {string}
  28713. */
  28714. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28715. /**
  28716. * The vertical blur PostProcess id in the pipeline
  28717. * @type {string}
  28718. */
  28719. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28720. /**
  28721. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28722. * @type {string}
  28723. */
  28724. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28725. this._firstUpdate = true;
  28726. this._scene = scene;
  28727. // Set up assets
  28728. this._createRandomTexture();
  28729. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28730. var ssaoRatio = ratio.ssaoRatio || ratio;
  28731. var combineRatio = ratio.combineRatio || ratio;
  28732. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28733. this._createSSAOPostProcess(ssaoRatio);
  28734. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28735. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28736. this._createSSAOCombinePostProcess(combineRatio);
  28737. // Set up pipeline
  28738. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28739. return _this._originalColorPostProcess;
  28740. }, true));
  28741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28742. return _this._ssaoPostProcess;
  28743. }, true));
  28744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28745. return _this._blurHPostProcess;
  28746. }, true));
  28747. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28748. return _this._blurVPostProcess;
  28749. }, true));
  28750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28751. return _this._ssaoCombinePostProcess;
  28752. }, true));
  28753. // Finish
  28754. scene.postProcessRenderPipelineManager.addPipeline(this);
  28755. if (cameras)
  28756. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28757. }
  28758. // Public Methods
  28759. /**
  28760. * Returns the horizontal blur PostProcess
  28761. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28762. */
  28763. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28764. return this._blurHPostProcess;
  28765. };
  28766. /**
  28767. * Returns the vertical blur PostProcess
  28768. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28769. */
  28770. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28771. return this._blurVPostProcess;
  28772. };
  28773. /**
  28774. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28775. */
  28776. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28777. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28778. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28779. this._originalColorPostProcess = undefined;
  28780. this._ssaoPostProcess = undefined;
  28781. this._blurHPostProcess = undefined;
  28782. this._blurVPostProcess = undefined;
  28783. this._ssaoCombinePostProcess = undefined;
  28784. this._randomTexture.dispose();
  28785. if (disableDepthRender)
  28786. this._scene.disableDepthRenderer();
  28787. };
  28788. // Private Methods
  28789. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28790. var _this = this;
  28791. var sampleSphere = [
  28792. 0.5381,
  28793. 0.1856,
  28794. -0.4319,
  28795. 0.1379,
  28796. 0.2486,
  28797. 0.4430,
  28798. 0.3371,
  28799. 0.5679,
  28800. -0.0057,
  28801. -0.6999,
  28802. -0.0451,
  28803. -0.0019,
  28804. 0.0689,
  28805. -0.1598,
  28806. -0.8547,
  28807. 0.0560,
  28808. 0.0069,
  28809. -0.1843,
  28810. -0.0146,
  28811. 0.1402,
  28812. 0.0762,
  28813. 0.0100,
  28814. -0.1924,
  28815. -0.0344,
  28816. -0.3577,
  28817. -0.5301,
  28818. -0.4358,
  28819. -0.3169,
  28820. 0.1063,
  28821. 0.0158,
  28822. 0.0103,
  28823. -0.5869,
  28824. 0.0046,
  28825. -0.0897,
  28826. -0.4940,
  28827. 0.3287,
  28828. 0.7119,
  28829. -0.0154,
  28830. -0.0918,
  28831. -0.0533,
  28832. 0.0596,
  28833. -0.5411,
  28834. 0.0352,
  28835. -0.0631,
  28836. 0.5460,
  28837. -0.4776,
  28838. 0.2847,
  28839. -0.0271
  28840. ];
  28841. var samplesFactor = 1.0 / 16.0;
  28842. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28843. this._ssaoPostProcess.onApply = function (effect) {
  28844. if (_this._firstUpdate) {
  28845. effect.setArray3("sampleSphere", sampleSphere);
  28846. effect.setFloat("samplesFactor", samplesFactor);
  28847. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28848. _this._firstUpdate = false;
  28849. }
  28850. effect.setTexture("textureSampler", _this._depthTexture);
  28851. effect.setTexture("randomSampler", _this._randomTexture);
  28852. };
  28853. };
  28854. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28855. var _this = this;
  28856. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28857. this._ssaoCombinePostProcess.onApply = function (effect) {
  28858. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28859. };
  28860. };
  28861. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28862. var size = 512;
  28863. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28864. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28865. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28866. var context = this._randomTexture.getContext();
  28867. var rand = function (min, max) {
  28868. return Math.random() * (max - min) + min;
  28869. };
  28870. for (var x = 0; x < size; x++) {
  28871. for (var y = 0; y < size; y++) {
  28872. var randVector = BABYLON.Vector3.Zero();
  28873. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28874. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28875. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28876. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28877. context.fillRect(x, y, 1, 1);
  28878. }
  28879. }
  28880. this._randomTexture.update(false);
  28881. };
  28882. return SSAORenderingPipeline;
  28883. })(BABYLON.PostProcessRenderPipeline);
  28884. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28885. })(BABYLON || (BABYLON = {}));
  28886. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28887. var BABYLON;
  28888. (function (BABYLON) {
  28889. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28890. var VolumetricLightScatteringPostProcess = (function (_super) {
  28891. __extends(VolumetricLightScatteringPostProcess, _super);
  28892. /**
  28893. * @constructor
  28894. * @param {string} name - The post-process name
  28895. * @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)
  28896. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28897. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28898. * @param {number} samples - The post-process quality, default 100
  28899. * @param {number} samplingMode - The post-process filtering mode
  28900. * @param {BABYLON.Engine} engine - The babylon engine
  28901. * @param {boolean} reusable - If the post-process is reusable
  28902. */
  28903. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28904. var _this = this;
  28905. if (samples === void 0) { samples = 100; }
  28906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28907. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28908. this._screenCoordinates = BABYLON.Vector2.Zero();
  28909. /**
  28910. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28911. * @type {boolean}
  28912. */
  28913. this.useCustomMeshPosition = false;
  28914. /**
  28915. * If the post-process should inverse the light scattering direction
  28916. * @type {boolean}
  28917. */
  28918. this.invert = true;
  28919. /**
  28920. * Array containing the excluded meshes not rendered in the internal pass
  28921. */
  28922. this.excludedMeshes = new Array();
  28923. this.exposure = 0.3;
  28924. this.decay = 0.96815;
  28925. this.weight = 0.58767;
  28926. this.density = 0.926;
  28927. var scene = camera.getScene();
  28928. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28929. // Configure mesh
  28930. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28931. // Configure
  28932. this._createPass(scene, ratio.passRatio || ratio);
  28933. this.onApply = function (effect) {
  28934. _this._updateMeshScreenCoordinates(scene);
  28935. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28936. effect.setFloat("exposure", _this.exposure);
  28937. effect.setFloat("decay", _this.decay);
  28938. effect.setFloat("weight", _this.weight);
  28939. effect.setFloat("density", _this.density);
  28940. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28941. };
  28942. }
  28943. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28944. var mesh = subMesh.getMesh();
  28945. var defines = [];
  28946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28947. var material = subMesh.getMaterial();
  28948. // Render this.mesh as default
  28949. if (mesh === this.mesh) {
  28950. defines.push("#define BASIC_RENDER");
  28951. }
  28952. // Alpha test
  28953. if (material) {
  28954. if (material.needAlphaTesting() || mesh === this.mesh)
  28955. defines.push("#define ALPHATEST");
  28956. if (material.opacityTexture !== undefined)
  28957. defines.push("#define OPACITY");
  28958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28959. attribs.push(BABYLON.VertexBuffer.UVKind);
  28960. defines.push("#define UV1");
  28961. }
  28962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28963. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28964. defines.push("#define UV2");
  28965. }
  28966. }
  28967. // Bones
  28968. if (mesh.useBones) {
  28969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28971. defines.push("#define BONES");
  28972. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28973. }
  28974. // Instances
  28975. if (useInstances) {
  28976. defines.push("#define INSTANCES");
  28977. attribs.push("world0");
  28978. attribs.push("world1");
  28979. attribs.push("world2");
  28980. attribs.push("world3");
  28981. }
  28982. // Get correct effect
  28983. var join = defines.join("\n");
  28984. if (this._cachedDefines !== join) {
  28985. this._cachedDefines = join;
  28986. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28987. }
  28988. return this._volumetricLightScatteringPass.isReady();
  28989. };
  28990. /**
  28991. * Sets the new light position for light scattering effect
  28992. * @param {BABYLON.Vector3} The new custom light position
  28993. */
  28994. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28995. this._customMeshPosition = position;
  28996. };
  28997. /**
  28998. * Returns the light position for light scattering effect
  28999. * @return {BABYLON.Vector3} The custom light position
  29000. */
  29001. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29002. return this._customMeshPosition;
  29003. };
  29004. /**
  29005. * Disposes the internal assets and detaches the post-process from the camera
  29006. */
  29007. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29008. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29009. if (rttIndex !== -1) {
  29010. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29011. }
  29012. this._volumetricLightScatteringRTT.dispose();
  29013. _super.prototype.dispose.call(this, camera);
  29014. };
  29015. /**
  29016. * Returns the render target texture used by the post-process
  29017. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29018. */
  29019. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29020. return this._volumetricLightScatteringRTT;
  29021. };
  29022. // Private methods
  29023. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29024. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29025. return true;
  29026. }
  29027. return false;
  29028. };
  29029. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29030. var _this = this;
  29031. var engine = scene.getEngine();
  29032. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29033. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29034. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29035. this._volumetricLightScatteringRTT.renderList = null;
  29036. this._volumetricLightScatteringRTT.renderParticles = false;
  29037. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29038. // Custom render function for submeshes
  29039. var renderSubMesh = function (subMesh) {
  29040. var mesh = subMesh.getRenderingMesh();
  29041. if (_this._meshExcluded(mesh)) {
  29042. return;
  29043. }
  29044. var scene = mesh.getScene();
  29045. var engine = scene.getEngine();
  29046. // Culling
  29047. engine.setState(subMesh.getMaterial().backFaceCulling);
  29048. // Managing instances
  29049. var batch = mesh._getInstancesRenderList(subMesh._id);
  29050. if (batch.mustReturn) {
  29051. return;
  29052. }
  29053. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29054. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29055. engine.enableEffect(_this._volumetricLightScatteringPass);
  29056. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29057. var material = subMesh.getMaterial();
  29058. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29059. // Alpha test
  29060. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29061. var alphaTexture = material.getAlphaTestTexture();
  29062. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29063. if (_this.mesh.material && alphaTexture)
  29064. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29065. if (material.opacityTexture !== undefined)
  29066. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29067. }
  29068. // Bones
  29069. if (mesh.useBones) {
  29070. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29071. }
  29072. // Draw
  29073. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29074. }
  29075. };
  29076. // Render target texture callbacks
  29077. var savedSceneClearColor;
  29078. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29079. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29080. savedSceneClearColor = scene.clearColor;
  29081. scene.clearColor = sceneClearColor;
  29082. };
  29083. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29084. scene.clearColor = savedSceneClearColor;
  29085. };
  29086. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29087. var index;
  29088. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29089. renderSubMesh(opaqueSubMeshes.data[index]);
  29090. }
  29091. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29092. renderSubMesh(alphaTestSubMeshes.data[index]);
  29093. }
  29094. for (index = 0; index < transparentSubMeshes.length; index++) {
  29095. renderSubMesh(transparentSubMeshes.data[index]);
  29096. }
  29097. };
  29098. };
  29099. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29100. var transform = scene.getTransformMatrix();
  29101. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29102. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29103. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29104. if (this.invert)
  29105. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29106. };
  29107. // Static methods
  29108. /**
  29109. * Creates a default mesh for the Volumeric Light Scattering post-process
  29110. * @param {string} The mesh name
  29111. * @param {BABYLON.Scene} The scene where to create the mesh
  29112. * @return {BABYLON.Mesh} the default mesh
  29113. */
  29114. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29115. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29116. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29117. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29118. return mesh;
  29119. };
  29120. return VolumetricLightScatteringPostProcess;
  29121. })(BABYLON.PostProcess);
  29122. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29123. })(BABYLON || (BABYLON = {}));
  29124. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29125. var BABYLON;
  29126. (function (BABYLON) {
  29127. var LensRenderingPipeline = (function (_super) {
  29128. __extends(LensRenderingPipeline, _super);
  29129. /**
  29130. * @constructor
  29131. * @param {string} name - The rendering pipeline name
  29132. * @param {object} parameters - An object containing all parameters (see below)
  29133. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29134. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29135. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29136. Effect parameters are as follow:
  29137. {
  29138. chromatic_aberration: number; // from 0 to x (1 for realism)
  29139. edge_blur: number; // from 0 to x (1 for realism)
  29140. distortion: number; // from 0 to x (1 for realism)
  29141. grain_amount: number; // from 0 to 1
  29142. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29143. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29144. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29145. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29146. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29147. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29148. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29149. }
  29150. Note: if an effect parameter is unset, effect is disabled
  29151. */
  29152. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29153. var _this = this;
  29154. if (ratio === void 0) { ratio = 1.0; }
  29155. _super.call(this, scene.getEngine(), name);
  29156. // Lens effects can be of the following:
  29157. // - chromatic aberration (slight shift of RGB colors)
  29158. // - blur on the edge of the lens
  29159. // - lens distortion
  29160. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29161. // - grain/dust-on-lens effect
  29162. // Two additional texture samplers are needed:
  29163. // - depth map (for depth-of-field)
  29164. // - grain texture
  29165. /**
  29166. * The chromatic aberration PostProcess id in the pipeline
  29167. * @type {string}
  29168. */
  29169. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29170. /**
  29171. * The depth-of-field PostProcess id in the pipeline
  29172. * @type {string}
  29173. */
  29174. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29175. this._scene = scene;
  29176. // Fetch texture samplers
  29177. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29178. if (parameters.grain_texture) {
  29179. this._grainTexture = parameters.grain_texture;
  29180. }
  29181. else {
  29182. this._createGrainTexture();
  29183. }
  29184. // save parameters
  29185. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29186. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29187. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29188. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29189. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29190. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29191. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29192. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29193. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29194. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29195. // Create effects
  29196. this._createChromaticAberrationPostProcess(ratio);
  29197. this._createDepthOfFieldPostProcess(ratio);
  29198. // Set up pipeline
  29199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29200. return _this._chromaticAberrationPostProcess;
  29201. }, true));
  29202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29203. return _this._depthOfFieldPostProcess;
  29204. }, true));
  29205. // Finish
  29206. scene.postProcessRenderPipelineManager.addPipeline(this);
  29207. if (cameras) {
  29208. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29209. }
  29210. }
  29211. // public methods
  29212. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29213. this._edgeBlur = amount;
  29214. };
  29215. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29216. this._edgeBlur = 0;
  29217. };
  29218. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29219. this._grainAmount = amount;
  29220. };
  29221. LensRenderingPipeline.prototype.disableGrain = function () {
  29222. this._grainAmount = 0;
  29223. };
  29224. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29225. this._chromaticAberration = amount;
  29226. };
  29227. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29228. this._chromaticAberration = 0;
  29229. };
  29230. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29231. this._distortion = amount;
  29232. };
  29233. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29234. this._distortion = 0;
  29235. };
  29236. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29237. this._highlightsGain = amount;
  29238. };
  29239. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29240. this._highlightsThreshold = amount;
  29241. };
  29242. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29243. this._dofDepth = amount;
  29244. };
  29245. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29246. this._dofDepth = -1;
  29247. };
  29248. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29249. this._dofAperture = amount;
  29250. };
  29251. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29252. this._dofPentagon = true;
  29253. };
  29254. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29255. this._dofPentagon = false;
  29256. };
  29257. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29258. this._blurNoise = true;
  29259. };
  29260. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29261. this._blurNoise = false;
  29262. };
  29263. /**
  29264. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29265. */
  29266. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29267. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29268. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29269. this._chromaticAberrationPostProcess = undefined;
  29270. this._depthOfFieldPostProcess = undefined;
  29271. this._grainTexture.dispose();
  29272. if (disableDepthRender)
  29273. this._scene.disableDepthRenderer();
  29274. };
  29275. // colors shifting and distortion
  29276. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29277. var _this = this;
  29278. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29279. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29280. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29281. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29282. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29283. };
  29284. };
  29285. // colors shifting and distortion
  29286. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29287. var _this = this;
  29288. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29289. "gain",
  29290. "threshold",
  29291. "focus_depth",
  29292. "aperture",
  29293. "pentagon",
  29294. "maxZ",
  29295. "edge_blur",
  29296. "chromatic_aberration",
  29297. "distortion",
  29298. "blur_noise",
  29299. "grain_amount",
  29300. "screen_width",
  29301. "screen_height"
  29302. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29303. this._depthOfFieldPostProcess.onApply = function (effect) {
  29304. effect.setBool('pentagon', _this._dofPentagon);
  29305. effect.setBool('blur_noise', _this._blurNoise);
  29306. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29307. effect.setFloat('grain_amount', _this._grainAmount);
  29308. effect.setTexture("depthSampler", _this._depthTexture);
  29309. effect.setTexture("grainSampler", _this._grainTexture);
  29310. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29311. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29312. effect.setFloat('distortion', _this._distortion);
  29313. effect.setFloat('focus_depth', _this._dofDepth);
  29314. effect.setFloat('aperture', _this._dofAperture);
  29315. effect.setFloat('gain', _this._highlightsGain);
  29316. effect.setFloat('threshold', _this._highlightsThreshold);
  29317. effect.setFloat('edge_blur', _this._edgeBlur);
  29318. };
  29319. };
  29320. // creates a black and white random noise texture, 512x512
  29321. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29322. var size = 512;
  29323. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29324. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29325. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29326. var context = this._grainTexture.getContext();
  29327. var rand = function (min, max) {
  29328. return Math.random() * (max - min) + min;
  29329. };
  29330. var value;
  29331. for (var x = 0; x < size; x++) {
  29332. for (var y = 0; y < size; y++) {
  29333. value = Math.floor(rand(0.42, 0.58) * 255);
  29334. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29335. context.fillRect(x, y, 1, 1);
  29336. }
  29337. }
  29338. this._grainTexture.update(false);
  29339. };
  29340. return LensRenderingPipeline;
  29341. })(BABYLON.PostProcessRenderPipeline);
  29342. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29343. })(BABYLON || (BABYLON = {}));
  29344. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map