babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var hw = 2.0 / width;
  1718. var hh = 2.0 / height;
  1719. var id = 1.0 / (zfar - znear);
  1720. var nid = znear / (znear - zfar);
  1721. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1722. };
  1723. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1724. var matrix = Matrix.Zero();
  1725. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1726. return matrix;
  1727. };
  1728. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1729. result.m[0] = 2.0 / (right - left);
  1730. result.m[1] = result.m[2] = result.m[3] = 0;
  1731. result.m[5] = 2.0 / (top - bottom);
  1732. result.m[4] = result.m[6] = result.m[7] = 0;
  1733. result.m[10] = -1.0 / (znear - zfar);
  1734. result.m[8] = result.m[9] = result.m[11] = 0;
  1735. result.m[12] = (left + right) / (left - right);
  1736. result.m[13] = (top + bottom) / (bottom - top);
  1737. result.m[14] = znear / (znear - zfar);
  1738. result.m[15] = 1.0;
  1739. };
  1740. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1741. var matrix = Matrix.Zero();
  1742. matrix.m[0] = (2.0 * znear) / width;
  1743. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1744. matrix.m[5] = (2.0 * znear) / height;
  1745. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1746. matrix.m[10] = -zfar / (znear - zfar);
  1747. matrix.m[8] = matrix.m[9] = 0.0;
  1748. matrix.m[11] = 1.0;
  1749. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1750. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1751. return matrix;
  1752. };
  1753. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1754. var matrix = Matrix.Zero();
  1755. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1759. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1760. var tan = 1.0 / (Math.tan(fov * 0.5));
  1761. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1762. if (v_fixed) {
  1763. result.m[0] = tan / aspect;
  1764. }
  1765. else {
  1766. result.m[0] = tan;
  1767. }
  1768. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1769. if (v_fixed) {
  1770. result.m[5] = tan;
  1771. }
  1772. else {
  1773. result.m[5] = tan * aspect;
  1774. }
  1775. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1776. result.m[8] = result.m[9] = 0.0;
  1777. result.m[10] = -zfar / (znear - zfar);
  1778. result.m[11] = 1.0;
  1779. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1780. result.m[14] = (znear * zfar) / (znear - zfar);
  1781. };
  1782. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1783. var cw = viewport.width;
  1784. var ch = viewport.height;
  1785. var cx = viewport.x;
  1786. var cy = viewport.y;
  1787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1788. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1789. };
  1790. Matrix.Transpose = function (matrix) {
  1791. var result = new Matrix();
  1792. result.m[0] = matrix.m[0];
  1793. result.m[1] = matrix.m[4];
  1794. result.m[2] = matrix.m[8];
  1795. result.m[3] = matrix.m[12];
  1796. result.m[4] = matrix.m[1];
  1797. result.m[5] = matrix.m[5];
  1798. result.m[6] = matrix.m[9];
  1799. result.m[7] = matrix.m[13];
  1800. result.m[8] = matrix.m[2];
  1801. result.m[9] = matrix.m[6];
  1802. result.m[10] = matrix.m[10];
  1803. result.m[11] = matrix.m[14];
  1804. result.m[12] = matrix.m[3];
  1805. result.m[13] = matrix.m[7];
  1806. result.m[14] = matrix.m[11];
  1807. result.m[15] = matrix.m[15];
  1808. return result;
  1809. };
  1810. Matrix.Reflection = function (plane) {
  1811. var matrix = new Matrix();
  1812. Matrix.ReflectionToRef(plane, matrix);
  1813. return matrix;
  1814. };
  1815. Matrix.ReflectionToRef = function (plane, result) {
  1816. plane.normalize();
  1817. var x = plane.normal.x;
  1818. var y = plane.normal.y;
  1819. var z = plane.normal.z;
  1820. var temp = -2 * x;
  1821. var temp2 = -2 * y;
  1822. var temp3 = -2 * z;
  1823. result.m[0] = (temp * x) + 1;
  1824. result.m[1] = temp2 * x;
  1825. result.m[2] = temp3 * x;
  1826. result.m[3] = 0.0;
  1827. result.m[4] = temp * y;
  1828. result.m[5] = (temp2 * y) + 1;
  1829. result.m[6] = temp3 * y;
  1830. result.m[7] = 0.0;
  1831. result.m[8] = temp * z;
  1832. result.m[9] = temp2 * z;
  1833. result.m[10] = (temp3 * z) + 1;
  1834. result.m[11] = 0.0;
  1835. result.m[12] = temp * plane.d;
  1836. result.m[13] = temp2 * plane.d;
  1837. result.m[14] = temp3 * plane.d;
  1838. result.m[15] = 1.0;
  1839. };
  1840. Matrix._tempQuaternion = new Quaternion();
  1841. Matrix._xAxis = Vector3.Zero();
  1842. Matrix._yAxis = Vector3.Zero();
  1843. Matrix._zAxis = Vector3.Zero();
  1844. return Matrix;
  1845. })();
  1846. BABYLON.Matrix = Matrix;
  1847. var Plane = (function () {
  1848. function Plane(a, b, c, d) {
  1849. this.normal = new Vector3(a, b, c);
  1850. this.d = d;
  1851. }
  1852. Plane.prototype.asArray = function () {
  1853. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1854. };
  1855. // Methods
  1856. Plane.prototype.clone = function () {
  1857. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1858. };
  1859. Plane.prototype.normalize = function () {
  1860. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1861. var magnitude = 0;
  1862. if (norm !== 0) {
  1863. magnitude = 1.0 / norm;
  1864. }
  1865. this.normal.x *= magnitude;
  1866. this.normal.y *= magnitude;
  1867. this.normal.z *= magnitude;
  1868. this.d *= magnitude;
  1869. return this;
  1870. };
  1871. Plane.prototype.transform = function (transformation) {
  1872. var transposedMatrix = Matrix.Transpose(transformation);
  1873. var x = this.normal.x;
  1874. var y = this.normal.y;
  1875. var z = this.normal.z;
  1876. var d = this.d;
  1877. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1878. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1879. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1880. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1881. return new Plane(normalX, normalY, normalZ, finalD);
  1882. };
  1883. Plane.prototype.dotCoordinate = function (point) {
  1884. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1885. };
  1886. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1887. var x1 = point2.x - point1.x;
  1888. var y1 = point2.y - point1.y;
  1889. var z1 = point2.z - point1.z;
  1890. var x2 = point3.x - point1.x;
  1891. var y2 = point3.y - point1.y;
  1892. var z2 = point3.z - point1.z;
  1893. var yz = (y1 * z2) - (z1 * y2);
  1894. var xz = (z1 * x2) - (x1 * z2);
  1895. var xy = (x1 * y2) - (y1 * x2);
  1896. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1897. var invPyth;
  1898. if (pyth !== 0) {
  1899. invPyth = 1.0 / pyth;
  1900. }
  1901. else {
  1902. invPyth = 0;
  1903. }
  1904. this.normal.x = yz * invPyth;
  1905. this.normal.y = xz * invPyth;
  1906. this.normal.z = xy * invPyth;
  1907. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1908. return this;
  1909. };
  1910. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1911. var dot = Vector3.Dot(this.normal, direction);
  1912. return (dot <= epsilon);
  1913. };
  1914. Plane.prototype.signedDistanceTo = function (point) {
  1915. return Vector3.Dot(point, this.normal) + this.d;
  1916. };
  1917. // Statics
  1918. Plane.FromArray = function (array) {
  1919. return new Plane(array[0], array[1], array[2], array[3]);
  1920. };
  1921. Plane.FromPoints = function (point1, point2, point3) {
  1922. var result = new Plane(0, 0, 0, 0);
  1923. result.copyFromPoints(point1, point2, point3);
  1924. return result;
  1925. };
  1926. Plane.FromPositionAndNormal = function (origin, normal) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. normal.normalize();
  1929. result.normal = normal;
  1930. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1931. return result;
  1932. };
  1933. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1934. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1935. return Vector3.Dot(point, normal) + d;
  1936. };
  1937. return Plane;
  1938. })();
  1939. BABYLON.Plane = Plane;
  1940. var Viewport = (function () {
  1941. function Viewport(x, y, width, height) {
  1942. this.x = x;
  1943. this.y = y;
  1944. this.width = width;
  1945. this.height = height;
  1946. }
  1947. Viewport.prototype.toGlobal = function (engine) {
  1948. var width = engine.getRenderWidth();
  1949. var height = engine.getRenderHeight();
  1950. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1951. };
  1952. return Viewport;
  1953. })();
  1954. BABYLON.Viewport = Viewport;
  1955. var Frustum = (function () {
  1956. function Frustum() {
  1957. }
  1958. Frustum.GetPlanes = function (transform) {
  1959. var frustumPlanes = [];
  1960. for (var index = 0; index < 6; index++) {
  1961. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1962. }
  1963. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1964. return frustumPlanes;
  1965. };
  1966. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1967. // Near
  1968. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1969. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1970. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1971. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1972. frustumPlanes[0].normalize();
  1973. // Far
  1974. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1975. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1976. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1977. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1978. frustumPlanes[1].normalize();
  1979. // Left
  1980. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1981. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1982. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1983. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1984. frustumPlanes[2].normalize();
  1985. // Right
  1986. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1987. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1988. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1989. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1990. frustumPlanes[3].normalize();
  1991. // Top
  1992. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1993. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1994. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1995. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1996. frustumPlanes[4].normalize();
  1997. // Bottom
  1998. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1999. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2000. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2001. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2002. frustumPlanes[5].normalize();
  2003. };
  2004. return Frustum;
  2005. })();
  2006. BABYLON.Frustum = Frustum;
  2007. var Ray = (function () {
  2008. function Ray(origin, direction, length) {
  2009. if (length === void 0) { length = Number.MAX_VALUE; }
  2010. this.origin = origin;
  2011. this.direction = direction;
  2012. this.length = length;
  2013. }
  2014. // Methods
  2015. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2016. var d = 0.0;
  2017. var maxValue = Number.MAX_VALUE;
  2018. if (Math.abs(this.direction.x) < 0.0000001) {
  2019. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2020. return false;
  2021. }
  2022. }
  2023. else {
  2024. var inv = 1.0 / this.direction.x;
  2025. var min = (minimum.x - this.origin.x) * inv;
  2026. var max = (maximum.x - this.origin.x) * inv;
  2027. if (max === -Infinity) {
  2028. max = Infinity;
  2029. }
  2030. if (min > max) {
  2031. var temp = min;
  2032. min = max;
  2033. max = temp;
  2034. }
  2035. d = Math.max(min, d);
  2036. maxValue = Math.min(max, maxValue);
  2037. if (d > maxValue) {
  2038. return false;
  2039. }
  2040. }
  2041. if (Math.abs(this.direction.y) < 0.0000001) {
  2042. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2043. return false;
  2044. }
  2045. }
  2046. else {
  2047. inv = 1.0 / this.direction.y;
  2048. min = (minimum.y - this.origin.y) * inv;
  2049. max = (maximum.y - this.origin.y) * inv;
  2050. if (max === -Infinity) {
  2051. max = Infinity;
  2052. }
  2053. if (min > max) {
  2054. temp = min;
  2055. min = max;
  2056. max = temp;
  2057. }
  2058. d = Math.max(min, d);
  2059. maxValue = Math.min(max, maxValue);
  2060. if (d > maxValue) {
  2061. return false;
  2062. }
  2063. }
  2064. if (Math.abs(this.direction.z) < 0.0000001) {
  2065. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2066. return false;
  2067. }
  2068. }
  2069. else {
  2070. inv = 1.0 / this.direction.z;
  2071. min = (minimum.z - this.origin.z) * inv;
  2072. max = (maximum.z - this.origin.z) * inv;
  2073. if (max === -Infinity) {
  2074. max = Infinity;
  2075. }
  2076. if (min > max) {
  2077. temp = min;
  2078. min = max;
  2079. max = temp;
  2080. }
  2081. d = Math.max(min, d);
  2082. maxValue = Math.min(max, maxValue);
  2083. if (d > maxValue) {
  2084. return false;
  2085. }
  2086. }
  2087. return true;
  2088. };
  2089. Ray.prototype.intersectsBox = function (box) {
  2090. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2091. };
  2092. Ray.prototype.intersectsSphere = function (sphere) {
  2093. var x = sphere.center.x - this.origin.x;
  2094. var y = sphere.center.y - this.origin.y;
  2095. var z = sphere.center.z - this.origin.z;
  2096. var pyth = (x * x) + (y * y) + (z * z);
  2097. var rr = sphere.radius * sphere.radius;
  2098. if (pyth <= rr) {
  2099. return true;
  2100. }
  2101. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2102. if (dot < 0.0) {
  2103. return false;
  2104. }
  2105. var temp = pyth - (dot * dot);
  2106. return temp <= rr;
  2107. };
  2108. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2109. if (!this._edge1) {
  2110. this._edge1 = Vector3.Zero();
  2111. this._edge2 = Vector3.Zero();
  2112. this._pvec = Vector3.Zero();
  2113. this._tvec = Vector3.Zero();
  2114. this._qvec = Vector3.Zero();
  2115. }
  2116. vertex1.subtractToRef(vertex0, this._edge1);
  2117. vertex2.subtractToRef(vertex0, this._edge2);
  2118. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2119. var det = Vector3.Dot(this._edge1, this._pvec);
  2120. if (det === 0) {
  2121. return null;
  2122. }
  2123. var invdet = 1 / det;
  2124. this.origin.subtractToRef(vertex0, this._tvec);
  2125. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2126. if (bu < 0 || bu > 1.0) {
  2127. return null;
  2128. }
  2129. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2130. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2131. if (bv < 0 || bu + bv > 1.0) {
  2132. return null;
  2133. }
  2134. //check if the distance is longer than the predefined length.
  2135. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2136. if (distance > this.length) {
  2137. return null;
  2138. }
  2139. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2140. };
  2141. // Statics
  2142. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2143. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2144. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2145. var direction = end.subtract(start);
  2146. direction.normalize();
  2147. return new Ray(start, direction);
  2148. };
  2149. /**
  2150. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2151. * transformed to the given world matrix.
  2152. * @param origin The origin point
  2153. * @param end The end point
  2154. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2155. */
  2156. Ray.CreateNewFromTo = function (origin, end, world) {
  2157. if (world === void 0) { world = Matrix.Identity(); }
  2158. var direction = end.subtract(origin);
  2159. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2160. direction.normalize();
  2161. return Ray.Transform(new Ray(origin, direction, length), world);
  2162. };
  2163. Ray.Transform = function (ray, matrix) {
  2164. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2165. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2166. return new Ray(newOrigin, newDirection, ray.length);
  2167. };
  2168. return Ray;
  2169. })();
  2170. BABYLON.Ray = Ray;
  2171. (function (Space) {
  2172. Space[Space["LOCAL"] = 0] = "LOCAL";
  2173. Space[Space["WORLD"] = 1] = "WORLD";
  2174. })(BABYLON.Space || (BABYLON.Space = {}));
  2175. var Space = BABYLON.Space;
  2176. var Axis = (function () {
  2177. function Axis() {
  2178. }
  2179. Axis.X = new Vector3(1, 0, 0);
  2180. Axis.Y = new Vector3(0, 1, 0);
  2181. Axis.Z = new Vector3(0, 0, 1);
  2182. return Axis;
  2183. })();
  2184. BABYLON.Axis = Axis;
  2185. ;
  2186. var BezierCurve = (function () {
  2187. function BezierCurve() {
  2188. }
  2189. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2190. // Extract X (which is equal to time here)
  2191. var f0 = 1 - 3 * x2 + 3 * x1;
  2192. var f1 = 3 * x2 - 6 * x1;
  2193. var f2 = 3 * x1;
  2194. var refinedT = t;
  2195. for (var i = 0; i < 5; i++) {
  2196. var refinedT2 = refinedT * refinedT;
  2197. var refinedT3 = refinedT2 * refinedT;
  2198. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2199. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2200. refinedT -= (x - t) * slope;
  2201. refinedT = Math.min(1, Math.max(0, refinedT));
  2202. }
  2203. // Resolve cubic bezier for the given x
  2204. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2205. };
  2206. return BezierCurve;
  2207. })();
  2208. BABYLON.BezierCurve = BezierCurve;
  2209. (function (Orientation) {
  2210. Orientation[Orientation["CW"] = 0] = "CW";
  2211. Orientation[Orientation["CCW"] = 1] = "CCW";
  2212. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2213. var Orientation = BABYLON.Orientation;
  2214. var Angle = (function () {
  2215. function Angle(radians) {
  2216. var _this = this;
  2217. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2218. this.radians = function () { return _this._radians; };
  2219. this._radians = radians;
  2220. if (this._radians < 0)
  2221. this._radians += (2 * Math.PI);
  2222. }
  2223. Angle.BetweenTwoPoints = function (a, b) {
  2224. var delta = b.subtract(a);
  2225. var theta = Math.atan2(delta.y, delta.x);
  2226. return new Angle(theta);
  2227. };
  2228. Angle.FromRadians = function (radians) {
  2229. return new Angle(radians);
  2230. };
  2231. Angle.FromDegrees = function (degrees) {
  2232. return new Angle(degrees * Math.PI / 180);
  2233. };
  2234. return Angle;
  2235. })();
  2236. BABYLON.Angle = Angle;
  2237. var Arc2 = (function () {
  2238. function Arc2(startPoint, midPoint, endPoint) {
  2239. this.startPoint = startPoint;
  2240. this.midPoint = midPoint;
  2241. this.endPoint = endPoint;
  2242. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2243. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2244. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2245. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2246. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2247. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2248. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2249. var a1 = this.startAngle.degrees();
  2250. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2251. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2252. // angles correction
  2253. if (a2 - a1 > +180.0)
  2254. a2 -= 360.0;
  2255. if (a2 - a1 < -180.0)
  2256. a2 += 360.0;
  2257. if (a3 - a2 > +180.0)
  2258. a3 -= 360.0;
  2259. if (a3 - a2 < -180.0)
  2260. a3 += 360.0;
  2261. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2262. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2263. }
  2264. return Arc2;
  2265. })();
  2266. BABYLON.Arc2 = Arc2;
  2267. var PathCursor = (function () {
  2268. function PathCursor(path) {
  2269. this.path = path;
  2270. this._onchange = new Array();
  2271. this.value = 0;
  2272. this.animations = new Array();
  2273. }
  2274. PathCursor.prototype.getPoint = function () {
  2275. var point = this.path.getPointAtLengthPosition(this.value);
  2276. return new Vector3(point.x, 0, point.y);
  2277. };
  2278. PathCursor.prototype.moveAhead = function (step) {
  2279. if (step === void 0) { step = 0.002; }
  2280. this.move(step);
  2281. return this;
  2282. };
  2283. PathCursor.prototype.moveBack = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(-step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.move = function (step) {
  2289. if (Math.abs(step) > 1) {
  2290. throw "step size should be less than 1.";
  2291. }
  2292. this.value += step;
  2293. this.ensureLimits();
  2294. this.raiseOnChange();
  2295. return this;
  2296. };
  2297. PathCursor.prototype.ensureLimits = function () {
  2298. while (this.value > 1) {
  2299. this.value -= 1;
  2300. }
  2301. while (this.value < 0) {
  2302. this.value += 1;
  2303. }
  2304. return this;
  2305. };
  2306. // used by animation engine
  2307. PathCursor.prototype.markAsDirty = function (propertyName) {
  2308. this.ensureLimits();
  2309. this.raiseOnChange();
  2310. return this;
  2311. };
  2312. PathCursor.prototype.raiseOnChange = function () {
  2313. var _this = this;
  2314. this._onchange.forEach(function (f) { return f(_this); });
  2315. return this;
  2316. };
  2317. PathCursor.prototype.onchange = function (f) {
  2318. this._onchange.push(f);
  2319. return this;
  2320. };
  2321. return PathCursor;
  2322. })();
  2323. BABYLON.PathCursor = PathCursor;
  2324. var Path2 = (function () {
  2325. function Path2(x, y) {
  2326. this._points = [];
  2327. this._length = 0;
  2328. this.closed = false;
  2329. this._points.push(new Vector2(x, y));
  2330. }
  2331. Path2.prototype.addLineTo = function (x, y) {
  2332. if (closed) {
  2333. BABYLON.Tools.Error("cannot add lines to closed paths");
  2334. return this;
  2335. }
  2336. var newPoint = new Vector2(x, y);
  2337. var previousPoint = this._points[this._points.length - 1];
  2338. this._points.push(newPoint);
  2339. this._length += newPoint.subtract(previousPoint).length();
  2340. return this;
  2341. };
  2342. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2343. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2344. if (closed) {
  2345. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2346. return this;
  2347. }
  2348. var startPoint = this._points[this._points.length - 1];
  2349. var midPoint = new Vector2(midX, midY);
  2350. var endPoint = new Vector2(endX, endY);
  2351. var arc = new Arc2(startPoint, midPoint, endPoint);
  2352. var increment = arc.angle.radians() / numberOfSegments;
  2353. if (arc.orientation === 0 /* CW */)
  2354. increment *= -1;
  2355. var currentAngle = arc.startAngle.radians() + increment;
  2356. for (var i = 0; i < numberOfSegments; i++) {
  2357. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2358. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2359. this.addLineTo(x, y);
  2360. currentAngle += increment;
  2361. }
  2362. return this;
  2363. };
  2364. Path2.prototype.close = function () {
  2365. this.closed = true;
  2366. return this;
  2367. };
  2368. Path2.prototype.length = function () {
  2369. var result = this._length;
  2370. if (!this.closed) {
  2371. var lastPoint = this._points[this._points.length - 1];
  2372. var firstPoint = this._points[0];
  2373. result += (firstPoint.subtract(lastPoint).length());
  2374. }
  2375. return result;
  2376. };
  2377. Path2.prototype.getPoints = function () {
  2378. return this._points;
  2379. };
  2380. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2381. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2382. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2383. return Vector2.Zero();
  2384. }
  2385. var lengthPosition = normalizedLengthPosition * this.length();
  2386. var previousOffset = 0;
  2387. for (var i = 0; i < this._points.length; i++) {
  2388. var j = (i + 1) % this._points.length;
  2389. var a = this._points[i];
  2390. var b = this._points[j];
  2391. var bToA = b.subtract(a);
  2392. var nextOffset = (bToA.length() + previousOffset);
  2393. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2394. var dir = bToA.normalize();
  2395. var localOffset = lengthPosition - previousOffset;
  2396. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2397. }
  2398. previousOffset = nextOffset;
  2399. }
  2400. BABYLON.Tools.Error("internal error");
  2401. return Vector2.Zero();
  2402. };
  2403. Path2.StartingAt = function (x, y) {
  2404. return new Path2(x, y);
  2405. };
  2406. return Path2;
  2407. })();
  2408. BABYLON.Path2 = Path2;
  2409. })(BABYLON || (BABYLON = {}));
  2410. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2411. (function (BABYLON) {
  2412. // Screenshots
  2413. var screenshotCanvas;
  2414. var cloneValue = function (source, destinationObject) {
  2415. if (!source)
  2416. return null;
  2417. if (source instanceof BABYLON.Mesh) {
  2418. return null;
  2419. }
  2420. if (source instanceof BABYLON.SubMesh) {
  2421. return source.clone(destinationObject);
  2422. }
  2423. else if (source.clone) {
  2424. return source.clone();
  2425. }
  2426. return null;
  2427. };
  2428. var Tools = (function () {
  2429. function Tools() {
  2430. }
  2431. Tools.GetFilename = function (path) {
  2432. var index = path.lastIndexOf("/");
  2433. if (index < 0)
  2434. return path;
  2435. return path.substring(index + 1);
  2436. };
  2437. Tools.GetDOMTextContent = function (element) {
  2438. var result = "";
  2439. var child = element.firstChild;
  2440. while (child) {
  2441. if (child.nodeType === 3) {
  2442. result += child.textContent;
  2443. }
  2444. child = child.nextSibling;
  2445. }
  2446. return result;
  2447. };
  2448. Tools.ToDegrees = function (angle) {
  2449. return angle * 180 / Math.PI;
  2450. };
  2451. Tools.ToRadians = function (angle) {
  2452. return angle * Math.PI / 180;
  2453. };
  2454. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2455. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2456. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2457. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2458. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2459. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2460. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2461. }
  2462. return {
  2463. minimum: minimum,
  2464. maximum: maximum
  2465. };
  2466. };
  2467. Tools.ExtractMinAndMax = function (positions, start, count) {
  2468. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2469. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2470. for (var index = start; index < start + count; index++) {
  2471. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2472. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2473. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2474. }
  2475. return {
  2476. minimum: minimum,
  2477. maximum: maximum
  2478. };
  2479. };
  2480. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2481. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2482. return undefined;
  2483. return Array.isArray(obj) ? obj : [obj];
  2484. };
  2485. // Misc.
  2486. Tools.GetPointerPrefix = function () {
  2487. var eventPrefix = "pointer";
  2488. // Check if hand.js is referenced or if the browser natively supports pointer events
  2489. if (!navigator.pointerEnabled) {
  2490. eventPrefix = "mouse";
  2491. }
  2492. return eventPrefix;
  2493. };
  2494. Tools.QueueNewFrame = function (func) {
  2495. if (window.requestAnimationFrame)
  2496. window.requestAnimationFrame(func);
  2497. else if (window.msRequestAnimationFrame)
  2498. window.msRequestAnimationFrame(func);
  2499. else if (window.webkitRequestAnimationFrame)
  2500. window.webkitRequestAnimationFrame(func);
  2501. else if (window.mozRequestAnimationFrame)
  2502. window.mozRequestAnimationFrame(func);
  2503. else if (window.oRequestAnimationFrame)
  2504. window.oRequestAnimationFrame(func);
  2505. else {
  2506. window.setTimeout(func, 16);
  2507. }
  2508. };
  2509. Tools.RequestFullscreen = function (element) {
  2510. if (element.requestFullscreen)
  2511. element.requestFullscreen();
  2512. else if (element.msRequestFullscreen)
  2513. element.msRequestFullscreen();
  2514. else if (element.webkitRequestFullscreen)
  2515. element.webkitRequestFullscreen();
  2516. else if (element.mozRequestFullScreen)
  2517. element.mozRequestFullScreen();
  2518. };
  2519. Tools.ExitFullscreen = function () {
  2520. if (document.exitFullscreen) {
  2521. document.exitFullscreen();
  2522. }
  2523. else if (document.mozCancelFullScreen) {
  2524. document.mozCancelFullScreen();
  2525. }
  2526. else if (document.webkitCancelFullScreen) {
  2527. document.webkitCancelFullScreen();
  2528. }
  2529. else if (document.msCancelFullScreen) {
  2530. document.msCancelFullScreen();
  2531. }
  2532. };
  2533. // External files
  2534. Tools.CleanUrl = function (url) {
  2535. url = url.replace(/#/mg, "%23");
  2536. return url;
  2537. };
  2538. Tools.LoadImage = function (url, onload, onerror, database) {
  2539. url = Tools.CleanUrl(url);
  2540. var img = new Image();
  2541. if (url.substr(0, 5) !== "data:")
  2542. img.crossOrigin = 'anonymous';
  2543. img.onload = function () {
  2544. onload(img);
  2545. };
  2546. img.onerror = function (err) {
  2547. onerror(img, err);
  2548. };
  2549. var noIndexedDB = function () {
  2550. img.src = url;
  2551. };
  2552. var loadFromIndexedDB = function () {
  2553. database.loadImageFromDB(url, img);
  2554. };
  2555. //ANY database to do!
  2556. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2557. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2558. }
  2559. else {
  2560. if (url.indexOf("file:") === -1) {
  2561. noIndexedDB();
  2562. }
  2563. else {
  2564. try {
  2565. var textureName = url.substring(5);
  2566. var blobURL;
  2567. try {
  2568. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2569. }
  2570. catch (ex) {
  2571. // Chrome doesn't support oneTimeOnly parameter
  2572. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2573. }
  2574. img.src = blobURL;
  2575. }
  2576. catch (e) {
  2577. Tools.Log("Error while trying to load texture: " + textureName);
  2578. img.src = null;
  2579. }
  2580. }
  2581. }
  2582. return img;
  2583. };
  2584. //ANY
  2585. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2586. url = Tools.CleanUrl(url);
  2587. var noIndexedDB = function () {
  2588. var request = new XMLHttpRequest();
  2589. var loadUrl = Tools.BaseUrl + url;
  2590. request.open('GET', loadUrl, true);
  2591. if (useArrayBuffer) {
  2592. request.responseType = "arraybuffer";
  2593. }
  2594. request.onprogress = progressCallBack;
  2595. request.onreadystatechange = function () {
  2596. if (request.readyState === 4) {
  2597. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2598. callback(!useArrayBuffer ? request.responseText : request.response);
  2599. }
  2600. else {
  2601. if (onError) {
  2602. onError();
  2603. }
  2604. else {
  2605. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2606. }
  2607. }
  2608. }
  2609. };
  2610. request.send(null);
  2611. };
  2612. var loadFromIndexedDB = function () {
  2613. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2614. };
  2615. if (url.indexOf("file:") !== -1) {
  2616. var fileName = url.substring(5);
  2617. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2618. }
  2619. else {
  2620. // Caching all files
  2621. if (database && database.enableSceneOffline) {
  2622. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2623. }
  2624. else {
  2625. noIndexedDB();
  2626. }
  2627. }
  2628. };
  2629. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2630. var reader = new FileReader();
  2631. reader.onload = function (e) {
  2632. //target doesn't have result from ts 1.3
  2633. callback(e.target['result']);
  2634. };
  2635. reader.onprogress = progressCallback;
  2636. reader.readAsDataURL(fileToLoad);
  2637. };
  2638. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2639. var reader = new FileReader();
  2640. reader.onload = function (e) {
  2641. //target doesn't have result from ts 1.3
  2642. callback(e.target['result']);
  2643. };
  2644. reader.onprogress = progressCallBack;
  2645. if (!useArrayBuffer) {
  2646. // Asynchronous read
  2647. reader.readAsText(fileToLoad);
  2648. }
  2649. else {
  2650. reader.readAsArrayBuffer(fileToLoad);
  2651. }
  2652. };
  2653. // Misc.
  2654. Tools.Clamp = function (value, min, max) {
  2655. if (min === void 0) { min = 0; }
  2656. if (max === void 0) { max = 1; }
  2657. return Math.min(max, Math.max(min, value));
  2658. };
  2659. // Returns -1 when value is a negative number and
  2660. // +1 when value is a positive number.
  2661. Tools.Sign = function (value) {
  2662. value = +value; // convert to a number
  2663. if (value === 0 || isNaN(value))
  2664. return value;
  2665. return value > 0 ? 1 : -1;
  2666. };
  2667. Tools.Format = function (value, decimals) {
  2668. if (decimals === void 0) { decimals = 2; }
  2669. return value.toFixed(decimals);
  2670. };
  2671. Tools.CheckExtends = function (v, min, max) {
  2672. if (v.x < min.x)
  2673. min.x = v.x;
  2674. if (v.y < min.y)
  2675. min.y = v.y;
  2676. if (v.z < min.z)
  2677. min.z = v.z;
  2678. if (v.x > max.x)
  2679. max.x = v.x;
  2680. if (v.y > max.y)
  2681. max.y = v.y;
  2682. if (v.z > max.z)
  2683. max.z = v.z;
  2684. };
  2685. Tools.WithinEpsilon = function (a, b, epsilon) {
  2686. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2687. var num = a - b;
  2688. return -epsilon <= num && num <= epsilon;
  2689. };
  2690. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2691. for (var prop in source) {
  2692. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2693. continue;
  2694. }
  2695. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2696. continue;
  2697. }
  2698. var sourceValue = source[prop];
  2699. var typeOfSourceValue = typeof sourceValue;
  2700. if (typeOfSourceValue === "function") {
  2701. continue;
  2702. }
  2703. if (typeOfSourceValue === "object") {
  2704. if (sourceValue instanceof Array) {
  2705. destination[prop] = [];
  2706. if (sourceValue.length > 0) {
  2707. if (typeof sourceValue[0] == "object") {
  2708. for (var index = 0; index < sourceValue.length; index++) {
  2709. var clonedValue = cloneValue(sourceValue[index], destination);
  2710. if (destination[prop].indexOf(clonedValue) === -1) {
  2711. destination[prop].push(clonedValue);
  2712. }
  2713. }
  2714. }
  2715. else {
  2716. destination[prop] = sourceValue.slice(0);
  2717. }
  2718. }
  2719. }
  2720. else {
  2721. destination[prop] = cloneValue(sourceValue, destination);
  2722. }
  2723. }
  2724. else {
  2725. destination[prop] = sourceValue;
  2726. }
  2727. }
  2728. };
  2729. Tools.IsEmpty = function (obj) {
  2730. for (var i in obj) {
  2731. return false;
  2732. }
  2733. return true;
  2734. };
  2735. Tools.RegisterTopRootEvents = function (events) {
  2736. for (var index = 0; index < events.length; index++) {
  2737. var event = events[index];
  2738. window.addEventListener(event.name, event.handler, false);
  2739. try {
  2740. if (window.parent) {
  2741. window.parent.addEventListener(event.name, event.handler, false);
  2742. }
  2743. }
  2744. catch (e) {
  2745. }
  2746. }
  2747. };
  2748. Tools.UnregisterTopRootEvents = function (events) {
  2749. for (var index = 0; index < events.length; index++) {
  2750. var event = events[index];
  2751. window.removeEventListener(event.name, event.handler);
  2752. try {
  2753. if (window.parent) {
  2754. window.parent.removeEventListener(event.name, event.handler);
  2755. }
  2756. }
  2757. catch (e) {
  2758. }
  2759. }
  2760. };
  2761. Tools.CreateScreenshot = function (engine, camera, size) {
  2762. var width;
  2763. var height;
  2764. var scene = camera.getScene();
  2765. var previousCamera = null;
  2766. if (scene.activeCamera !== camera) {
  2767. previousCamera = scene.activeCamera;
  2768. scene.activeCamera = camera;
  2769. }
  2770. //If a precision value is specified
  2771. if (size.precision) {
  2772. width = Math.round(engine.getRenderWidth() * size.precision);
  2773. height = Math.round(width / engine.getAspectRatio(camera));
  2774. size = { width: width, height: height };
  2775. }
  2776. else if (size.width && size.height) {
  2777. width = size.width;
  2778. height = size.height;
  2779. }
  2780. else if (size.width && !size.height) {
  2781. width = size.width;
  2782. height = Math.round(width / engine.getAspectRatio(camera));
  2783. size = { width: width, height: height };
  2784. }
  2785. else if (size.height && !size.width) {
  2786. height = size.height;
  2787. width = Math.round(height * engine.getAspectRatio(camera));
  2788. size = { width: width, height: height };
  2789. }
  2790. else if (!isNaN(size)) {
  2791. height = size;
  2792. width = size;
  2793. }
  2794. else {
  2795. Tools.Error("Invalid 'size' parameter !");
  2796. return;
  2797. }
  2798. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2799. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2800. texture.renderList = scene.meshes;
  2801. texture.onAfterRender = function () {
  2802. // Read the contents of the framebuffer
  2803. var numberOfChannelsByLine = width * 4;
  2804. var halfHeight = height / 2;
  2805. //Reading datas from WebGL
  2806. var data = engine.readPixels(0, 0, width, height);
  2807. for (var i = 0; i < halfHeight; i++) {
  2808. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2809. var currentCell = j + i * numberOfChannelsByLine;
  2810. var targetLine = height - i - 1;
  2811. var targetCell = j + targetLine * numberOfChannelsByLine;
  2812. var temp = data[currentCell];
  2813. data[currentCell] = data[targetCell];
  2814. data[targetCell] = temp;
  2815. }
  2816. }
  2817. // Create a 2D canvas to store the result
  2818. if (!screenshotCanvas) {
  2819. screenshotCanvas = document.createElement('canvas');
  2820. }
  2821. screenshotCanvas.width = width;
  2822. screenshotCanvas.height = height;
  2823. var context = screenshotCanvas.getContext('2d');
  2824. // Copy the pixels to a 2D canvas
  2825. var imageData = context.createImageData(width, height);
  2826. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2827. var data = imageData.data;
  2828. data.set(data);
  2829. context.putImageData(imageData, 0, 0);
  2830. var base64Image = screenshotCanvas.toDataURL();
  2831. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2832. if (("download" in document.createElement("a"))) {
  2833. var a = window.document.createElement("a");
  2834. a.href = base64Image;
  2835. var date = new Date();
  2836. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2837. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2838. window.document.body.appendChild(a);
  2839. a.addEventListener("click", function () {
  2840. a.parentElement.removeChild(a);
  2841. });
  2842. a.click();
  2843. }
  2844. else {
  2845. var newWindow = window.open("");
  2846. var img = newWindow.document.createElement("img");
  2847. img.src = base64Image;
  2848. newWindow.document.body.appendChild(img);
  2849. }
  2850. };
  2851. scene.incrementRenderId();
  2852. texture.render(true);
  2853. texture.dispose();
  2854. if (previousCamera) {
  2855. scene.activeCamera = previousCamera;
  2856. }
  2857. };
  2858. // XHR response validator for local file scenario
  2859. Tools.ValidateXHRData = function (xhr, dataType) {
  2860. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2861. if (dataType === void 0) { dataType = 7; }
  2862. try {
  2863. if (dataType & 1) {
  2864. if (xhr.responseText && xhr.responseText.length > 0) {
  2865. return true;
  2866. }
  2867. else if (dataType === 1) {
  2868. return false;
  2869. }
  2870. }
  2871. if (dataType & 2) {
  2872. // Check header width and height since there is no "TGA" magic number
  2873. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2874. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2875. return true;
  2876. }
  2877. else if (dataType === 2) {
  2878. return false;
  2879. }
  2880. }
  2881. if (dataType & 4) {
  2882. // Check for the "DDS" magic number
  2883. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2884. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2885. return true;
  2886. }
  2887. else {
  2888. return false;
  2889. }
  2890. }
  2891. }
  2892. catch (e) {
  2893. }
  2894. return false;
  2895. };
  2896. Object.defineProperty(Tools, "NoneLogLevel", {
  2897. get: function () {
  2898. return Tools._NoneLogLevel;
  2899. },
  2900. enumerable: true,
  2901. configurable: true
  2902. });
  2903. Object.defineProperty(Tools, "MessageLogLevel", {
  2904. get: function () {
  2905. return Tools._MessageLogLevel;
  2906. },
  2907. enumerable: true,
  2908. configurable: true
  2909. });
  2910. Object.defineProperty(Tools, "WarningLogLevel", {
  2911. get: function () {
  2912. return Tools._WarningLogLevel;
  2913. },
  2914. enumerable: true,
  2915. configurable: true
  2916. });
  2917. Object.defineProperty(Tools, "ErrorLogLevel", {
  2918. get: function () {
  2919. return Tools._ErrorLogLevel;
  2920. },
  2921. enumerable: true,
  2922. configurable: true
  2923. });
  2924. Object.defineProperty(Tools, "AllLogLevel", {
  2925. get: function () {
  2926. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2927. },
  2928. enumerable: true,
  2929. configurable: true
  2930. });
  2931. Tools._AddLogEntry = function (entry) {
  2932. Tools._LogCache = entry + Tools._LogCache;
  2933. if (Tools.OnNewCacheEntry) {
  2934. Tools.OnNewCacheEntry(entry);
  2935. }
  2936. };
  2937. Tools._FormatMessage = function (message) {
  2938. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2939. var date = new Date();
  2940. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2941. };
  2942. Tools._LogDisabled = function (message) {
  2943. // nothing to do
  2944. };
  2945. Tools._LogEnabled = function (message) {
  2946. var formattedMessage = Tools._FormatMessage(message);
  2947. console.log("BJS - " + formattedMessage);
  2948. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2949. Tools._AddLogEntry(entry);
  2950. };
  2951. Tools._WarnDisabled = function (message) {
  2952. // nothing to do
  2953. };
  2954. Tools._WarnEnabled = function (message) {
  2955. var formattedMessage = Tools._FormatMessage(message);
  2956. console.warn("BJS - " + formattedMessage);
  2957. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2958. Tools._AddLogEntry(entry);
  2959. };
  2960. Tools._ErrorDisabled = function (message) {
  2961. // nothing to do
  2962. };
  2963. Tools._ErrorEnabled = function (message) {
  2964. var formattedMessage = Tools._FormatMessage(message);
  2965. console.error("BJS - " + formattedMessage);
  2966. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2967. Tools._AddLogEntry(entry);
  2968. };
  2969. Object.defineProperty(Tools, "LogCache", {
  2970. get: function () {
  2971. return Tools._LogCache;
  2972. },
  2973. enumerable: true,
  2974. configurable: true
  2975. });
  2976. Object.defineProperty(Tools, "LogLevels", {
  2977. set: function (level) {
  2978. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2979. Tools.Log = Tools._LogEnabled;
  2980. }
  2981. else {
  2982. Tools.Log = Tools._LogDisabled;
  2983. }
  2984. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2985. Tools.Warn = Tools._WarnEnabled;
  2986. }
  2987. else {
  2988. Tools.Warn = Tools._WarnDisabled;
  2989. }
  2990. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2991. Tools.Error = Tools._ErrorEnabled;
  2992. }
  2993. else {
  2994. Tools.Error = Tools._ErrorDisabled;
  2995. }
  2996. },
  2997. enumerable: true,
  2998. configurable: true
  2999. });
  3000. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3001. get: function () {
  3002. return Tools._PerformanceNoneLogLevel;
  3003. },
  3004. enumerable: true,
  3005. configurable: true
  3006. });
  3007. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3008. get: function () {
  3009. return Tools._PerformanceUserMarkLogLevel;
  3010. },
  3011. enumerable: true,
  3012. configurable: true
  3013. });
  3014. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3015. get: function () {
  3016. return Tools._PerformanceConsoleLogLevel;
  3017. },
  3018. enumerable: true,
  3019. configurable: true
  3020. });
  3021. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3022. set: function (level) {
  3023. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3024. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3025. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3026. return;
  3027. }
  3028. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3029. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3030. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3031. return;
  3032. }
  3033. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3034. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3035. },
  3036. enumerable: true,
  3037. configurable: true
  3038. });
  3039. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3040. };
  3041. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3042. };
  3043. Tools._StartUserMark = function (counterName, condition) {
  3044. if (condition === void 0) { condition = true; }
  3045. if (!condition || !Tools._performance.mark) {
  3046. return;
  3047. }
  3048. Tools._performance.mark(counterName + "-Begin");
  3049. };
  3050. Tools._EndUserMark = function (counterName, condition) {
  3051. if (condition === void 0) { condition = true; }
  3052. if (!condition || !Tools._performance.mark) {
  3053. return;
  3054. }
  3055. Tools._performance.mark(counterName + "-End");
  3056. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3057. };
  3058. Tools._StartPerformanceConsole = function (counterName, condition) {
  3059. if (condition === void 0) { condition = true; }
  3060. if (!condition) {
  3061. return;
  3062. }
  3063. Tools._StartUserMark(counterName, condition);
  3064. if (console.time) {
  3065. console.time(counterName);
  3066. }
  3067. };
  3068. Tools._EndPerformanceConsole = function (counterName, condition) {
  3069. if (condition === void 0) { condition = true; }
  3070. if (!condition) {
  3071. return;
  3072. }
  3073. Tools._EndUserMark(counterName, condition);
  3074. if (console.time) {
  3075. console.timeEnd(counterName);
  3076. }
  3077. };
  3078. Object.defineProperty(Tools, "Now", {
  3079. get: function () {
  3080. if (window.performance && window.performance.now) {
  3081. return window.performance.now();
  3082. }
  3083. return new Date().getTime();
  3084. },
  3085. enumerable: true,
  3086. configurable: true
  3087. });
  3088. // Deprecated
  3089. Tools.GetFps = function () {
  3090. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3091. return 0;
  3092. };
  3093. Tools.BaseUrl = "";
  3094. Tools.GetExponantOfTwo = function (value, max) {
  3095. var count = 1;
  3096. do {
  3097. count *= 2;
  3098. } while (count < value);
  3099. if (count > max)
  3100. count = max;
  3101. return count;
  3102. };
  3103. // Logs
  3104. Tools._NoneLogLevel = 0;
  3105. Tools._MessageLogLevel = 1;
  3106. Tools._WarningLogLevel = 2;
  3107. Tools._ErrorLogLevel = 4;
  3108. Tools._LogCache = "";
  3109. Tools.Log = Tools._LogEnabled;
  3110. Tools.Warn = Tools._WarnEnabled;
  3111. Tools.Error = Tools._ErrorEnabled;
  3112. // Performances
  3113. Tools._PerformanceNoneLogLevel = 0;
  3114. Tools._PerformanceUserMarkLogLevel = 1;
  3115. Tools._PerformanceConsoleLogLevel = 2;
  3116. Tools._performance = window.performance;
  3117. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3118. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3119. return Tools;
  3120. })();
  3121. BABYLON.Tools = Tools;
  3122. /**
  3123. * An implementation of a loop for asynchronous functions.
  3124. */
  3125. var AsyncLoop = (function () {
  3126. /**
  3127. * Constroctor.
  3128. * @param iterations the number of iterations.
  3129. * @param _fn the function to run each iteration
  3130. * @param _successCallback the callback that will be called upon succesful execution
  3131. * @param offset starting offset.
  3132. */
  3133. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3134. if (offset === void 0) { offset = 0; }
  3135. this.iterations = iterations;
  3136. this._fn = _fn;
  3137. this._successCallback = _successCallback;
  3138. this.index = offset - 1;
  3139. this._done = false;
  3140. }
  3141. /**
  3142. * Execute the next iteration. Must be called after the last iteration was finished.
  3143. */
  3144. AsyncLoop.prototype.executeNext = function () {
  3145. if (!this._done) {
  3146. if (this.index + 1 < this.iterations) {
  3147. ++this.index;
  3148. this._fn(this);
  3149. }
  3150. else {
  3151. this.breakLoop();
  3152. }
  3153. }
  3154. };
  3155. /**
  3156. * Break the loop and run the success callback.
  3157. */
  3158. AsyncLoop.prototype.breakLoop = function () {
  3159. this._done = true;
  3160. this._successCallback();
  3161. };
  3162. /**
  3163. * Helper function
  3164. */
  3165. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3166. if (offset === void 0) { offset = 0; }
  3167. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3168. loop.executeNext();
  3169. return loop;
  3170. };
  3171. /**
  3172. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3173. * @param iterations total number of iterations
  3174. * @param syncedIterations number of synchronous iterations in each async iteration.
  3175. * @param fn the function to call each iteration.
  3176. * @param callback a success call back that will be called when iterating stops.
  3177. * @param breakFunction a break condition (optional)
  3178. * @param timeout timeout settings for the setTimeout function. default - 0.
  3179. * @constructor
  3180. */
  3181. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3182. if (timeout === void 0) { timeout = 0; }
  3183. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3184. if (breakFunction && breakFunction())
  3185. loop.breakLoop();
  3186. else {
  3187. setTimeout(function () {
  3188. for (var i = 0; i < syncedIterations; ++i) {
  3189. var iteration = (loop.index * syncedIterations) + i;
  3190. if (iteration >= iterations)
  3191. break;
  3192. fn(iteration);
  3193. if (breakFunction && breakFunction()) {
  3194. loop.breakLoop();
  3195. break;
  3196. }
  3197. }
  3198. loop.executeNext();
  3199. }, timeout);
  3200. }
  3201. }, callback);
  3202. };
  3203. return AsyncLoop;
  3204. })();
  3205. BABYLON.AsyncLoop = AsyncLoop;
  3206. })(BABYLON || (BABYLON = {}));
  3207. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3208. (function (BABYLON) {
  3209. var _DepthCullingState = (function () {
  3210. function _DepthCullingState() {
  3211. this._isDepthTestDirty = false;
  3212. this._isDepthMaskDirty = false;
  3213. this._isDepthFuncDirty = false;
  3214. this._isCullFaceDirty = false;
  3215. this._isCullDirty = false;
  3216. }
  3217. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3218. get: function () {
  3219. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3220. },
  3221. enumerable: true,
  3222. configurable: true
  3223. });
  3224. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3225. get: function () {
  3226. return this._cullFace;
  3227. },
  3228. set: function (value) {
  3229. if (this._cullFace === value) {
  3230. return;
  3231. }
  3232. this._cullFace = value;
  3233. this._isCullFaceDirty = true;
  3234. },
  3235. enumerable: true,
  3236. configurable: true
  3237. });
  3238. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3239. get: function () {
  3240. return this._cull;
  3241. },
  3242. set: function (value) {
  3243. if (this._cull === value) {
  3244. return;
  3245. }
  3246. this._cull = value;
  3247. this._isCullDirty = true;
  3248. },
  3249. enumerable: true,
  3250. configurable: true
  3251. });
  3252. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3253. get: function () {
  3254. return this._depthFunc;
  3255. },
  3256. set: function (value) {
  3257. if (this._depthFunc === value) {
  3258. return;
  3259. }
  3260. this._depthFunc = value;
  3261. this._isDepthFuncDirty = true;
  3262. },
  3263. enumerable: true,
  3264. configurable: true
  3265. });
  3266. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3267. get: function () {
  3268. return this._depthMask;
  3269. },
  3270. set: function (value) {
  3271. if (this._depthMask === value) {
  3272. return;
  3273. }
  3274. this._depthMask = value;
  3275. this._isDepthMaskDirty = true;
  3276. },
  3277. enumerable: true,
  3278. configurable: true
  3279. });
  3280. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3281. get: function () {
  3282. return this._depthTest;
  3283. },
  3284. set: function (value) {
  3285. if (this._depthTest === value) {
  3286. return;
  3287. }
  3288. this._depthTest = value;
  3289. this._isDepthTestDirty = true;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. _DepthCullingState.prototype.reset = function () {
  3295. this._depthMask = true;
  3296. this._depthTest = true;
  3297. this._depthFunc = null;
  3298. this._cull = null;
  3299. this._cullFace = null;
  3300. this._isDepthTestDirty = true;
  3301. this._isDepthMaskDirty = true;
  3302. this._isDepthFuncDirty = false;
  3303. this._isCullFaceDirty = false;
  3304. this._isCullDirty = false;
  3305. };
  3306. _DepthCullingState.prototype.apply = function (gl) {
  3307. if (!this.isDirty) {
  3308. return;
  3309. }
  3310. // Cull
  3311. if (this._isCullDirty) {
  3312. if (this.cull) {
  3313. gl.enable(gl.CULL_FACE);
  3314. }
  3315. else {
  3316. gl.disable(gl.CULL_FACE);
  3317. }
  3318. this._isCullDirty = false;
  3319. }
  3320. // Cull face
  3321. if (this._isCullFaceDirty) {
  3322. gl.cullFace(this.cullFace);
  3323. this._isCullFaceDirty = false;
  3324. }
  3325. // Depth mask
  3326. if (this._isDepthMaskDirty) {
  3327. gl.depthMask(this.depthMask);
  3328. this._isDepthMaskDirty = false;
  3329. }
  3330. // Depth test
  3331. if (this._isDepthTestDirty) {
  3332. if (this.depthTest) {
  3333. gl.enable(gl.DEPTH_TEST);
  3334. }
  3335. else {
  3336. gl.disable(gl.DEPTH_TEST);
  3337. }
  3338. this._isDepthTestDirty = false;
  3339. }
  3340. // Depth func
  3341. if (this._isDepthFuncDirty) {
  3342. gl.depthFunc(this.depthFunc);
  3343. this._isDepthFuncDirty = false;
  3344. }
  3345. };
  3346. return _DepthCullingState;
  3347. })();
  3348. BABYLON._DepthCullingState = _DepthCullingState;
  3349. var _AlphaState = (function () {
  3350. function _AlphaState() {
  3351. this._isAlphaBlendDirty = false;
  3352. this._isBlendFunctionParametersDirty = false;
  3353. this._alphaBlend = false;
  3354. this._blendFunctionParameters = new Array(4);
  3355. }
  3356. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3357. get: function () {
  3358. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3364. get: function () {
  3365. return this._alphaBlend;
  3366. },
  3367. set: function (value) {
  3368. if (this._alphaBlend === value) {
  3369. return;
  3370. }
  3371. this._alphaBlend = value;
  3372. this._isAlphaBlendDirty = true;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3378. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3379. return;
  3380. }
  3381. this._blendFunctionParameters[0] = value0;
  3382. this._blendFunctionParameters[1] = value1;
  3383. this._blendFunctionParameters[2] = value2;
  3384. this._blendFunctionParameters[3] = value3;
  3385. this._isBlendFunctionParametersDirty = true;
  3386. };
  3387. _AlphaState.prototype.reset = function () {
  3388. this._alphaBlend = false;
  3389. this._blendFunctionParameters[0] = null;
  3390. this._blendFunctionParameters[1] = null;
  3391. this._blendFunctionParameters[2] = null;
  3392. this._blendFunctionParameters[3] = null;
  3393. this._isAlphaBlendDirty = true;
  3394. this._isBlendFunctionParametersDirty = false;
  3395. };
  3396. _AlphaState.prototype.apply = function (gl) {
  3397. if (!this.isDirty) {
  3398. return;
  3399. }
  3400. // Alpha blend
  3401. if (this._isAlphaBlendDirty) {
  3402. if (this._alphaBlend) {
  3403. gl.enable(gl.BLEND);
  3404. }
  3405. else {
  3406. gl.disable(gl.BLEND);
  3407. }
  3408. this._isAlphaBlendDirty = false;
  3409. }
  3410. // Alpha function
  3411. if (this._isBlendFunctionParametersDirty) {
  3412. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3413. this._isBlendFunctionParametersDirty = false;
  3414. }
  3415. };
  3416. return _AlphaState;
  3417. })();
  3418. BABYLON._AlphaState = _AlphaState;
  3419. var compileShader = function (gl, source, type, defines) {
  3420. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3421. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3422. gl.compileShader(shader);
  3423. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3424. throw new Error(gl.getShaderInfoLog(shader));
  3425. }
  3426. return shader;
  3427. };
  3428. var getWebGLTextureType = function (gl, type) {
  3429. var textureType = gl.UNSIGNED_BYTE;
  3430. if (type === Engine.TEXTURETYPE_FLOAT)
  3431. textureType = gl.FLOAT;
  3432. return textureType;
  3433. };
  3434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3435. var magFilter = gl.NEAREST;
  3436. var minFilter = gl.NEAREST;
  3437. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3438. magFilter = gl.LINEAR;
  3439. if (generateMipMaps) {
  3440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3441. }
  3442. else {
  3443. minFilter = gl.LINEAR;
  3444. }
  3445. }
  3446. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3447. magFilter = gl.LINEAR;
  3448. if (generateMipMaps) {
  3449. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3450. }
  3451. else {
  3452. minFilter = gl.LINEAR;
  3453. }
  3454. }
  3455. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3456. magFilter = gl.NEAREST;
  3457. if (generateMipMaps) {
  3458. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3459. }
  3460. else {
  3461. minFilter = gl.NEAREST;
  3462. }
  3463. }
  3464. return {
  3465. min: minFilter,
  3466. mag: magFilter
  3467. };
  3468. };
  3469. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3471. var engine = scene.getEngine();
  3472. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3473. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3474. gl.bindTexture(gl.TEXTURE_2D, texture);
  3475. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3476. processFunction(potWidth, potHeight);
  3477. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3480. if (!noMipmap && !isCompressed) {
  3481. gl.generateMipmap(gl.TEXTURE_2D);
  3482. }
  3483. gl.bindTexture(gl.TEXTURE_2D, null);
  3484. engine._activeTexturesCache = [];
  3485. texture._baseWidth = width;
  3486. texture._baseHeight = height;
  3487. texture._width = potWidth;
  3488. texture._height = potHeight;
  3489. texture.isReady = true;
  3490. texture.samplingMode = samplingMode;
  3491. scene._removePendingData(texture);
  3492. };
  3493. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3494. var onload = function () {
  3495. loadedImages[index] = img;
  3496. loadedImages._internalCount++;
  3497. scene._removePendingData(img);
  3498. if (loadedImages._internalCount === 6) {
  3499. onfinish(loadedImages);
  3500. }
  3501. };
  3502. var onerror = function () {
  3503. scene._removePendingData(img);
  3504. };
  3505. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3506. scene._addPendingData(img);
  3507. };
  3508. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3509. var loadedImages = [];
  3510. loadedImages._internalCount = 0;
  3511. for (var index = 0; index < 6; index++) {
  3512. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3513. }
  3514. };
  3515. var EngineCapabilities = (function () {
  3516. function EngineCapabilities() {
  3517. }
  3518. return EngineCapabilities;
  3519. })();
  3520. BABYLON.EngineCapabilities = EngineCapabilities;
  3521. /**
  3522. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3523. */
  3524. var Engine = (function () {
  3525. /**
  3526. * @constructor
  3527. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3528. * @param {boolean} [antialias] - enable antialias
  3529. * @param options - further options to be sent to the getContext function
  3530. */
  3531. function Engine(canvas, antialias, options) {
  3532. var _this = this;
  3533. // Public members
  3534. this.isFullscreen = false;
  3535. this.isPointerLock = false;
  3536. this.cullBackFaces = true;
  3537. this.renderEvenInBackground = true;
  3538. this.scenes = new Array();
  3539. this._windowIsBackground = false;
  3540. this._loadingDivBackgroundColor = "black";
  3541. this._drawCalls = 0;
  3542. this._renderingQueueLaunched = false;
  3543. this._activeRenderLoops = [];
  3544. // FPS
  3545. this.fpsRange = 60;
  3546. this.previousFramesDuration = [];
  3547. this.fps = 60;
  3548. this.deltaTime = 0;
  3549. // States
  3550. this._depthCullingState = new _DepthCullingState();
  3551. this._alphaState = new _AlphaState();
  3552. this._alphaMode = Engine.ALPHA_DISABLE;
  3553. // Cache
  3554. this._loadedTexturesCache = new Array();
  3555. this._activeTexturesCache = new Array();
  3556. this._compiledEffects = {};
  3557. this._uintIndicesCurrentlySet = false;
  3558. this._renderingCanvas = canvas;
  3559. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3560. options = options || {};
  3561. options.antialias = antialias;
  3562. try {
  3563. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3564. }
  3565. catch (e) {
  3566. throw new Error("WebGL not supported");
  3567. }
  3568. if (!this._gl) {
  3569. throw new Error("WebGL not supported");
  3570. }
  3571. this._onBlur = function () {
  3572. _this._windowIsBackground = true;
  3573. };
  3574. this._onFocus = function () {
  3575. _this._windowIsBackground = false;
  3576. };
  3577. window.addEventListener("blur", this._onBlur);
  3578. window.addEventListener("focus", this._onFocus);
  3579. // Textures
  3580. this._workingCanvas = document.createElement("canvas");
  3581. this._workingContext = this._workingCanvas.getContext("2d");
  3582. // Viewport
  3583. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3584. this.resize();
  3585. // Caps
  3586. this._caps = new EngineCapabilities();
  3587. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3588. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3589. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3590. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3591. // Infos
  3592. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3593. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3594. if (rendererInfo != null) {
  3595. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3596. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3597. }
  3598. if (!this._glVendor) {
  3599. this._glVendor = "Unknown vendor";
  3600. }
  3601. if (!this._glRenderer) {
  3602. this._glRenderer = "Unknown renderer";
  3603. }
  3604. // Extensions
  3605. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3606. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3607. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3608. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  3609. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3610. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3611. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3612. // Depth buffer
  3613. this.setDepthBuffer(true);
  3614. this.setDepthFunctionToLessOrEqual();
  3615. this.setDepthWrite(true);
  3616. // Fullscreen
  3617. this._onFullscreenChange = function () {
  3618. if (document.fullscreen !== undefined) {
  3619. _this.isFullscreen = document.fullscreen;
  3620. }
  3621. else if (document.mozFullScreen !== undefined) {
  3622. _this.isFullscreen = document.mozFullScreen;
  3623. }
  3624. else if (document.webkitIsFullScreen !== undefined) {
  3625. _this.isFullscreen = document.webkitIsFullScreen;
  3626. }
  3627. else if (document.msIsFullScreen !== undefined) {
  3628. _this.isFullscreen = document.msIsFullScreen;
  3629. }
  3630. // Pointer lock
  3631. if (_this.isFullscreen && _this._pointerLockRequested) {
  3632. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3633. if (canvas.requestPointerLock) {
  3634. canvas.requestPointerLock();
  3635. }
  3636. }
  3637. };
  3638. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3639. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3640. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3641. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3642. // Pointer lock
  3643. this._onPointerLockChange = function () {
  3644. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3645. };
  3646. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3647. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3648. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3649. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3650. if (!Engine.audioEngine) {
  3651. Engine.audioEngine = new BABYLON.AudioEngine();
  3652. }
  3653. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3654. }
  3655. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3656. get: function () {
  3657. return Engine._ALPHA_DISABLE;
  3658. },
  3659. enumerable: true,
  3660. configurable: true
  3661. });
  3662. Object.defineProperty(Engine, "ALPHA_ADD", {
  3663. get: function () {
  3664. return Engine._ALPHA_ADD;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3670. get: function () {
  3671. return Engine._ALPHA_COMBINE;
  3672. },
  3673. enumerable: true,
  3674. configurable: true
  3675. });
  3676. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3677. get: function () {
  3678. return Engine._DELAYLOADSTATE_NONE;
  3679. },
  3680. enumerable: true,
  3681. configurable: true
  3682. });
  3683. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3684. get: function () {
  3685. return Engine._DELAYLOADSTATE_LOADED;
  3686. },
  3687. enumerable: true,
  3688. configurable: true
  3689. });
  3690. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3691. get: function () {
  3692. return Engine._DELAYLOADSTATE_LOADING;
  3693. },
  3694. enumerable: true,
  3695. configurable: true
  3696. });
  3697. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3698. get: function () {
  3699. return Engine._DELAYLOADSTATE_NOTLOADED;
  3700. },
  3701. enumerable: true,
  3702. configurable: true
  3703. });
  3704. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3705. get: function () {
  3706. return Engine._TEXTUREFORMAT_ALPHA;
  3707. },
  3708. enumerable: true,
  3709. configurable: true
  3710. });
  3711. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3712. get: function () {
  3713. return Engine._TEXTUREFORMAT_LUMINANCE;
  3714. },
  3715. enumerable: true,
  3716. configurable: true
  3717. });
  3718. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3719. get: function () {
  3720. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3721. },
  3722. enumerable: true,
  3723. configurable: true
  3724. });
  3725. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3726. get: function () {
  3727. return Engine._TEXTUREFORMAT_RGB;
  3728. },
  3729. enumerable: true,
  3730. configurable: true
  3731. });
  3732. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3733. get: function () {
  3734. return Engine._TEXTUREFORMAT_RGBA;
  3735. },
  3736. enumerable: true,
  3737. configurable: true
  3738. });
  3739. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3740. get: function () {
  3741. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3747. get: function () {
  3748. return Engine._TEXTURETYPE_FLOAT;
  3749. },
  3750. enumerable: true,
  3751. configurable: true
  3752. });
  3753. Object.defineProperty(Engine, "Version", {
  3754. get: function () {
  3755. return "2.0.0";
  3756. },
  3757. enumerable: true,
  3758. configurable: true
  3759. });
  3760. Engine.prototype.getGlInfo = function () {
  3761. return {
  3762. vendor: this._glVendor,
  3763. renderer: this._glRenderer,
  3764. version: this._glVersion
  3765. };
  3766. };
  3767. Engine.prototype.getAspectRatio = function (camera) {
  3768. var viewport = camera.viewport;
  3769. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3770. };
  3771. Engine.prototype.getRenderWidth = function () {
  3772. if (this._currentRenderTarget) {
  3773. return this._currentRenderTarget._width;
  3774. }
  3775. return this._renderingCanvas.width;
  3776. };
  3777. Engine.prototype.getRenderHeight = function () {
  3778. if (this._currentRenderTarget) {
  3779. return this._currentRenderTarget._height;
  3780. }
  3781. return this._renderingCanvas.height;
  3782. };
  3783. Engine.prototype.getRenderingCanvas = function () {
  3784. return this._renderingCanvas;
  3785. };
  3786. Engine.prototype.getRenderingCanvasClientRect = function () {
  3787. return this._renderingCanvas.getBoundingClientRect();
  3788. };
  3789. Engine.prototype.setHardwareScalingLevel = function (level) {
  3790. this._hardwareScalingLevel = level;
  3791. this.resize();
  3792. };
  3793. Engine.prototype.getHardwareScalingLevel = function () {
  3794. return this._hardwareScalingLevel;
  3795. };
  3796. Engine.prototype.getLoadedTexturesCache = function () {
  3797. return this._loadedTexturesCache;
  3798. };
  3799. Engine.prototype.getCaps = function () {
  3800. return this._caps;
  3801. };
  3802. Object.defineProperty(Engine.prototype, "drawCalls", {
  3803. get: function () {
  3804. return this._drawCalls;
  3805. },
  3806. enumerable: true,
  3807. configurable: true
  3808. });
  3809. // Methods
  3810. Engine.prototype.resetDrawCalls = function () {
  3811. this._drawCalls = 0;
  3812. };
  3813. Engine.prototype.setDepthFunctionToGreater = function () {
  3814. this._depthCullingState.depthFunc = this._gl.GREATER;
  3815. };
  3816. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3817. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3818. };
  3819. Engine.prototype.setDepthFunctionToLess = function () {
  3820. this._depthCullingState.depthFunc = this._gl.LESS;
  3821. };
  3822. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3823. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3824. };
  3825. /**
  3826. * stop executing a render loop function and remove it from the execution array
  3827. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3828. */
  3829. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3830. if (!renderFunction) {
  3831. this._activeRenderLoops = [];
  3832. return;
  3833. }
  3834. var index = this._activeRenderLoops.indexOf(renderFunction);
  3835. if (index >= 0) {
  3836. this._activeRenderLoops.splice(index, 1);
  3837. }
  3838. };
  3839. Engine.prototype._renderLoop = function () {
  3840. var _this = this;
  3841. var shouldRender = true;
  3842. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3843. shouldRender = false;
  3844. }
  3845. if (shouldRender) {
  3846. // Start new frame
  3847. this.beginFrame();
  3848. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3849. var renderFunction = this._activeRenderLoops[index];
  3850. renderFunction();
  3851. }
  3852. // Present
  3853. this.endFrame();
  3854. }
  3855. if (this._activeRenderLoops.length > 0) {
  3856. // Register new frame
  3857. BABYLON.Tools.QueueNewFrame(function () {
  3858. _this._renderLoop();
  3859. });
  3860. }
  3861. else {
  3862. this._renderingQueueLaunched = false;
  3863. }
  3864. };
  3865. /**
  3866. * Register and execute a render loop. The engine can have more than one render function.
  3867. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3868. * @example
  3869. * engine.runRenderLoop(function () {
  3870. * scene.render()
  3871. * })
  3872. */
  3873. Engine.prototype.runRenderLoop = function (renderFunction) {
  3874. var _this = this;
  3875. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3876. return;
  3877. }
  3878. this._activeRenderLoops.push(renderFunction);
  3879. if (!this._renderingQueueLaunched) {
  3880. this._renderingQueueLaunched = true;
  3881. BABYLON.Tools.QueueNewFrame(function () {
  3882. _this._renderLoop();
  3883. });
  3884. }
  3885. };
  3886. /**
  3887. * Toggle full screen mode.
  3888. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3889. */
  3890. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3891. if (this.isFullscreen) {
  3892. BABYLON.Tools.ExitFullscreen();
  3893. }
  3894. else {
  3895. this._pointerLockRequested = requestPointerLock;
  3896. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3897. }
  3898. };
  3899. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3900. this.applyStates();
  3901. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3902. if (this._depthCullingState.depthMask) {
  3903. this._gl.clearDepth(1.0);
  3904. }
  3905. var mode = 0;
  3906. if (backBuffer)
  3907. mode |= this._gl.COLOR_BUFFER_BIT;
  3908. if (depthStencil && this._depthCullingState.depthMask)
  3909. mode |= this._gl.DEPTH_BUFFER_BIT;
  3910. this._gl.clear(mode);
  3911. };
  3912. /**
  3913. * Set the WebGL's viewport
  3914. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3915. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3916. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3917. */
  3918. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3919. var width = requiredWidth || this._renderingCanvas.width;
  3920. var height = requiredHeight || this._renderingCanvas.height;
  3921. var x = viewport.x || 0;
  3922. var y = viewport.y || 0;
  3923. this._cachedViewport = viewport;
  3924. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3925. };
  3926. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3927. this._cachedViewport = null;
  3928. this._gl.viewport(x, y, width, height);
  3929. };
  3930. Engine.prototype.beginFrame = function () {
  3931. this._measureFps();
  3932. };
  3933. Engine.prototype.endFrame = function () {
  3934. //this.flushFramebuffer();
  3935. };
  3936. /**
  3937. * resize the view according to the canvas' size.
  3938. * @example
  3939. * window.addEventListener("resize", function () {
  3940. * engine.resize();
  3941. * });
  3942. */
  3943. Engine.prototype.resize = function () {
  3944. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3945. };
  3946. /**
  3947. * force a specific size of the canvas
  3948. * @param {number} width - the new canvas' width
  3949. * @param {number} height - the new canvas' height
  3950. */
  3951. Engine.prototype.setSize = function (width, height) {
  3952. this._renderingCanvas.width = width;
  3953. this._renderingCanvas.height = height;
  3954. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3955. };
  3956. Engine.prototype.bindFramebuffer = function (texture) {
  3957. this._currentRenderTarget = texture;
  3958. var gl = this._gl;
  3959. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3960. this._gl.viewport(0, 0, texture._width, texture._height);
  3961. this.wipeCaches();
  3962. };
  3963. Engine.prototype.unBindFramebuffer = function (texture) {
  3964. this._currentRenderTarget = null;
  3965. if (texture.generateMipMaps) {
  3966. var gl = this._gl;
  3967. gl.bindTexture(gl.TEXTURE_2D, texture);
  3968. gl.generateMipmap(gl.TEXTURE_2D);
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. }
  3971. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3972. };
  3973. Engine.prototype.flushFramebuffer = function () {
  3974. this._gl.flush();
  3975. };
  3976. Engine.prototype.restoreDefaultFramebuffer = function () {
  3977. this._currentRenderTarget = null;
  3978. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3979. this.setViewport(this._cachedViewport);
  3980. this.wipeCaches();
  3981. };
  3982. // VBOs
  3983. Engine.prototype._resetVertexBufferBinding = function () {
  3984. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3985. this._cachedVertexBuffers = null;
  3986. };
  3987. Engine.prototype.createVertexBuffer = function (vertices) {
  3988. var vbo = this._gl.createBuffer();
  3989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3991. this._resetVertexBufferBinding();
  3992. vbo.references = 1;
  3993. return vbo;
  3994. };
  3995. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3996. var vbo = this._gl.createBuffer();
  3997. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3998. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3999. this._resetVertexBufferBinding();
  4000. vbo.references = 1;
  4001. return vbo;
  4002. };
  4003. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4004. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4005. if (offset === undefined) {
  4006. offset = 0;
  4007. }
  4008. if (vertices instanceof Float32Array) {
  4009. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4010. }
  4011. else {
  4012. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4013. }
  4014. this._resetVertexBufferBinding();
  4015. };
  4016. Engine.prototype._resetIndexBufferBinding = function () {
  4017. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4018. this._cachedIndexBuffer = null;
  4019. };
  4020. Engine.prototype.createIndexBuffer = function (indices) {
  4021. var vbo = this._gl.createBuffer();
  4022. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4023. // Check for 32 bits indices
  4024. var arrayBuffer;
  4025. var need32Bits = false;
  4026. if (this._caps.uintIndices) {
  4027. for (var index = 0; index < indices.length; index++) {
  4028. if (indices[index] > 65535) {
  4029. need32Bits = true;
  4030. break;
  4031. }
  4032. }
  4033. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4034. }
  4035. else {
  4036. arrayBuffer = new Uint16Array(indices);
  4037. }
  4038. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4039. this._resetIndexBufferBinding();
  4040. vbo.references = 1;
  4041. vbo.is32Bits = need32Bits;
  4042. return vbo;
  4043. };
  4044. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4045. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4046. this._cachedVertexBuffers = vertexBuffer;
  4047. this._cachedEffectForVertexBuffers = effect;
  4048. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4049. var offset = 0;
  4050. for (var index = 0; index < vertexDeclaration.length; index++) {
  4051. var order = effect.getAttributeLocation(index);
  4052. if (order >= 0) {
  4053. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4054. }
  4055. offset += vertexDeclaration[index] * 4;
  4056. }
  4057. }
  4058. if (this._cachedIndexBuffer !== indexBuffer) {
  4059. this._cachedIndexBuffer = indexBuffer;
  4060. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4061. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4062. }
  4063. };
  4064. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4065. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4066. this._cachedVertexBuffers = vertexBuffers;
  4067. this._cachedEffectForVertexBuffers = effect;
  4068. var attributes = effect.getAttributesNames();
  4069. for (var index = 0; index < attributes.length; index++) {
  4070. var order = effect.getAttributeLocation(index);
  4071. if (order >= 0) {
  4072. var vertexBuffer = vertexBuffers[attributes[index]];
  4073. if (!vertexBuffer) {
  4074. continue;
  4075. }
  4076. var stride = vertexBuffer.getStrideSize();
  4077. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4078. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4079. }
  4080. }
  4081. }
  4082. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4083. this._cachedIndexBuffer = indexBuffer;
  4084. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4085. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4086. }
  4087. };
  4088. Engine.prototype._releaseBuffer = function (buffer) {
  4089. buffer.references--;
  4090. if (buffer.references === 0) {
  4091. this._gl.deleteBuffer(buffer);
  4092. return true;
  4093. }
  4094. return false;
  4095. };
  4096. Engine.prototype.createInstancesBuffer = function (capacity) {
  4097. var buffer = this._gl.createBuffer();
  4098. buffer.capacity = capacity;
  4099. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4100. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4101. return buffer;
  4102. };
  4103. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4104. this._gl.deleteBuffer(buffer);
  4105. };
  4106. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4107. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4109. for (var index = 0; index < 4; index++) {
  4110. var offsetLocation = offsetLocations[index];
  4111. this._gl.enableVertexAttribArray(offsetLocation);
  4112. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4113. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4114. }
  4115. };
  4116. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4117. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4118. for (var index = 0; index < 4; index++) {
  4119. var offsetLocation = offsetLocations[index];
  4120. this._gl.disableVertexAttribArray(offsetLocation);
  4121. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4122. }
  4123. };
  4124. Engine.prototype.applyStates = function () {
  4125. this._depthCullingState.apply(this._gl);
  4126. this._alphaState.apply(this._gl);
  4127. };
  4128. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4129. // Apply states
  4130. this.applyStates();
  4131. this._drawCalls++;
  4132. // Render
  4133. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4134. if (instancesCount) {
  4135. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4136. return;
  4137. }
  4138. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4139. };
  4140. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4141. // Apply states
  4142. this.applyStates();
  4143. this._drawCalls++;
  4144. if (instancesCount) {
  4145. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4146. return;
  4147. }
  4148. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4149. };
  4150. // Shaders
  4151. Engine.prototype._releaseEffect = function (effect) {
  4152. if (this._compiledEffects[effect._key]) {
  4153. delete this._compiledEffects[effect._key];
  4154. if (effect.getProgram()) {
  4155. this._gl.deleteProgram(effect.getProgram());
  4156. }
  4157. }
  4158. };
  4159. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4160. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4161. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4162. var name = vertex + "+" + fragment + "@" + defines;
  4163. if (this._compiledEffects[name]) {
  4164. return this._compiledEffects[name];
  4165. }
  4166. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4167. effect._key = name;
  4168. this._compiledEffects[name] = effect;
  4169. return effect;
  4170. };
  4171. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4172. if (uniformsNames === void 0) { uniformsNames = []; }
  4173. if (samplers === void 0) { samplers = []; }
  4174. if (defines === void 0) { defines = ""; }
  4175. return this.createEffect({
  4176. vertex: "particles",
  4177. fragmentElement: fragmentName
  4178. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4179. };
  4180. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4181. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4182. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4183. var shaderProgram = this._gl.createProgram();
  4184. this._gl.attachShader(shaderProgram, vertexShader);
  4185. this._gl.attachShader(shaderProgram, fragmentShader);
  4186. this._gl.linkProgram(shaderProgram);
  4187. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4188. if (!linked) {
  4189. var error = this._gl.getProgramInfoLog(shaderProgram);
  4190. if (error) {
  4191. throw new Error(error);
  4192. }
  4193. }
  4194. this._gl.deleteShader(vertexShader);
  4195. this._gl.deleteShader(fragmentShader);
  4196. return shaderProgram;
  4197. };
  4198. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4199. var results = [];
  4200. for (var index = 0; index < uniformsNames.length; index++) {
  4201. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4202. }
  4203. return results;
  4204. };
  4205. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4206. var results = [];
  4207. for (var index = 0; index < attributesNames.length; index++) {
  4208. try {
  4209. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4210. }
  4211. catch (e) {
  4212. results.push(-1);
  4213. }
  4214. }
  4215. return results;
  4216. };
  4217. Engine.prototype.enableEffect = function (effect) {
  4218. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4219. if (effect && effect.onBind) {
  4220. effect.onBind(effect);
  4221. }
  4222. return;
  4223. }
  4224. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4225. // Use program
  4226. this._gl.useProgram(effect.getProgram());
  4227. for (var i in this._vertexAttribArrays) {
  4228. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4229. continue;
  4230. }
  4231. this._vertexAttribArrays[i] = false;
  4232. this._gl.disableVertexAttribArray(i);
  4233. }
  4234. var attributesCount = effect.getAttributesCount();
  4235. for (var index = 0; index < attributesCount; index++) {
  4236. // Attributes
  4237. var order = effect.getAttributeLocation(index);
  4238. if (order >= 0) {
  4239. this._vertexAttribArrays[order] = true;
  4240. this._gl.enableVertexAttribArray(order);
  4241. }
  4242. }
  4243. this._currentEffect = effect;
  4244. if (effect.onBind) {
  4245. effect.onBind(effect);
  4246. }
  4247. };
  4248. Engine.prototype.setArray = function (uniform, array) {
  4249. if (!uniform)
  4250. return;
  4251. this._gl.uniform1fv(uniform, array);
  4252. };
  4253. Engine.prototype.setArray2 = function (uniform, array) {
  4254. if (!uniform || array.length % 2 !== 0)
  4255. return;
  4256. this._gl.uniform2fv(uniform, array);
  4257. };
  4258. Engine.prototype.setArray3 = function (uniform, array) {
  4259. if (!uniform || array.length % 3 !== 0)
  4260. return;
  4261. this._gl.uniform3fv(uniform, array);
  4262. };
  4263. Engine.prototype.setArray4 = function (uniform, array) {
  4264. if (!uniform || array.length % 4 !== 0)
  4265. return;
  4266. this._gl.uniform4fv(uniform, array);
  4267. };
  4268. Engine.prototype.setMatrices = function (uniform, matrices) {
  4269. if (!uniform)
  4270. return;
  4271. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4272. };
  4273. Engine.prototype.setMatrix = function (uniform, matrix) {
  4274. if (!uniform)
  4275. return;
  4276. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4277. };
  4278. Engine.prototype.setFloat = function (uniform, value) {
  4279. if (!uniform)
  4280. return;
  4281. this._gl.uniform1f(uniform, value);
  4282. };
  4283. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4284. if (!uniform)
  4285. return;
  4286. this._gl.uniform2f(uniform, x, y);
  4287. };
  4288. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4289. if (!uniform)
  4290. return;
  4291. this._gl.uniform3f(uniform, x, y, z);
  4292. };
  4293. Engine.prototype.setBool = function (uniform, bool) {
  4294. if (!uniform)
  4295. return;
  4296. this._gl.uniform1i(uniform, bool);
  4297. };
  4298. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4299. if (!uniform)
  4300. return;
  4301. this._gl.uniform4f(uniform, x, y, z, w);
  4302. };
  4303. Engine.prototype.setColor3 = function (uniform, color3) {
  4304. if (!uniform)
  4305. return;
  4306. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4307. };
  4308. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4309. if (!uniform)
  4310. return;
  4311. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4312. };
  4313. // States
  4314. Engine.prototype.setState = function (culling, force) {
  4315. // Culling
  4316. if (this._depthCullingState.cull !== culling || force) {
  4317. if (culling) {
  4318. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4319. this._depthCullingState.cull = true;
  4320. }
  4321. else {
  4322. this._depthCullingState.cull = false;
  4323. }
  4324. }
  4325. };
  4326. Engine.prototype.setDepthBuffer = function (enable) {
  4327. this._depthCullingState.depthTest = enable;
  4328. };
  4329. Engine.prototype.getDepthWrite = function () {
  4330. return this._depthCullingState.depthMask;
  4331. };
  4332. Engine.prototype.setDepthWrite = function (enable) {
  4333. this._depthCullingState.depthMask = enable;
  4334. };
  4335. Engine.prototype.setColorWrite = function (enable) {
  4336. this._gl.colorMask(enable, enable, enable, enable);
  4337. };
  4338. Engine.prototype.setAlphaMode = function (mode) {
  4339. switch (mode) {
  4340. case Engine.ALPHA_DISABLE:
  4341. this.setDepthWrite(true);
  4342. this._alphaState.alphaBlend = false;
  4343. break;
  4344. case Engine.ALPHA_COMBINE:
  4345. this.setDepthWrite(false);
  4346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4347. this._alphaState.alphaBlend = true;
  4348. break;
  4349. case Engine.ALPHA_ADD:
  4350. this.setDepthWrite(false);
  4351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4352. this._alphaState.alphaBlend = true;
  4353. break;
  4354. }
  4355. this._alphaMode = mode;
  4356. };
  4357. Engine.prototype.getAlphaMode = function () {
  4358. return this._alphaMode;
  4359. };
  4360. Engine.prototype.setAlphaTesting = function (enable) {
  4361. this._alphaTest = enable;
  4362. };
  4363. Engine.prototype.getAlphaTesting = function () {
  4364. return this._alphaTest;
  4365. };
  4366. // Textures
  4367. Engine.prototype.wipeCaches = function () {
  4368. this._activeTexturesCache = [];
  4369. this._currentEffect = null;
  4370. this._depthCullingState.reset();
  4371. this._alphaState.reset();
  4372. this._cachedVertexBuffers = null;
  4373. this._cachedIndexBuffer = null;
  4374. this._cachedEffectForVertexBuffers = null;
  4375. };
  4376. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4377. var gl = this._gl;
  4378. gl.bindTexture(gl.TEXTURE_2D, texture);
  4379. var magFilter = gl.NEAREST;
  4380. var minFilter = gl.NEAREST;
  4381. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4382. magFilter = gl.LINEAR;
  4383. minFilter = gl.LINEAR;
  4384. }
  4385. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4386. magFilter = gl.LINEAR;
  4387. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4388. }
  4389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4391. gl.bindTexture(gl.TEXTURE_2D, null);
  4392. texture.samplingMode = samplingMode;
  4393. };
  4394. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4395. var _this = this;
  4396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4397. if (onLoad === void 0) { onLoad = null; }
  4398. if (onError === void 0) { onError = null; }
  4399. if (buffer === void 0) { buffer = null; }
  4400. var texture = this._gl.createTexture();
  4401. var extension;
  4402. var fromData = false;
  4403. if (url.substr(0, 5) === "data:") {
  4404. fromData = true;
  4405. }
  4406. if (!fromData)
  4407. extension = url.substr(url.length - 4, 4).toLowerCase();
  4408. else {
  4409. var oldUrl = url;
  4410. fromData = oldUrl.split(':');
  4411. url = oldUrl;
  4412. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4413. }
  4414. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4415. var isTGA = (extension === ".tga");
  4416. scene._addPendingData(texture);
  4417. texture.url = url;
  4418. texture.noMipmap = noMipmap;
  4419. texture.references = 1;
  4420. this._loadedTexturesCache.push(texture);
  4421. var onerror = function () {
  4422. scene._removePendingData(texture);
  4423. if (onError) {
  4424. onError();
  4425. }
  4426. };
  4427. if (isTGA) {
  4428. var callback = function (arrayBuffer) {
  4429. var data = new Uint8Array(arrayBuffer);
  4430. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4431. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4432. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4433. if (onLoad) {
  4434. onLoad();
  4435. }
  4436. }, samplingMode);
  4437. };
  4438. if (!(fromData instanceof Array))
  4439. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4440. callback(arrayBuffer);
  4441. }, onerror, scene.database, true);
  4442. else
  4443. callback(buffer);
  4444. }
  4445. else if (isDDS) {
  4446. callback = function (data) {
  4447. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4448. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4449. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4450. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4451. if (onLoad) {
  4452. onLoad();
  4453. }
  4454. }, samplingMode);
  4455. };
  4456. if (!(fromData instanceof Array))
  4457. BABYLON.Tools.LoadFile(url, function (data) {
  4458. callback(data);
  4459. }, onerror, scene.database, true);
  4460. else
  4461. callback(buffer);
  4462. }
  4463. else {
  4464. var onload = function (img) {
  4465. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4466. var isPot = (img.width === potWidth && img.height === potHeight);
  4467. if (!isPot) {
  4468. _this._workingCanvas.width = potWidth;
  4469. _this._workingCanvas.height = potHeight;
  4470. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4471. _this._workingContext.imageSmoothingEnabled = false;
  4472. _this._workingContext.mozImageSmoothingEnabled = false;
  4473. _this._workingContext.oImageSmoothingEnabled = false;
  4474. _this._workingContext.webkitImageSmoothingEnabled = false;
  4475. _this._workingContext.msImageSmoothingEnabled = false;
  4476. }
  4477. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4478. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4479. _this._workingContext.imageSmoothingEnabled = true;
  4480. _this._workingContext.mozImageSmoothingEnabled = true;
  4481. _this._workingContext.oImageSmoothingEnabled = true;
  4482. _this._workingContext.webkitImageSmoothingEnabled = true;
  4483. _this._workingContext.msImageSmoothingEnabled = true;
  4484. }
  4485. }
  4486. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4487. if (onLoad) {
  4488. onLoad();
  4489. }
  4490. }, samplingMode);
  4491. };
  4492. if (!(fromData instanceof Array))
  4493. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4494. else
  4495. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4496. }
  4497. return texture;
  4498. };
  4499. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4500. var texture = this._gl.createTexture();
  4501. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4502. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4503. // Format
  4504. var internalFormat = this._gl.RGBA;
  4505. switch (format) {
  4506. case Engine.TEXTUREFORMAT_ALPHA:
  4507. internalFormat = this._gl.ALPHA;
  4508. break;
  4509. case Engine.TEXTUREFORMAT_LUMINANCE:
  4510. internalFormat = this._gl.LUMINANCE;
  4511. break;
  4512. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4513. internalFormat = this._gl.LUMINANCE_ALPHA;
  4514. break;
  4515. case Engine.TEXTUREFORMAT_RGB:
  4516. internalFormat = this._gl.RGB;
  4517. break;
  4518. case Engine.TEXTUREFORMAT_RGBA:
  4519. internalFormat = this._gl.RGBA;
  4520. break;
  4521. }
  4522. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4523. if (generateMipMaps) {
  4524. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4525. }
  4526. // Filters
  4527. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4530. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4531. this._activeTexturesCache = [];
  4532. texture._baseWidth = width;
  4533. texture._baseHeight = height;
  4534. texture._width = width;
  4535. texture._height = height;
  4536. texture.isReady = true;
  4537. texture.references = 1;
  4538. texture.samplingMode = samplingMode;
  4539. this._loadedTexturesCache.push(texture);
  4540. return texture;
  4541. };
  4542. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4543. var texture = this._gl.createTexture();
  4544. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4545. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4546. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4547. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4550. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4551. this._activeTexturesCache = [];
  4552. texture._baseWidth = width;
  4553. texture._baseHeight = height;
  4554. texture._width = width;
  4555. texture._height = height;
  4556. texture.isReady = false;
  4557. texture.generateMipMaps = generateMipMaps;
  4558. texture.references = 1;
  4559. texture.samplingMode = samplingMode;
  4560. this._loadedTexturesCache.push(texture);
  4561. return texture;
  4562. };
  4563. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4564. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4565. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4566. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4567. if (texture.generateMipMaps) {
  4568. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4569. }
  4570. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4571. this._activeTexturesCache = [];
  4572. texture.isReady = true;
  4573. };
  4574. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4575. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4576. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4577. // Scale the video if it is a NPOT using the current working canvas
  4578. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4579. if (!texture._workingCanvas) {
  4580. texture._workingCanvas = document.createElement("canvas");
  4581. texture._workingContext = texture._workingCanvas.getContext("2d");
  4582. texture._workingCanvas.width = texture._width;
  4583. texture._workingCanvas.height = texture._height;
  4584. }
  4585. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4586. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4587. }
  4588. else {
  4589. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4590. }
  4591. if (texture.generateMipMaps) {
  4592. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4593. }
  4594. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4595. this._activeTexturesCache = [];
  4596. texture.isReady = true;
  4597. };
  4598. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4599. // old version had a "generateMipMaps" arg instead of options.
  4600. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4601. // in the same way, generateDepthBuffer is defaulted to true
  4602. var generateMipMaps = false;
  4603. var generateDepthBuffer = true;
  4604. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4605. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4606. if (options !== undefined) {
  4607. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4608. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4609. type = options.type === undefined ? type : options.type;
  4610. if (options.samplingMode !== undefined) {
  4611. samplingMode = options.samplingMode;
  4612. }
  4613. if (type === Engine.TEXTURETYPE_FLOAT) {
  4614. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4615. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4616. }
  4617. }
  4618. var gl = this._gl;
  4619. var texture = gl.createTexture();
  4620. gl.bindTexture(gl.TEXTURE_2D, texture);
  4621. var width = size.width || size;
  4622. var height = size.height || size;
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4624. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4625. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4626. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4627. }
  4628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4632. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4633. var depthBuffer;
  4634. // Create the depth buffer
  4635. if (generateDepthBuffer) {
  4636. depthBuffer = gl.createRenderbuffer();
  4637. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4638. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4639. }
  4640. // Create the framebuffer
  4641. var framebuffer = gl.createFramebuffer();
  4642. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4644. if (generateDepthBuffer) {
  4645. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4646. }
  4647. // Unbind
  4648. gl.bindTexture(gl.TEXTURE_2D, null);
  4649. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4650. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4651. texture._framebuffer = framebuffer;
  4652. if (generateDepthBuffer) {
  4653. texture._depthBuffer = depthBuffer;
  4654. }
  4655. texture._width = width;
  4656. texture._height = height;
  4657. texture.isReady = true;
  4658. texture.generateMipMaps = generateMipMaps;
  4659. texture.references = 1;
  4660. texture.samplingMode = samplingMode;
  4661. this._activeTexturesCache = [];
  4662. this._loadedTexturesCache.push(texture);
  4663. return texture;
  4664. };
  4665. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4666. var _this = this;
  4667. var gl = this._gl;
  4668. var texture = gl.createTexture();
  4669. texture.isCube = true;
  4670. texture.url = rootUrl;
  4671. texture.references = 1;
  4672. this._loadedTexturesCache.push(texture);
  4673. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4674. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4675. if (isDDS) {
  4676. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4677. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4678. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4679. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4680. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4681. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4682. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4684. }
  4685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4689. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4690. _this._activeTexturesCache = [];
  4691. texture._width = info.width;
  4692. texture._height = info.height;
  4693. texture.isReady = true;
  4694. }, null, null, true);
  4695. }
  4696. else {
  4697. cascadeLoad(rootUrl, scene, function (imgs) {
  4698. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4699. var height = width;
  4700. _this._workingCanvas.width = width;
  4701. _this._workingCanvas.height = height;
  4702. var faces = [
  4703. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4704. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4705. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4706. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4707. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4708. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4709. ];
  4710. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4711. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4712. for (var index = 0; index < faces.length; index++) {
  4713. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4714. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4715. }
  4716. if (!noMipmap) {
  4717. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4718. }
  4719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4723. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4724. _this._activeTexturesCache = [];
  4725. texture._width = width;
  4726. texture._height = height;
  4727. texture.isReady = true;
  4728. }, extensions);
  4729. }
  4730. return texture;
  4731. };
  4732. Engine.prototype._releaseTexture = function (texture) {
  4733. var gl = this._gl;
  4734. if (texture._framebuffer) {
  4735. gl.deleteFramebuffer(texture._framebuffer);
  4736. }
  4737. if (texture._depthBuffer) {
  4738. gl.deleteRenderbuffer(texture._depthBuffer);
  4739. }
  4740. gl.deleteTexture(texture);
  4741. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4742. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4743. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4744. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4745. this._activeTexturesCache[channel] = null;
  4746. }
  4747. var index = this._loadedTexturesCache.indexOf(texture);
  4748. if (index !== -1) {
  4749. this._loadedTexturesCache.splice(index, 1);
  4750. }
  4751. };
  4752. Engine.prototype.bindSamplers = function (effect) {
  4753. this._gl.useProgram(effect.getProgram());
  4754. var samplers = effect.getSamplers();
  4755. for (var index = 0; index < samplers.length; index++) {
  4756. var uniform = effect.getUniform(samplers[index]);
  4757. this._gl.uniform1i(uniform, index);
  4758. }
  4759. this._currentEffect = null;
  4760. };
  4761. Engine.prototype._bindTexture = function (channel, texture) {
  4762. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4763. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4764. this._activeTexturesCache[channel] = null;
  4765. };
  4766. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4767. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4768. };
  4769. Engine.prototype.setTexture = function (channel, texture) {
  4770. if (channel < 0) {
  4771. return;
  4772. }
  4773. // Not ready?
  4774. if (!texture || !texture.isReady()) {
  4775. if (this._activeTexturesCache[channel] != null) {
  4776. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4777. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4778. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4779. this._activeTexturesCache[channel] = null;
  4780. }
  4781. return;
  4782. }
  4783. // Video
  4784. if (texture instanceof BABYLON.VideoTexture) {
  4785. if (texture.update()) {
  4786. this._activeTexturesCache[channel] = null;
  4787. }
  4788. }
  4789. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4790. texture.delayLoad();
  4791. return;
  4792. }
  4793. if (this._activeTexturesCache[channel] === texture) {
  4794. return;
  4795. }
  4796. this._activeTexturesCache[channel] = texture;
  4797. var internalTexture = texture.getInternalTexture();
  4798. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4799. if (internalTexture.isCube) {
  4800. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4801. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4802. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4803. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4804. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4805. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4806. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4807. }
  4808. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4809. }
  4810. else {
  4811. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4812. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4813. internalTexture._cachedWrapU = texture.wrapU;
  4814. switch (texture.wrapU) {
  4815. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4817. break;
  4818. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4820. break;
  4821. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4822. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4823. break;
  4824. }
  4825. }
  4826. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4827. internalTexture._cachedWrapV = texture.wrapV;
  4828. switch (texture.wrapV) {
  4829. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4831. break;
  4832. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4833. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4834. break;
  4835. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4837. break;
  4838. }
  4839. }
  4840. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4841. }
  4842. };
  4843. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4844. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4845. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4846. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4847. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4848. }
  4849. };
  4850. Engine.prototype.readPixels = function (x, y, width, height) {
  4851. var data = new Uint8Array(height * width * 4);
  4852. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4853. return data;
  4854. };
  4855. // Dispose
  4856. Engine.prototype.dispose = function () {
  4857. this.hideLoadingUI();
  4858. this.stopRenderLoop();
  4859. while (this.scenes.length) {
  4860. this.scenes[0].dispose();
  4861. }
  4862. // Release audio engine
  4863. Engine.audioEngine.dispose();
  4864. for (var name in this._compiledEffects) {
  4865. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4866. }
  4867. for (var i in this._vertexAttribArrays) {
  4868. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4869. continue;
  4870. }
  4871. this._gl.disableVertexAttribArray(i);
  4872. }
  4873. // Events
  4874. window.removeEventListener("blur", this._onBlur);
  4875. window.removeEventListener("focus", this._onFocus);
  4876. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4877. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4878. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4879. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4880. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4881. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4882. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4883. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4884. };
  4885. // Loading screen
  4886. Engine.prototype.displayLoadingUI = function () {
  4887. var _this = this;
  4888. this._loadingDiv = document.createElement("div");
  4889. this._loadingDiv.style.opacity = "0";
  4890. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4891. // Loading text
  4892. this._loadingTextDiv = document.createElement("div");
  4893. this._loadingTextDiv.style.position = "absolute";
  4894. this._loadingTextDiv.style.left = "0";
  4895. this._loadingTextDiv.style.top = "50%";
  4896. this._loadingTextDiv.style.marginTop = "80px";
  4897. this._loadingTextDiv.style.width = "100%";
  4898. this._loadingTextDiv.style.height = "20px";
  4899. this._loadingTextDiv.style.fontFamily = "Arial";
  4900. this._loadingTextDiv.style.fontSize = "14px";
  4901. this._loadingTextDiv.style.color = "white";
  4902. this._loadingTextDiv.style.textAlign = "center";
  4903. this._loadingTextDiv.innerHTML = "Loading";
  4904. this._loadingDiv.appendChild(this._loadingTextDiv);
  4905. // Loading img
  4906. var imgBack = new Image();
  4907. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  4908. imgBack.style.position = "absolute";
  4909. imgBack.style.left = "50%";
  4910. imgBack.style.top = "50%";
  4911. imgBack.style.marginLeft = "-50px";
  4912. imgBack.style.marginTop = "-50px";
  4913. imgBack.style.transition = "transform 1.0s ease";
  4914. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4915. var deg = 360;
  4916. var onTransitionEnd = function () {
  4917. deg += 360;
  4918. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4919. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4920. };
  4921. imgBack.addEventListener("transitionend", onTransitionEnd);
  4922. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4923. this._loadingDiv.appendChild(imgBack);
  4924. // front image
  4925. var imgFront = new Image();
  4926. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  4927. imgFront.style.position = "absolute";
  4928. imgFront.style.left = "50%";
  4929. imgFront.style.top = "50%";
  4930. imgFront.style.marginLeft = "-50px";
  4931. imgFront.style.marginTop = "-50px";
  4932. this._loadingDiv.appendChild(imgFront);
  4933. // Resize
  4934. this._resizeLoadingUI = function () {
  4935. var canvasRect = _this.getRenderingCanvasClientRect();
  4936. _this._loadingDiv.style.position = "absolute";
  4937. _this._loadingDiv.style.left = canvasRect.left + "px";
  4938. _this._loadingDiv.style.top = canvasRect.top + "px";
  4939. _this._loadingDiv.style.width = canvasRect.width + "px";
  4940. _this._loadingDiv.style.height = canvasRect.height + "px";
  4941. };
  4942. this._resizeLoadingUI();
  4943. window.addEventListener("resize", this._resizeLoadingUI);
  4944. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4945. document.body.appendChild(this._loadingDiv);
  4946. setTimeout(function () {
  4947. _this._loadingDiv.style.opacity = "1";
  4948. imgBack.style.transform = "rotateZ(360deg)";
  4949. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4950. }, 0);
  4951. };
  4952. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4953. set: function (text) {
  4954. if (!this._loadingDiv) {
  4955. return;
  4956. }
  4957. this._loadingTextDiv.innerHTML = text;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4963. get: function () {
  4964. return this._loadingDivBackgroundColor;
  4965. },
  4966. set: function (color) {
  4967. this._loadingDivBackgroundColor = color;
  4968. if (!this._loadingDiv) {
  4969. return;
  4970. }
  4971. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Engine.prototype.hideLoadingUI = function () {
  4977. var _this = this;
  4978. if (!this._loadingDiv) {
  4979. return;
  4980. }
  4981. var onTransitionEnd = function () {
  4982. if (!_this._loadingDiv) {
  4983. return;
  4984. }
  4985. document.body.removeChild(_this._loadingDiv);
  4986. window.removeEventListener("resize", _this._resizeLoadingUI);
  4987. _this._loadingDiv = null;
  4988. };
  4989. this._loadingDiv.style.opacity = "0";
  4990. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4991. };
  4992. // FPS
  4993. Engine.prototype.getFps = function () {
  4994. return this.fps;
  4995. };
  4996. Engine.prototype.getDeltaTime = function () {
  4997. return this.deltaTime;
  4998. };
  4999. Engine.prototype._measureFps = function () {
  5000. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5001. var length = this.previousFramesDuration.length;
  5002. if (length >= 2) {
  5003. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5004. }
  5005. if (length >= this.fpsRange) {
  5006. if (length > this.fpsRange) {
  5007. this.previousFramesDuration.splice(0, 1);
  5008. length = this.previousFramesDuration.length;
  5009. }
  5010. var sum = 0;
  5011. for (var id = 0; id < length - 1; id++) {
  5012. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5013. }
  5014. this.fps = 1000.0 / (sum / (length - 1));
  5015. }
  5016. };
  5017. // Statics
  5018. Engine.isSupported = function () {
  5019. try {
  5020. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5021. if (navigator.isCocoonJS) {
  5022. return true;
  5023. }
  5024. var tempcanvas = document.createElement("canvas");
  5025. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5026. return gl != null && !!window.WebGLRenderingContext;
  5027. }
  5028. catch (e) {
  5029. return false;
  5030. }
  5031. };
  5032. // Const statics
  5033. Engine._ALPHA_DISABLE = 0;
  5034. Engine._ALPHA_ADD = 1;
  5035. Engine._ALPHA_COMBINE = 2;
  5036. Engine._DELAYLOADSTATE_NONE = 0;
  5037. Engine._DELAYLOADSTATE_LOADED = 1;
  5038. Engine._DELAYLOADSTATE_LOADING = 2;
  5039. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5040. Engine._TEXTUREFORMAT_ALPHA = 0;
  5041. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5042. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5043. Engine._TEXTUREFORMAT_RGB = 4;
  5044. Engine._TEXTUREFORMAT_RGBA = 4;
  5045. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5046. Engine._TEXTURETYPE_FLOAT = 1;
  5047. // Updatable statics so stick with vars here
  5048. Engine.Epsilon = 0.001;
  5049. Engine.CollisionsEpsilon = 0.001;
  5050. Engine.ShadersRepository = "Babylon/Shaders/";
  5051. return Engine;
  5052. })();
  5053. BABYLON.Engine = Engine;
  5054. })(BABYLON || (BABYLON = {}));
  5055. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5056. (function (BABYLON) {
  5057. /**
  5058. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5059. */
  5060. var Node = (function () {
  5061. /**
  5062. * @constructor
  5063. * @param {string} name - the name and id to be given to this node
  5064. * @param {BABYLON.Scene} the scene this node will be added to
  5065. */
  5066. function Node(name, scene) {
  5067. this.state = "";
  5068. this.animations = new Array();
  5069. this._childrenFlag = -1;
  5070. this._isEnabled = true;
  5071. this._isReady = true;
  5072. this._currentRenderId = -1;
  5073. this.name = name;
  5074. this.id = name;
  5075. this._scene = scene;
  5076. this._initCache();
  5077. }
  5078. Node.prototype.getScene = function () {
  5079. return this._scene;
  5080. };
  5081. Node.prototype.getEngine = function () {
  5082. return this._scene.getEngine();
  5083. };
  5084. // override it in derived class
  5085. Node.prototype.getWorldMatrix = function () {
  5086. return BABYLON.Matrix.Identity();
  5087. };
  5088. // override it in derived class if you add new variables to the cache
  5089. // and call the parent class method
  5090. Node.prototype._initCache = function () {
  5091. this._cache = {};
  5092. this._cache.parent = undefined;
  5093. };
  5094. Node.prototype.updateCache = function (force) {
  5095. if (!force && this.isSynchronized())
  5096. return;
  5097. this._cache.parent = this.parent;
  5098. this._updateCache();
  5099. };
  5100. // override it in derived class if you add new variables to the cache
  5101. // and call the parent class method if !ignoreParentClass
  5102. Node.prototype._updateCache = function (ignoreParentClass) {
  5103. };
  5104. // override it in derived class if you add new variables to the cache
  5105. Node.prototype._isSynchronized = function () {
  5106. return true;
  5107. };
  5108. Node.prototype.isSynchronizedWithParent = function () {
  5109. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5110. };
  5111. Node.prototype.isSynchronized = function (updateCache) {
  5112. var check = this.hasNewParent();
  5113. check = check || !this.isSynchronizedWithParent();
  5114. check = check || !this._isSynchronized();
  5115. if (updateCache)
  5116. this.updateCache(true);
  5117. return !check;
  5118. };
  5119. Node.prototype.hasNewParent = function (update) {
  5120. if (this._cache.parent === this.parent)
  5121. return false;
  5122. if (update)
  5123. this._cache.parent = this.parent;
  5124. return true;
  5125. };
  5126. /**
  5127. * Is this node ready to be used/rendered
  5128. * @return {boolean} is it ready
  5129. */
  5130. Node.prototype.isReady = function () {
  5131. return this._isReady;
  5132. };
  5133. /**
  5134. * Is this node enabled.
  5135. * If the node has a parent and is enabled, the parent will be inspected as well.
  5136. * @return {boolean} whether this node (and its parent) is enabled.
  5137. * @see setEnabled
  5138. */
  5139. Node.prototype.isEnabled = function () {
  5140. if (!this._isEnabled) {
  5141. return false;
  5142. }
  5143. if (this.parent) {
  5144. return this.parent.isEnabled();
  5145. }
  5146. return true;
  5147. };
  5148. /**
  5149. * Set the enabled state of this node.
  5150. * @param {boolean} value - the new enabled state
  5151. * @see isEnabled
  5152. */
  5153. Node.prototype.setEnabled = function (value) {
  5154. this._isEnabled = value;
  5155. };
  5156. /**
  5157. * Is this node a descendant of the given node.
  5158. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5159. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5160. * @see parent
  5161. */
  5162. Node.prototype.isDescendantOf = function (ancestor) {
  5163. if (this.parent) {
  5164. if (this.parent === ancestor) {
  5165. return true;
  5166. }
  5167. return this.parent.isDescendantOf(ancestor);
  5168. }
  5169. return false;
  5170. };
  5171. Node.prototype._getDescendants = function (list, results) {
  5172. for (var index = 0; index < list.length; index++) {
  5173. var item = list[index];
  5174. if (item.isDescendantOf(this)) {
  5175. results.push(item);
  5176. }
  5177. }
  5178. };
  5179. /**
  5180. * Will return all nodes that have this node as parent.
  5181. * @return {BABYLON.Node[]} all children nodes of all types.
  5182. */
  5183. Node.prototype.getDescendants = function () {
  5184. var results = [];
  5185. this._getDescendants(this._scene.meshes, results);
  5186. this._getDescendants(this._scene.lights, results);
  5187. this._getDescendants(this._scene.cameras, results);
  5188. return results;
  5189. };
  5190. Node.prototype._setReady = function (state) {
  5191. if (state == this._isReady) {
  5192. return;
  5193. }
  5194. if (!state) {
  5195. this._isReady = false;
  5196. return;
  5197. }
  5198. this._isReady = true;
  5199. if (this.onReady) {
  5200. this.onReady(this);
  5201. }
  5202. };
  5203. return Node;
  5204. })();
  5205. BABYLON.Node = Node;
  5206. })(BABYLON || (BABYLON = {}));
  5207. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5208. (function (BABYLON) {
  5209. var BoundingSphere = (function () {
  5210. function BoundingSphere(minimum, maximum) {
  5211. this.minimum = minimum;
  5212. this.maximum = maximum;
  5213. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5214. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5215. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5216. this.radius = distance * 0.5;
  5217. this.centerWorld = BABYLON.Vector3.Zero();
  5218. this._update(BABYLON.Matrix.Identity());
  5219. }
  5220. // Methods
  5221. BoundingSphere.prototype._update = function (world) {
  5222. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5223. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5224. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5225. };
  5226. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5227. for (var i = 0; i < 6; i++) {
  5228. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5229. return false;
  5230. }
  5231. return true;
  5232. };
  5233. BoundingSphere.prototype.intersectsPoint = function (point) {
  5234. var x = this.centerWorld.x - point.x;
  5235. var y = this.centerWorld.y - point.y;
  5236. var z = this.centerWorld.z - point.z;
  5237. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5238. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5239. return false;
  5240. return true;
  5241. };
  5242. // Statics
  5243. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5244. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5245. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5246. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5247. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5248. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5249. return false;
  5250. return true;
  5251. };
  5252. return BoundingSphere;
  5253. })();
  5254. BABYLON.BoundingSphere = BoundingSphere;
  5255. })(BABYLON || (BABYLON = {}));
  5256. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5257. (function (BABYLON) {
  5258. var BoundingBox = (function () {
  5259. function BoundingBox(minimum, maximum) {
  5260. this.minimum = minimum;
  5261. this.maximum = maximum;
  5262. this.vectors = new Array();
  5263. this.vectorsWorld = new Array();
  5264. // Bounding vectors
  5265. this.vectors.push(this.minimum.clone());
  5266. this.vectors.push(this.maximum.clone());
  5267. this.vectors.push(this.minimum.clone());
  5268. this.vectors[2].x = this.maximum.x;
  5269. this.vectors.push(this.minimum.clone());
  5270. this.vectors[3].y = this.maximum.y;
  5271. this.vectors.push(this.minimum.clone());
  5272. this.vectors[4].z = this.maximum.z;
  5273. this.vectors.push(this.maximum.clone());
  5274. this.vectors[5].z = this.minimum.z;
  5275. this.vectors.push(this.maximum.clone());
  5276. this.vectors[6].x = this.minimum.x;
  5277. this.vectors.push(this.maximum.clone());
  5278. this.vectors[7].y = this.minimum.y;
  5279. // OBB
  5280. this.center = this.maximum.add(this.minimum).scale(0.5);
  5281. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5282. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5283. for (var index = 0; index < this.vectors.length; index++) {
  5284. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5285. }
  5286. this.minimumWorld = BABYLON.Vector3.Zero();
  5287. this.maximumWorld = BABYLON.Vector3.Zero();
  5288. this._update(BABYLON.Matrix.Identity());
  5289. }
  5290. // Methods
  5291. BoundingBox.prototype.getWorldMatrix = function () {
  5292. return this._worldMatrix;
  5293. };
  5294. BoundingBox.prototype._update = function (world) {
  5295. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5296. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5297. for (var index = 0; index < this.vectors.length; index++) {
  5298. var v = this.vectorsWorld[index];
  5299. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5300. if (v.x < this.minimumWorld.x)
  5301. this.minimumWorld.x = v.x;
  5302. if (v.y < this.minimumWorld.y)
  5303. this.minimumWorld.y = v.y;
  5304. if (v.z < this.minimumWorld.z)
  5305. this.minimumWorld.z = v.z;
  5306. if (v.x > this.maximumWorld.x)
  5307. this.maximumWorld.x = v.x;
  5308. if (v.y > this.maximumWorld.y)
  5309. this.maximumWorld.y = v.y;
  5310. if (v.z > this.maximumWorld.z)
  5311. this.maximumWorld.z = v.z;
  5312. }
  5313. // OBB
  5314. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5315. this.center.scaleInPlace(0.5);
  5316. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5317. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5318. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5319. this._worldMatrix = world;
  5320. };
  5321. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5322. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5323. };
  5324. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5325. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5326. };
  5327. BoundingBox.prototype.intersectsPoint = function (point) {
  5328. var delta = BABYLON.Engine.Epsilon;
  5329. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5330. return false;
  5331. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5332. return false;
  5333. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5334. return false;
  5335. return true;
  5336. };
  5337. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5338. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5339. };
  5340. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5341. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5342. return false;
  5343. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5344. return false;
  5345. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5346. return false;
  5347. return true;
  5348. };
  5349. // Statics
  5350. BoundingBox.Intersects = function (box0, box1) {
  5351. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5352. return false;
  5353. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5354. return false;
  5355. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5356. return false;
  5357. return true;
  5358. };
  5359. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5360. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5361. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5362. return (num <= (sphereRadius * sphereRadius));
  5363. };
  5364. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5365. for (var p = 0; p < 6; p++) {
  5366. for (var i = 0; i < 8; i++) {
  5367. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5368. return false;
  5369. }
  5370. }
  5371. }
  5372. return true;
  5373. };
  5374. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5375. for (var p = 0; p < 6; p++) {
  5376. var inCount = 8;
  5377. for (var i = 0; i < 8; i++) {
  5378. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5379. --inCount;
  5380. }
  5381. else {
  5382. break;
  5383. }
  5384. }
  5385. if (inCount === 0)
  5386. return false;
  5387. }
  5388. return true;
  5389. };
  5390. return BoundingBox;
  5391. })();
  5392. BABYLON.BoundingBox = BoundingBox;
  5393. })(BABYLON || (BABYLON = {}));
  5394. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5395. (function (BABYLON) {
  5396. var computeBoxExtents = function (axis, box) {
  5397. var p = BABYLON.Vector3.Dot(box.center, axis);
  5398. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5399. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5400. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5401. var r = r0 + r1 + r2;
  5402. return {
  5403. min: p - r,
  5404. max: p + r
  5405. };
  5406. };
  5407. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5408. var axisOverlap = function (axis, box0, box1) {
  5409. var result0 = computeBoxExtents(axis, box0);
  5410. var result1 = computeBoxExtents(axis, box1);
  5411. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5412. };
  5413. var BoundingInfo = (function () {
  5414. function BoundingInfo(minimum, maximum) {
  5415. this.minimum = minimum;
  5416. this.maximum = maximum;
  5417. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5418. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5419. }
  5420. // Methods
  5421. BoundingInfo.prototype._update = function (world) {
  5422. this.boundingBox._update(world);
  5423. this.boundingSphere._update(world);
  5424. };
  5425. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5426. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5427. return false;
  5428. return this.boundingBox.isInFrustum(frustumPlanes);
  5429. };
  5430. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5431. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5432. };
  5433. BoundingInfo.prototype._checkCollision = function (collider) {
  5434. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5435. };
  5436. BoundingInfo.prototype.intersectsPoint = function (point) {
  5437. if (!this.boundingSphere.centerWorld) {
  5438. return false;
  5439. }
  5440. if (!this.boundingSphere.intersectsPoint(point)) {
  5441. return false;
  5442. }
  5443. if (!this.boundingBox.intersectsPoint(point)) {
  5444. return false;
  5445. }
  5446. return true;
  5447. };
  5448. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5449. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5450. return false;
  5451. }
  5452. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5453. return false;
  5454. }
  5455. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5456. return false;
  5457. }
  5458. if (!precise) {
  5459. return true;
  5460. }
  5461. var box0 = this.boundingBox;
  5462. var box1 = boundingInfo.boundingBox;
  5463. if (!axisOverlap(box0.directions[0], box0, box1))
  5464. return false;
  5465. if (!axisOverlap(box0.directions[1], box0, box1))
  5466. return false;
  5467. if (!axisOverlap(box0.directions[2], box0, box1))
  5468. return false;
  5469. if (!axisOverlap(box1.directions[0], box0, box1))
  5470. return false;
  5471. if (!axisOverlap(box1.directions[1], box0, box1))
  5472. return false;
  5473. if (!axisOverlap(box1.directions[2], box0, box1))
  5474. return false;
  5475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5476. return false;
  5477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5478. return false;
  5479. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5480. return false;
  5481. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5482. return false;
  5483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5484. return false;
  5485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5486. return false;
  5487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5488. return false;
  5489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5490. return false;
  5491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5492. return false;
  5493. return true;
  5494. };
  5495. return BoundingInfo;
  5496. })();
  5497. BABYLON.BoundingInfo = BoundingInfo;
  5498. })(BABYLON || (BABYLON = {}));
  5499. //# sourceMappingURL=babylon.boundingInfo.js.map
  5500. var BABYLON;
  5501. (function (BABYLON) {
  5502. var Light = (function (_super) {
  5503. __extends(Light, _super);
  5504. function Light(name, scene) {
  5505. _super.call(this, name, scene);
  5506. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5507. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5508. this.intensity = 1.0;
  5509. this.range = Number.MAX_VALUE;
  5510. this.includedOnlyMeshes = new Array();
  5511. this.excludedMeshes = new Array();
  5512. this._excludedMeshesIds = new Array();
  5513. this._includedOnlyMeshesIds = new Array();
  5514. scene.lights.push(this);
  5515. }
  5516. Light.prototype.getShadowGenerator = function () {
  5517. return this._shadowGenerator;
  5518. };
  5519. Light.prototype.getAbsolutePosition = function () {
  5520. return BABYLON.Vector3.Zero();
  5521. };
  5522. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5523. };
  5524. Light.prototype._getWorldMatrix = function () {
  5525. return BABYLON.Matrix.Identity();
  5526. };
  5527. Light.prototype.canAffectMesh = function (mesh) {
  5528. if (!mesh) {
  5529. return true;
  5530. }
  5531. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5532. return false;
  5533. }
  5534. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5535. return false;
  5536. }
  5537. return true;
  5538. };
  5539. Light.prototype.getWorldMatrix = function () {
  5540. this._currentRenderId = this.getScene().getRenderId();
  5541. var worldMatrix = this._getWorldMatrix();
  5542. if (this.parent && this.parent.getWorldMatrix) {
  5543. if (!this._parentedWorldMatrix) {
  5544. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5545. }
  5546. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5547. return this._parentedWorldMatrix;
  5548. }
  5549. return worldMatrix;
  5550. };
  5551. Light.prototype.dispose = function () {
  5552. if (this._shadowGenerator) {
  5553. this._shadowGenerator.dispose();
  5554. this._shadowGenerator = null;
  5555. }
  5556. // Remove from scene
  5557. var index = this.getScene().lights.indexOf(this);
  5558. this.getScene().lights.splice(index, 1);
  5559. };
  5560. return Light;
  5561. })(BABYLON.Node);
  5562. BABYLON.Light = Light;
  5563. })(BABYLON || (BABYLON = {}));
  5564. //# sourceMappingURL=babylon.light.js.map
  5565. var BABYLON;
  5566. (function (BABYLON) {
  5567. var PointLight = (function (_super) {
  5568. __extends(PointLight, _super);
  5569. function PointLight(name, position, scene) {
  5570. _super.call(this, name, scene);
  5571. this.position = position;
  5572. }
  5573. PointLight.prototype.getAbsolutePosition = function () {
  5574. return this._transformedPosition ? this._transformedPosition : this.position;
  5575. };
  5576. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5577. if (this.parent && this.parent.getWorldMatrix) {
  5578. if (!this._transformedPosition) {
  5579. this._transformedPosition = BABYLON.Vector3.Zero();
  5580. }
  5581. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5582. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5583. return;
  5584. }
  5585. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5586. };
  5587. PointLight.prototype.getShadowGenerator = function () {
  5588. return null;
  5589. };
  5590. PointLight.prototype._getWorldMatrix = function () {
  5591. if (!this._worldMatrix) {
  5592. this._worldMatrix = BABYLON.Matrix.Identity();
  5593. }
  5594. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5595. return this._worldMatrix;
  5596. };
  5597. return PointLight;
  5598. })(BABYLON.Light);
  5599. BABYLON.PointLight = PointLight;
  5600. })(BABYLON || (BABYLON = {}));
  5601. //# sourceMappingURL=babylon.pointLight.js.map
  5602. var BABYLON;
  5603. (function (BABYLON) {
  5604. var SpotLight = (function (_super) {
  5605. __extends(SpotLight, _super);
  5606. function SpotLight(name, position, direction, angle, exponent, scene) {
  5607. _super.call(this, name, scene);
  5608. this.position = position;
  5609. this.direction = direction;
  5610. this.angle = angle;
  5611. this.exponent = exponent;
  5612. }
  5613. SpotLight.prototype.getAbsolutePosition = function () {
  5614. return this.transformedPosition ? this.transformedPosition : this.position;
  5615. };
  5616. SpotLight.prototype.setDirectionToTarget = function (target) {
  5617. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5618. return this.direction;
  5619. };
  5620. SpotLight.prototype.computeTransformedPosition = function () {
  5621. if (this.parent && this.parent.getWorldMatrix) {
  5622. if (!this.transformedPosition) {
  5623. this.transformedPosition = BABYLON.Vector3.Zero();
  5624. }
  5625. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5626. return true;
  5627. }
  5628. return false;
  5629. };
  5630. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5631. var normalizeDirection;
  5632. if (this.parent && this.parent.getWorldMatrix) {
  5633. if (!this._transformedDirection) {
  5634. this._transformedDirection = BABYLON.Vector3.Zero();
  5635. }
  5636. this.computeTransformedPosition();
  5637. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5638. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5639. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5640. }
  5641. else {
  5642. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5643. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5644. }
  5645. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5646. };
  5647. SpotLight.prototype._getWorldMatrix = function () {
  5648. if (!this._worldMatrix) {
  5649. this._worldMatrix = BABYLON.Matrix.Identity();
  5650. }
  5651. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5652. return this._worldMatrix;
  5653. };
  5654. return SpotLight;
  5655. })(BABYLON.Light);
  5656. BABYLON.SpotLight = SpotLight;
  5657. })(BABYLON || (BABYLON = {}));
  5658. //# sourceMappingURL=babylon.spotLight.js.map
  5659. var BABYLON;
  5660. (function (BABYLON) {
  5661. var DirectionalLight = (function (_super) {
  5662. __extends(DirectionalLight, _super);
  5663. function DirectionalLight(name, direction, scene) {
  5664. _super.call(this, name, scene);
  5665. this.direction = direction;
  5666. this.position = direction.scale(-1);
  5667. }
  5668. DirectionalLight.prototype.getAbsolutePosition = function () {
  5669. return this.transformedPosition ? this.transformedPosition : this.position;
  5670. };
  5671. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5672. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5673. return this.direction;
  5674. };
  5675. DirectionalLight.prototype.computeTransformedPosition = function () {
  5676. if (this.parent && this.parent.getWorldMatrix) {
  5677. if (!this.transformedPosition) {
  5678. this.transformedPosition = BABYLON.Vector3.Zero();
  5679. }
  5680. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5681. return true;
  5682. }
  5683. return false;
  5684. };
  5685. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5686. if (this.parent && this.parent.getWorldMatrix) {
  5687. if (!this._transformedDirection) {
  5688. this._transformedDirection = BABYLON.Vector3.Zero();
  5689. }
  5690. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5691. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5692. return;
  5693. }
  5694. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5695. };
  5696. DirectionalLight.prototype._getWorldMatrix = function () {
  5697. if (!this._worldMatrix) {
  5698. this._worldMatrix = BABYLON.Matrix.Identity();
  5699. }
  5700. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5701. return this._worldMatrix;
  5702. };
  5703. return DirectionalLight;
  5704. })(BABYLON.Light);
  5705. BABYLON.DirectionalLight = DirectionalLight;
  5706. })(BABYLON || (BABYLON = {}));
  5707. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5708. (function (BABYLON) {
  5709. var ShadowGenerator = (function () {
  5710. function ShadowGenerator(mapSize, light) {
  5711. var _this = this;
  5712. // Members
  5713. this.filter = ShadowGenerator.FILTER_NONE;
  5714. this._darkness = 0;
  5715. this._transparencyShadow = false;
  5716. this._viewMatrix = BABYLON.Matrix.Zero();
  5717. this._projectionMatrix = BABYLON.Matrix.Zero();
  5718. this._transformMatrix = BABYLON.Matrix.Zero();
  5719. this._worldViewProjection = BABYLON.Matrix.Zero();
  5720. this._light = light;
  5721. this._scene = light.getScene();
  5722. light._shadowGenerator = this;
  5723. // Render target
  5724. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5725. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5726. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5727. this._shadowMap.renderParticles = false;
  5728. // Custom render function
  5729. var renderSubMesh = function (subMesh) {
  5730. var mesh = subMesh.getRenderingMesh();
  5731. var scene = _this._scene;
  5732. var engine = scene.getEngine();
  5733. // Culling
  5734. engine.setState(subMesh.getMaterial().backFaceCulling);
  5735. // Managing instances
  5736. var batch = mesh._getInstancesRenderList(subMesh._id);
  5737. if (batch.mustReturn) {
  5738. return;
  5739. }
  5740. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5741. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5742. engine.enableEffect(_this._effect);
  5743. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5744. var material = subMesh.getMaterial();
  5745. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5746. // Alpha test
  5747. if (material && material.needAlphaTesting()) {
  5748. var alphaTexture = material.getAlphaTestTexture();
  5749. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5750. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5751. }
  5752. // Bones
  5753. if (mesh.useBones) {
  5754. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5755. }
  5756. // Draw
  5757. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5758. }
  5759. else {
  5760. // Need to reset refresh rate of the shadowMap
  5761. _this._shadowMap.resetRefreshCounter();
  5762. }
  5763. };
  5764. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5765. var index;
  5766. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5767. renderSubMesh(opaqueSubMeshes.data[index]);
  5768. }
  5769. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5770. renderSubMesh(alphaTestSubMeshes.data[index]);
  5771. }
  5772. if (_this._transparencyShadow) {
  5773. for (index = 0; index < transparentSubMeshes.length; index++) {
  5774. renderSubMesh(transparentSubMeshes.data[index]);
  5775. }
  5776. }
  5777. };
  5778. }
  5779. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5780. // Static
  5781. get: function () {
  5782. return ShadowGenerator._FILTER_NONE;
  5783. },
  5784. enumerable: true,
  5785. configurable: true
  5786. });
  5787. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5788. get: function () {
  5789. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5790. },
  5791. enumerable: true,
  5792. configurable: true
  5793. });
  5794. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5795. get: function () {
  5796. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5797. },
  5798. enumerable: true,
  5799. configurable: true
  5800. });
  5801. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5802. get: function () {
  5803. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5804. },
  5805. set: function (value) {
  5806. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5807. },
  5808. enumerable: true,
  5809. configurable: true
  5810. });
  5811. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5812. get: function () {
  5813. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5814. },
  5815. set: function (value) {
  5816. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5817. },
  5818. enumerable: true,
  5819. configurable: true
  5820. });
  5821. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5822. var defines = [];
  5823. if (this.useVarianceShadowMap) {
  5824. defines.push("#define VSM");
  5825. }
  5826. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5827. var mesh = subMesh.getMesh();
  5828. var material = subMesh.getMaterial();
  5829. // Alpha test
  5830. if (material && material.needAlphaTesting()) {
  5831. defines.push("#define ALPHATEST");
  5832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5833. attribs.push(BABYLON.VertexBuffer.UVKind);
  5834. defines.push("#define UV1");
  5835. }
  5836. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5837. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5838. defines.push("#define UV2");
  5839. }
  5840. }
  5841. // Bones
  5842. if (mesh.useBones) {
  5843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5845. defines.push("#define BONES");
  5846. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5847. }
  5848. // Instances
  5849. if (useInstances) {
  5850. defines.push("#define INSTANCES");
  5851. attribs.push("world0");
  5852. attribs.push("world1");
  5853. attribs.push("world2");
  5854. attribs.push("world3");
  5855. }
  5856. // Get correct effect
  5857. var join = defines.join("\n");
  5858. if (this._cachedDefines !== join) {
  5859. this._cachedDefines = join;
  5860. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5861. }
  5862. return this._effect.isReady();
  5863. };
  5864. ShadowGenerator.prototype.getShadowMap = function () {
  5865. return this._shadowMap;
  5866. };
  5867. ShadowGenerator.prototype.getLight = function () {
  5868. return this._light;
  5869. };
  5870. // Methods
  5871. ShadowGenerator.prototype.getTransformMatrix = function () {
  5872. var lightPosition = this._light.position;
  5873. var lightDirection = this._light.direction;
  5874. if (this._light.computeTransformedPosition()) {
  5875. lightPosition = this._light.transformedPosition;
  5876. }
  5877. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5878. this._cachedPosition = lightPosition.clone();
  5879. this._cachedDirection = lightDirection.clone();
  5880. var activeCamera = this._scene.activeCamera;
  5881. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5882. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5883. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5884. }
  5885. return this._transformMatrix;
  5886. };
  5887. ShadowGenerator.prototype.getDarkness = function () {
  5888. return this._darkness;
  5889. };
  5890. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5891. if (darkness >= 1.0)
  5892. this._darkness = 1.0;
  5893. else if (darkness <= 0.0)
  5894. this._darkness = 0.0;
  5895. else
  5896. this._darkness = darkness;
  5897. };
  5898. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5899. this._transparencyShadow = hasShadow;
  5900. };
  5901. ShadowGenerator.prototype.dispose = function () {
  5902. this._shadowMap.dispose();
  5903. };
  5904. ShadowGenerator._FILTER_NONE = 0;
  5905. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5906. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5907. return ShadowGenerator;
  5908. })();
  5909. BABYLON.ShadowGenerator = ShadowGenerator;
  5910. })(BABYLON || (BABYLON = {}));
  5911. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5912. var BABYLON;
  5913. (function (BABYLON) {
  5914. var HemisphericLight = (function (_super) {
  5915. __extends(HemisphericLight, _super);
  5916. function HemisphericLight(name, direction, scene) {
  5917. _super.call(this, name, scene);
  5918. this.direction = direction;
  5919. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5920. }
  5921. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5922. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5923. return this.direction;
  5924. };
  5925. HemisphericLight.prototype.getShadowGenerator = function () {
  5926. return null;
  5927. };
  5928. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5929. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5930. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5931. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5932. };
  5933. HemisphericLight.prototype._getWorldMatrix = function () {
  5934. if (!this._worldMatrix) {
  5935. this._worldMatrix = BABYLON.Matrix.Identity();
  5936. }
  5937. return this._worldMatrix;
  5938. };
  5939. return HemisphericLight;
  5940. })(BABYLON.Light);
  5941. BABYLON.HemisphericLight = HemisphericLight;
  5942. })(BABYLON || (BABYLON = {}));
  5943. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5944. (function (BABYLON) {
  5945. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5946. if (boxMin.x > sphereCenter.x + sphereRadius)
  5947. return false;
  5948. if (sphereCenter.x - sphereRadius > boxMax.x)
  5949. return false;
  5950. if (boxMin.y > sphereCenter.y + sphereRadius)
  5951. return false;
  5952. if (sphereCenter.y - sphereRadius > boxMax.y)
  5953. return false;
  5954. if (boxMin.z > sphereCenter.z + sphereRadius)
  5955. return false;
  5956. if (sphereCenter.z - sphereRadius > boxMax.z)
  5957. return false;
  5958. return true;
  5959. };
  5960. var getLowestRoot = function (a, b, c, maxR) {
  5961. var determinant = b * b - 4.0 * a * c;
  5962. var result = { root: 0, found: false };
  5963. if (determinant < 0)
  5964. return result;
  5965. var sqrtD = Math.sqrt(determinant);
  5966. var r1 = (-b - sqrtD) / (2.0 * a);
  5967. var r2 = (-b + sqrtD) / (2.0 * a);
  5968. if (r1 > r2) {
  5969. var temp = r2;
  5970. r2 = r1;
  5971. r1 = temp;
  5972. }
  5973. if (r1 > 0 && r1 < maxR) {
  5974. result.root = r1;
  5975. result.found = true;
  5976. return result;
  5977. }
  5978. if (r2 > 0 && r2 < maxR) {
  5979. result.root = r2;
  5980. result.found = true;
  5981. return result;
  5982. }
  5983. return result;
  5984. };
  5985. var Collider = (function () {
  5986. function Collider() {
  5987. this.radius = new BABYLON.Vector3(1, 1, 1);
  5988. this.retry = 0;
  5989. this.basePointWorld = BABYLON.Vector3.Zero();
  5990. this.velocityWorld = BABYLON.Vector3.Zero();
  5991. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5992. this._collisionPoint = BABYLON.Vector3.Zero();
  5993. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5994. this._tempVector = BABYLON.Vector3.Zero();
  5995. this._tempVector2 = BABYLON.Vector3.Zero();
  5996. this._tempVector3 = BABYLON.Vector3.Zero();
  5997. this._tempVector4 = BABYLON.Vector3.Zero();
  5998. this._edge = BABYLON.Vector3.Zero();
  5999. this._baseToVertex = BABYLON.Vector3.Zero();
  6000. this._destinationPoint = BABYLON.Vector3.Zero();
  6001. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6002. this._displacementVector = BABYLON.Vector3.Zero();
  6003. }
  6004. // Methods
  6005. Collider.prototype._initialize = function (source, dir, e) {
  6006. this.velocity = dir;
  6007. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6008. this.basePoint = source;
  6009. source.multiplyToRef(this.radius, this.basePointWorld);
  6010. dir.multiplyToRef(this.radius, this.velocityWorld);
  6011. this.velocityWorldLength = this.velocityWorld.length();
  6012. this.epsilon = e;
  6013. this.collisionFound = false;
  6014. };
  6015. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6016. pa.subtractToRef(point, this._tempVector);
  6017. pb.subtractToRef(point, this._tempVector2);
  6018. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6019. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6020. if (d < 0)
  6021. return false;
  6022. pc.subtractToRef(point, this._tempVector3);
  6023. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6024. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6025. if (d < 0)
  6026. return false;
  6027. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6028. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6029. return d >= 0;
  6030. };
  6031. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6032. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6033. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6034. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6035. return false;
  6036. }
  6037. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6038. return false;
  6039. return true;
  6040. };
  6041. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6042. var t0;
  6043. var embeddedInPlane = false;
  6044. if (!subMesh._trianglePlanes) {
  6045. subMesh._trianglePlanes = [];
  6046. }
  6047. if (!subMesh._trianglePlanes[faceIndex]) {
  6048. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6049. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6050. }
  6051. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6052. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6053. return;
  6054. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6055. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6056. if (normalDotVelocity == 0) {
  6057. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6058. return;
  6059. embeddedInPlane = true;
  6060. t0 = 0;
  6061. }
  6062. else {
  6063. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6064. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6065. if (t0 > t1) {
  6066. var temp = t1;
  6067. t1 = t0;
  6068. t0 = temp;
  6069. }
  6070. if (t0 > 1.0 || t1 < 0.0)
  6071. return;
  6072. if (t0 < 0)
  6073. t0 = 0;
  6074. if (t0 > 1.0)
  6075. t0 = 1.0;
  6076. }
  6077. this._collisionPoint.copyFromFloats(0, 0, 0);
  6078. var found = false;
  6079. var t = 1.0;
  6080. if (!embeddedInPlane) {
  6081. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6082. this.velocity.scaleToRef(t0, this._tempVector);
  6083. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6084. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6085. found = true;
  6086. t = t0;
  6087. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6088. }
  6089. }
  6090. if (!found) {
  6091. var velocitySquaredLength = this.velocity.lengthSquared();
  6092. var a = velocitySquaredLength;
  6093. this.basePoint.subtractToRef(p1, this._tempVector);
  6094. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6095. var c = this._tempVector.lengthSquared() - 1.0;
  6096. var lowestRoot = getLowestRoot(a, b, c, t);
  6097. if (lowestRoot.found) {
  6098. t = lowestRoot.root;
  6099. found = true;
  6100. this._collisionPoint.copyFrom(p1);
  6101. }
  6102. this.basePoint.subtractToRef(p2, this._tempVector);
  6103. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6104. c = this._tempVector.lengthSquared() - 1.0;
  6105. lowestRoot = getLowestRoot(a, b, c, t);
  6106. if (lowestRoot.found) {
  6107. t = lowestRoot.root;
  6108. found = true;
  6109. this._collisionPoint.copyFrom(p2);
  6110. }
  6111. this.basePoint.subtractToRef(p3, this._tempVector);
  6112. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6113. c = this._tempVector.lengthSquared() - 1.0;
  6114. lowestRoot = getLowestRoot(a, b, c, t);
  6115. if (lowestRoot.found) {
  6116. t = lowestRoot.root;
  6117. found = true;
  6118. this._collisionPoint.copyFrom(p3);
  6119. }
  6120. p2.subtractToRef(p1, this._edge);
  6121. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6122. var edgeSquaredLength = this._edge.lengthSquared();
  6123. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6124. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6125. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6126. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6127. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6128. lowestRoot = getLowestRoot(a, b, c, t);
  6129. if (lowestRoot.found) {
  6130. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6131. if (f >= 0.0 && f <= 1.0) {
  6132. t = lowestRoot.root;
  6133. found = true;
  6134. this._edge.scaleInPlace(f);
  6135. p1.addToRef(this._edge, this._collisionPoint);
  6136. }
  6137. }
  6138. p3.subtractToRef(p2, this._edge);
  6139. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6140. edgeSquaredLength = this._edge.lengthSquared();
  6141. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6142. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6143. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6144. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6145. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6146. lowestRoot = getLowestRoot(a, b, c, t);
  6147. if (lowestRoot.found) {
  6148. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6149. if (f >= 0.0 && f <= 1.0) {
  6150. t = lowestRoot.root;
  6151. found = true;
  6152. this._edge.scaleInPlace(f);
  6153. p2.addToRef(this._edge, this._collisionPoint);
  6154. }
  6155. }
  6156. p1.subtractToRef(p3, this._edge);
  6157. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6158. edgeSquaredLength = this._edge.lengthSquared();
  6159. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6160. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6161. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6162. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6163. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6164. lowestRoot = getLowestRoot(a, b, c, t);
  6165. if (lowestRoot.found) {
  6166. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6167. if (f >= 0.0 && f <= 1.0) {
  6168. t = lowestRoot.root;
  6169. found = true;
  6170. this._edge.scaleInPlace(f);
  6171. p3.addToRef(this._edge, this._collisionPoint);
  6172. }
  6173. }
  6174. }
  6175. if (found) {
  6176. var distToCollision = t * this.velocity.length();
  6177. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6178. if (!this.intersectionPoint) {
  6179. this.intersectionPoint = this._collisionPoint.clone();
  6180. }
  6181. else {
  6182. this.intersectionPoint.copyFrom(this._collisionPoint);
  6183. }
  6184. this.nearestDistance = distToCollision;
  6185. this.collisionFound = true;
  6186. this.collidedMesh = subMesh.getMesh();
  6187. }
  6188. }
  6189. };
  6190. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6191. for (var i = indexStart; i < indexEnd; i += 3) {
  6192. var p1 = pts[indices[i] - decal];
  6193. var p2 = pts[indices[i + 1] - decal];
  6194. var p3 = pts[indices[i + 2] - decal];
  6195. this._testTriangle(i, subMesh, p3, p2, p1);
  6196. }
  6197. };
  6198. Collider.prototype._getResponse = function (pos, vel) {
  6199. pos.addToRef(vel, this._destinationPoint);
  6200. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6201. this.basePoint.addToRef(vel, pos);
  6202. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6203. this._slidePlaneNormal.normalize();
  6204. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6205. pos.addInPlace(this._displacementVector);
  6206. this.intersectionPoint.addInPlace(this._displacementVector);
  6207. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6208. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6209. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6210. };
  6211. return Collider;
  6212. })();
  6213. BABYLON.Collider = Collider;
  6214. })(BABYLON || (BABYLON = {}));
  6215. //# sourceMappingURL=babylon.collider.js.map
  6216. var BABYLON;
  6217. (function (BABYLON) {
  6218. var Camera = (function (_super) {
  6219. __extends(Camera, _super);
  6220. function Camera(name, position, scene) {
  6221. _super.call(this, name, scene);
  6222. this.position = position;
  6223. // Members
  6224. this.upVector = BABYLON.Vector3.Up();
  6225. this.orthoLeft = null;
  6226. this.orthoRight = null;
  6227. this.orthoBottom = null;
  6228. this.orthoTop = null;
  6229. this.fov = 0.8;
  6230. this.minZ = 1.0;
  6231. this.maxZ = 10000.0;
  6232. this.inertia = 0.9;
  6233. this.mode = Camera.PERSPECTIVE_CAMERA;
  6234. this.isIntermediate = false;
  6235. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6236. this.subCameras = [];
  6237. this.layerMask = 0xFFFFFFFF;
  6238. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6239. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6240. this._projectionMatrix = new BABYLON.Matrix();
  6241. this._postProcesses = new Array();
  6242. this._postProcessesTakenIndices = [];
  6243. this._activeMeshes = new BABYLON.SmartArray(256);
  6244. scene.cameras.push(this);
  6245. if (!scene.activeCamera) {
  6246. scene.activeCamera = this;
  6247. }
  6248. }
  6249. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6250. get: function () {
  6251. return Camera._PERSPECTIVE_CAMERA;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6257. get: function () {
  6258. return Camera._ORTHOGRAPHIC_CAMERA;
  6259. },
  6260. enumerable: true,
  6261. configurable: true
  6262. });
  6263. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6264. get: function () {
  6265. return Camera._FOVMODE_VERTICAL_FIXED;
  6266. },
  6267. enumerable: true,
  6268. configurable: true
  6269. });
  6270. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6271. get: function () {
  6272. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6273. },
  6274. enumerable: true,
  6275. configurable: true
  6276. });
  6277. Camera.prototype.getActiveMeshes = function () {
  6278. return this._activeMeshes;
  6279. };
  6280. Camera.prototype.isActiveMesh = function (mesh) {
  6281. return (this._activeMeshes.indexOf(mesh) !== -1);
  6282. };
  6283. //Cache
  6284. Camera.prototype._initCache = function () {
  6285. _super.prototype._initCache.call(this);
  6286. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6287. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6288. this._cache.mode = undefined;
  6289. this._cache.minZ = undefined;
  6290. this._cache.maxZ = undefined;
  6291. this._cache.fov = undefined;
  6292. this._cache.aspectRatio = undefined;
  6293. this._cache.orthoLeft = undefined;
  6294. this._cache.orthoRight = undefined;
  6295. this._cache.orthoBottom = undefined;
  6296. this._cache.orthoTop = undefined;
  6297. this._cache.renderWidth = undefined;
  6298. this._cache.renderHeight = undefined;
  6299. };
  6300. Camera.prototype._updateCache = function (ignoreParentClass) {
  6301. if (!ignoreParentClass) {
  6302. _super.prototype._updateCache.call(this);
  6303. }
  6304. var engine = this.getEngine();
  6305. this._cache.position.copyFrom(this.position);
  6306. this._cache.upVector.copyFrom(this.upVector);
  6307. this._cache.mode = this.mode;
  6308. this._cache.minZ = this.minZ;
  6309. this._cache.maxZ = this.maxZ;
  6310. this._cache.fov = this.fov;
  6311. this._cache.aspectRatio = engine.getAspectRatio(this);
  6312. this._cache.orthoLeft = this.orthoLeft;
  6313. this._cache.orthoRight = this.orthoRight;
  6314. this._cache.orthoBottom = this.orthoBottom;
  6315. this._cache.orthoTop = this.orthoTop;
  6316. this._cache.renderWidth = engine.getRenderWidth();
  6317. this._cache.renderHeight = engine.getRenderHeight();
  6318. };
  6319. Camera.prototype._updateFromScene = function () {
  6320. this.updateCache();
  6321. this._update();
  6322. };
  6323. // Synchronized
  6324. Camera.prototype._isSynchronized = function () {
  6325. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6326. };
  6327. Camera.prototype._isSynchronizedViewMatrix = function () {
  6328. if (!_super.prototype._isSynchronized.call(this))
  6329. return false;
  6330. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6331. };
  6332. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6333. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6334. if (!check) {
  6335. return false;
  6336. }
  6337. var engine = this.getEngine();
  6338. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6339. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6340. }
  6341. else {
  6342. 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();
  6343. }
  6344. return check;
  6345. };
  6346. // Controls
  6347. Camera.prototype.attachControl = function (element) {
  6348. };
  6349. Camera.prototype.detachControl = function (element) {
  6350. };
  6351. Camera.prototype._update = function () {
  6352. };
  6353. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6354. if (insertAt === void 0) { insertAt = null; }
  6355. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6356. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6357. return 0;
  6358. }
  6359. if (insertAt == null || insertAt < 0) {
  6360. this._postProcesses.push(postProcess);
  6361. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6362. return this._postProcesses.length - 1;
  6363. }
  6364. var add = 0;
  6365. if (this._postProcesses[insertAt]) {
  6366. var start = this._postProcesses.length - 1;
  6367. for (var i = start; i >= insertAt + 1; --i) {
  6368. this._postProcesses[i + 1] = this._postProcesses[i];
  6369. }
  6370. add = 1;
  6371. }
  6372. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6373. if (this._postProcessesTakenIndices[i] < insertAt) {
  6374. continue;
  6375. }
  6376. start = this._postProcessesTakenIndices.length - 1;
  6377. for (var j = start; j >= i; --j) {
  6378. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6379. }
  6380. this._postProcessesTakenIndices[i] = insertAt;
  6381. break;
  6382. }
  6383. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6384. this._postProcessesTakenIndices.push(insertAt);
  6385. }
  6386. var result = insertAt + add;
  6387. this._postProcesses[result] = postProcess;
  6388. return result;
  6389. };
  6390. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6391. if (atIndices === void 0) { atIndices = null; }
  6392. var result = [];
  6393. if (!atIndices) {
  6394. var length = this._postProcesses.length;
  6395. for (var i = 0; i < length; i++) {
  6396. if (this._postProcesses[i] !== postProcess) {
  6397. continue;
  6398. }
  6399. delete this._postProcesses[i];
  6400. var index = this._postProcessesTakenIndices.indexOf(i);
  6401. this._postProcessesTakenIndices.splice(index, 1);
  6402. }
  6403. }
  6404. else {
  6405. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6406. for (i = 0; i < atIndices.length; i++) {
  6407. var foundPostProcess = this._postProcesses[atIndices[i]];
  6408. if (foundPostProcess !== postProcess) {
  6409. result.push(i);
  6410. continue;
  6411. }
  6412. delete this._postProcesses[atIndices[i]];
  6413. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6414. this._postProcessesTakenIndices.splice(index, 1);
  6415. }
  6416. }
  6417. return result;
  6418. };
  6419. Camera.prototype.getWorldMatrix = function () {
  6420. if (!this._worldMatrix) {
  6421. this._worldMatrix = BABYLON.Matrix.Identity();
  6422. }
  6423. var viewMatrix = this.getViewMatrix();
  6424. viewMatrix.invertToRef(this._worldMatrix);
  6425. return this._worldMatrix;
  6426. };
  6427. Camera.prototype._getViewMatrix = function () {
  6428. return BABYLON.Matrix.Identity();
  6429. };
  6430. Camera.prototype.getViewMatrix = function () {
  6431. this._computedViewMatrix = this._computeViewMatrix();
  6432. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6433. return this._computedViewMatrix;
  6434. }
  6435. if (!this._worldMatrix) {
  6436. this._worldMatrix = BABYLON.Matrix.Identity();
  6437. }
  6438. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6439. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6440. this._computedViewMatrix.invert();
  6441. this._currentRenderId = this.getScene().getRenderId();
  6442. return this._computedViewMatrix;
  6443. };
  6444. Camera.prototype._computeViewMatrix = function (force) {
  6445. if (!force && this._isSynchronizedViewMatrix()) {
  6446. return this._computedViewMatrix;
  6447. }
  6448. this._computedViewMatrix = this._getViewMatrix();
  6449. if (!this.parent || !this.parent.getWorldMatrix) {
  6450. this._currentRenderId = this.getScene().getRenderId();
  6451. }
  6452. return this._computedViewMatrix;
  6453. };
  6454. Camera.prototype.getProjectionMatrix = function (force) {
  6455. if (!force && this._isSynchronizedProjectionMatrix()) {
  6456. return this._projectionMatrix;
  6457. }
  6458. var engine = this.getEngine();
  6459. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6460. if (this.minZ <= 0) {
  6461. this.minZ = 0.1;
  6462. }
  6463. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6464. return this._projectionMatrix;
  6465. }
  6466. var halfWidth = engine.getRenderWidth() / 2.0;
  6467. var halfHeight = engine.getRenderHeight() / 2.0;
  6468. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6469. return this._projectionMatrix;
  6470. };
  6471. Camera.prototype.dispose = function () {
  6472. // Remove from scene
  6473. var index = this.getScene().cameras.indexOf(this);
  6474. this.getScene().cameras.splice(index, 1);
  6475. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6476. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6477. }
  6478. };
  6479. // Statics
  6480. Camera._PERSPECTIVE_CAMERA = 0;
  6481. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6482. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6483. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6484. return Camera;
  6485. })(BABYLON.Node);
  6486. BABYLON.Camera = Camera;
  6487. })(BABYLON || (BABYLON = {}));
  6488. //# sourceMappingURL=babylon.camera.js.map
  6489. var BABYLON;
  6490. (function (BABYLON) {
  6491. var TargetCamera = (function (_super) {
  6492. __extends(TargetCamera, _super);
  6493. function TargetCamera(name, position, scene) {
  6494. _super.call(this, name, position, scene);
  6495. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6496. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6497. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6498. this.speed = 2.0;
  6499. this.noRotationConstraint = false;
  6500. this.lockedTarget = null;
  6501. this._currentTarget = BABYLON.Vector3.Zero();
  6502. this._viewMatrix = BABYLON.Matrix.Zero();
  6503. this._camMatrix = BABYLON.Matrix.Zero();
  6504. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6505. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6506. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6507. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6508. this._lookAtTemp = BABYLON.Matrix.Zero();
  6509. this._tempMatrix = BABYLON.Matrix.Zero();
  6510. }
  6511. TargetCamera.prototype._getLockedTargetPosition = function () {
  6512. if (!this.lockedTarget) {
  6513. return null;
  6514. }
  6515. return this.lockedTarget.position || this.lockedTarget;
  6516. };
  6517. // Cache
  6518. TargetCamera.prototype._initCache = function () {
  6519. _super.prototype._initCache.call(this);
  6520. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6521. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6522. };
  6523. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6524. if (!ignoreParentClass) {
  6525. _super.prototype._updateCache.call(this);
  6526. }
  6527. var lockedTargetPosition = this._getLockedTargetPosition();
  6528. if (!lockedTargetPosition) {
  6529. this._cache.lockedTarget = null;
  6530. }
  6531. else {
  6532. if (!this._cache.lockedTarget) {
  6533. this._cache.lockedTarget = lockedTargetPosition.clone();
  6534. }
  6535. else {
  6536. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6537. }
  6538. }
  6539. this._cache.rotation.copyFrom(this.rotation);
  6540. };
  6541. // Synchronized
  6542. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6543. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6544. return false;
  6545. }
  6546. var lockedTargetPosition = this._getLockedTargetPosition();
  6547. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6548. };
  6549. // Methods
  6550. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6551. var engine = this.getEngine();
  6552. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6553. };
  6554. // Target
  6555. TargetCamera.prototype.setTarget = function (target) {
  6556. this.upVector.normalize();
  6557. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6558. this._camMatrix.invert();
  6559. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6560. var vDir = target.subtract(this.position);
  6561. if (vDir.x >= 0.0) {
  6562. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6563. }
  6564. else {
  6565. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6566. }
  6567. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6568. if (isNaN(this.rotation.x)) {
  6569. this.rotation.x = 0;
  6570. }
  6571. if (isNaN(this.rotation.y)) {
  6572. this.rotation.y = 0;
  6573. }
  6574. if (isNaN(this.rotation.z)) {
  6575. this.rotation.z = 0;
  6576. }
  6577. };
  6578. TargetCamera.prototype.getTarget = function () {
  6579. return this._currentTarget;
  6580. };
  6581. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6582. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6583. };
  6584. TargetCamera.prototype._updatePosition = function () {
  6585. this.position.addInPlace(this.cameraDirection);
  6586. };
  6587. TargetCamera.prototype._update = function () {
  6588. var needToMove = this._decideIfNeedsToMove();
  6589. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6590. // Move
  6591. if (needToMove) {
  6592. this._updatePosition();
  6593. }
  6594. // Rotate
  6595. if (needToRotate) {
  6596. this.rotation.x += this.cameraRotation.x;
  6597. this.rotation.y += this.cameraRotation.y;
  6598. if (!this.noRotationConstraint) {
  6599. var limit = (Math.PI / 2) * 0.95;
  6600. if (this.rotation.x > limit)
  6601. this.rotation.x = limit;
  6602. if (this.rotation.x < -limit)
  6603. this.rotation.x = -limit;
  6604. }
  6605. }
  6606. // Inertia
  6607. if (needToMove) {
  6608. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6609. this.cameraDirection.x = 0;
  6610. }
  6611. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6612. this.cameraDirection.y = 0;
  6613. }
  6614. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6615. this.cameraDirection.z = 0;
  6616. }
  6617. this.cameraDirection.scaleInPlace(this.inertia);
  6618. }
  6619. if (needToRotate) {
  6620. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6621. this.cameraRotation.x = 0;
  6622. }
  6623. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6624. this.cameraRotation.y = 0;
  6625. }
  6626. this.cameraRotation.scaleInPlace(this.inertia);
  6627. }
  6628. };
  6629. TargetCamera.prototype._getViewMatrix = function () {
  6630. if (!this.lockedTarget) {
  6631. // Compute
  6632. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6633. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6634. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6635. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6636. this._lookAtTemp.invert();
  6637. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6638. }
  6639. else {
  6640. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6641. }
  6642. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6643. // Computing target and final matrix
  6644. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6645. }
  6646. else {
  6647. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6648. }
  6649. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6650. return this._viewMatrix;
  6651. };
  6652. return TargetCamera;
  6653. })(BABYLON.Camera);
  6654. BABYLON.TargetCamera = TargetCamera;
  6655. })(BABYLON || (BABYLON = {}));
  6656. //# sourceMappingURL=babylon.targetCamera.js.map
  6657. var BABYLON;
  6658. (function (BABYLON) {
  6659. var FollowCamera = (function (_super) {
  6660. __extends(FollowCamera, _super);
  6661. function FollowCamera(name, position, scene) {
  6662. _super.call(this, name, position, scene);
  6663. this.radius = 12;
  6664. this.rotationOffset = 0;
  6665. this.heightOffset = 4;
  6666. this.cameraAcceleration = 0.05;
  6667. this.maxCameraSpeed = 20;
  6668. }
  6669. FollowCamera.prototype.getRadians = function (degrees) {
  6670. return degrees * Math.PI / 180;
  6671. };
  6672. FollowCamera.prototype.follow = function (cameraTarget) {
  6673. if (!cameraTarget)
  6674. return;
  6675. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6676. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6677. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6678. var dx = targetX - this.position.x;
  6679. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6680. var dz = (targetZ) - this.position.z;
  6681. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6682. var vy = dy * this.cameraAcceleration;
  6683. var vz = dz * this.cameraAcceleration * 2;
  6684. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6685. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6686. }
  6687. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6688. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6689. }
  6690. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6691. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6692. }
  6693. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6694. this.setTarget(cameraTarget.position);
  6695. };
  6696. FollowCamera.prototype._update = function () {
  6697. _super.prototype._update.call(this);
  6698. this.follow(this.target);
  6699. };
  6700. return FollowCamera;
  6701. })(BABYLON.TargetCamera);
  6702. BABYLON.FollowCamera = FollowCamera;
  6703. })(BABYLON || (BABYLON = {}));
  6704. //# sourceMappingURL=babylon.followCamera.js.map
  6705. var BABYLON;
  6706. (function (BABYLON) {
  6707. var FreeCamera = (function (_super) {
  6708. __extends(FreeCamera, _super);
  6709. function FreeCamera(name, position, scene) {
  6710. _super.call(this, name, position, scene);
  6711. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6712. this.keysUp = [38];
  6713. this.keysDown = [40];
  6714. this.keysLeft = [37];
  6715. this.keysRight = [39];
  6716. this.checkCollisions = false;
  6717. this.applyGravity = false;
  6718. this.angularSensibility = 2000.0;
  6719. this._keys = [];
  6720. this._collider = new BABYLON.Collider();
  6721. this._needMoveForGravity = true;
  6722. this._oldPosition = BABYLON.Vector3.Zero();
  6723. this._diffPosition = BABYLON.Vector3.Zero();
  6724. this._newPosition = BABYLON.Vector3.Zero();
  6725. }
  6726. // Controls
  6727. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6728. var _this = this;
  6729. var previousPosition;
  6730. var engine = this.getEngine();
  6731. if (this._attachedElement) {
  6732. return;
  6733. }
  6734. this._attachedElement = element;
  6735. if (this._onMouseDown === undefined) {
  6736. this._onMouseDown = function (evt) {
  6737. previousPosition = {
  6738. x: evt.clientX,
  6739. y: evt.clientY
  6740. };
  6741. if (!noPreventDefault) {
  6742. evt.preventDefault();
  6743. }
  6744. };
  6745. this._onMouseUp = function (evt) {
  6746. previousPosition = null;
  6747. if (!noPreventDefault) {
  6748. evt.preventDefault();
  6749. }
  6750. };
  6751. this._onMouseOut = function (evt) {
  6752. previousPosition = null;
  6753. _this._keys = [];
  6754. if (!noPreventDefault) {
  6755. evt.preventDefault();
  6756. }
  6757. };
  6758. this._onMouseMove = function (evt) {
  6759. if (!previousPosition && !engine.isPointerLock) {
  6760. return;
  6761. }
  6762. var offsetX;
  6763. var offsetY;
  6764. if (!engine.isPointerLock) {
  6765. offsetX = evt.clientX - previousPosition.x;
  6766. offsetY = evt.clientY - previousPosition.y;
  6767. }
  6768. else {
  6769. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6770. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6771. }
  6772. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6773. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6774. previousPosition = {
  6775. x: evt.clientX,
  6776. y: evt.clientY
  6777. };
  6778. if (!noPreventDefault) {
  6779. evt.preventDefault();
  6780. }
  6781. };
  6782. this._onKeyDown = function (evt) {
  6783. 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) {
  6784. var index = _this._keys.indexOf(evt.keyCode);
  6785. if (index === -1) {
  6786. _this._keys.push(evt.keyCode);
  6787. }
  6788. if (!noPreventDefault) {
  6789. evt.preventDefault();
  6790. }
  6791. }
  6792. };
  6793. this._onKeyUp = function (evt) {
  6794. 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) {
  6795. var index = _this._keys.indexOf(evt.keyCode);
  6796. if (index >= 0) {
  6797. _this._keys.splice(index, 1);
  6798. }
  6799. if (!noPreventDefault) {
  6800. evt.preventDefault();
  6801. }
  6802. }
  6803. };
  6804. this._onLostFocus = function () {
  6805. _this._keys = [];
  6806. };
  6807. this._reset = function () {
  6808. _this._keys = [];
  6809. previousPosition = null;
  6810. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6811. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6812. };
  6813. }
  6814. element.addEventListener("mousedown", this._onMouseDown, false);
  6815. element.addEventListener("mouseup", this._onMouseUp, false);
  6816. element.addEventListener("mouseout", this._onMouseOut, false);
  6817. element.addEventListener("mousemove", this._onMouseMove, false);
  6818. BABYLON.Tools.RegisterTopRootEvents([
  6819. { name: "keydown", handler: this._onKeyDown },
  6820. { name: "keyup", handler: this._onKeyUp },
  6821. { name: "blur", handler: this._onLostFocus }
  6822. ]);
  6823. };
  6824. FreeCamera.prototype.detachControl = function (element) {
  6825. if (this._attachedElement != element) {
  6826. return;
  6827. }
  6828. element.removeEventListener("mousedown", this._onMouseDown);
  6829. element.removeEventListener("mouseup", this._onMouseUp);
  6830. element.removeEventListener("mouseout", this._onMouseOut);
  6831. element.removeEventListener("mousemove", this._onMouseMove);
  6832. BABYLON.Tools.UnregisterTopRootEvents([
  6833. { name: "keydown", handler: this._onKeyDown },
  6834. { name: "keyup", handler: this._onKeyUp },
  6835. { name: "blur", handler: this._onLostFocus }
  6836. ]);
  6837. this._attachedElement = null;
  6838. if (this._reset) {
  6839. this._reset();
  6840. }
  6841. };
  6842. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6843. var globalPosition;
  6844. if (this.parent) {
  6845. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6846. }
  6847. else {
  6848. globalPosition = this.position;
  6849. }
  6850. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6851. this._collider.radius = this.ellipsoid;
  6852. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6853. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6854. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6855. this.position.addInPlace(this._diffPosition);
  6856. if (this.onCollide) {
  6857. this.onCollide(this._collider.collidedMesh);
  6858. }
  6859. }
  6860. };
  6861. FreeCamera.prototype._checkInputs = function () {
  6862. if (!this._localDirection) {
  6863. this._localDirection = BABYLON.Vector3.Zero();
  6864. this._transformedDirection = BABYLON.Vector3.Zero();
  6865. }
  6866. for (var index = 0; index < this._keys.length; index++) {
  6867. var keyCode = this._keys[index];
  6868. var speed = this._computeLocalCameraSpeed();
  6869. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6870. this._localDirection.copyFromFloats(-speed, 0, 0);
  6871. }
  6872. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6873. this._localDirection.copyFromFloats(0, 0, speed);
  6874. }
  6875. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6876. this._localDirection.copyFromFloats(speed, 0, 0);
  6877. }
  6878. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6879. this._localDirection.copyFromFloats(0, 0, -speed);
  6880. }
  6881. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6882. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6883. this.cameraDirection.addInPlace(this._transformedDirection);
  6884. }
  6885. };
  6886. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6887. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6888. };
  6889. FreeCamera.prototype._updatePosition = function () {
  6890. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6891. this._collideWithWorld(this.cameraDirection);
  6892. if (this.applyGravity) {
  6893. var oldPosition = this.position;
  6894. this._collideWithWorld(this.getScene().gravity);
  6895. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6896. }
  6897. }
  6898. else {
  6899. this.position.addInPlace(this.cameraDirection);
  6900. }
  6901. };
  6902. FreeCamera.prototype._update = function () {
  6903. this._checkInputs();
  6904. _super.prototype._update.call(this);
  6905. };
  6906. return FreeCamera;
  6907. })(BABYLON.TargetCamera);
  6908. BABYLON.FreeCamera = FreeCamera;
  6909. })(BABYLON || (BABYLON = {}));
  6910. //# sourceMappingURL=babylon.freeCamera.js.map
  6911. var BABYLON;
  6912. (function (BABYLON) {
  6913. // We're mainly based on the logic defined into the FreeCamera code
  6914. var TouchCamera = (function (_super) {
  6915. __extends(TouchCamera, _super);
  6916. function TouchCamera(name, position, scene) {
  6917. _super.call(this, name, position, scene);
  6918. this._offsetX = null;
  6919. this._offsetY = null;
  6920. this._pointerCount = 0;
  6921. this._pointerPressed = [];
  6922. this.angularSensibility = 200000.0;
  6923. this.moveSensibility = 500.0;
  6924. }
  6925. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6926. var _this = this;
  6927. var previousPosition;
  6928. if (this._attachedCanvas) {
  6929. return;
  6930. }
  6931. this._attachedCanvas = canvas;
  6932. if (this._onPointerDown === undefined) {
  6933. this._onPointerDown = function (evt) {
  6934. if (!noPreventDefault) {
  6935. evt.preventDefault();
  6936. }
  6937. _this._pointerPressed.push(evt.pointerId);
  6938. if (_this._pointerPressed.length !== 1) {
  6939. return;
  6940. }
  6941. previousPosition = {
  6942. x: evt.clientX,
  6943. y: evt.clientY
  6944. };
  6945. };
  6946. this._onPointerUp = function (evt) {
  6947. if (!noPreventDefault) {
  6948. evt.preventDefault();
  6949. }
  6950. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6951. if (index === -1) {
  6952. return;
  6953. }
  6954. _this._pointerPressed.splice(index, 1);
  6955. if (index != 0) {
  6956. return;
  6957. }
  6958. previousPosition = null;
  6959. _this._offsetX = null;
  6960. _this._offsetY = null;
  6961. };
  6962. this._onPointerMove = function (evt) {
  6963. if (!noPreventDefault) {
  6964. evt.preventDefault();
  6965. }
  6966. if (!previousPosition) {
  6967. return;
  6968. }
  6969. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6970. if (index != 0) {
  6971. return;
  6972. }
  6973. _this._offsetX = evt.clientX - previousPosition.x;
  6974. _this._offsetY = -(evt.clientY - previousPosition.y);
  6975. };
  6976. this._onLostFocus = function () {
  6977. _this._offsetX = null;
  6978. _this._offsetY = null;
  6979. };
  6980. }
  6981. canvas.addEventListener("pointerdown", this._onPointerDown);
  6982. canvas.addEventListener("pointerup", this._onPointerUp);
  6983. canvas.addEventListener("pointerout", this._onPointerUp);
  6984. canvas.addEventListener("pointermove", this._onPointerMove);
  6985. BABYLON.Tools.RegisterTopRootEvents([
  6986. { name: "blur", handler: this._onLostFocus }
  6987. ]);
  6988. };
  6989. TouchCamera.prototype.detachControl = function (canvas) {
  6990. if (this._attachedCanvas != canvas) {
  6991. return;
  6992. }
  6993. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6994. canvas.removeEventListener("pointerup", this._onPointerUp);
  6995. canvas.removeEventListener("pointerout", this._onPointerUp);
  6996. canvas.removeEventListener("pointermove", this._onPointerMove);
  6997. BABYLON.Tools.UnregisterTopRootEvents([
  6998. { name: "blur", handler: this._onLostFocus }
  6999. ]);
  7000. this._attachedCanvas = null;
  7001. };
  7002. TouchCamera.prototype._checkInputs = function () {
  7003. if (!this._offsetX) {
  7004. return;
  7005. }
  7006. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7007. if (this._pointerPressed.length > 1) {
  7008. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7009. }
  7010. else {
  7011. var speed = this._computeLocalCameraSpeed();
  7012. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7013. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7014. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7015. }
  7016. };
  7017. return TouchCamera;
  7018. })(BABYLON.FreeCamera);
  7019. BABYLON.TouchCamera = TouchCamera;
  7020. })(BABYLON || (BABYLON = {}));
  7021. //# sourceMappingURL=babylon.touchCamera.js.map
  7022. var BABYLON;
  7023. (function (BABYLON) {
  7024. // We're mainly based on the logic defined into the FreeCamera code
  7025. var DeviceOrientationCamera = (function (_super) {
  7026. __extends(DeviceOrientationCamera, _super);
  7027. function DeviceOrientationCamera(name, position, scene) {
  7028. var _this = this;
  7029. _super.call(this, name, position, scene);
  7030. this._offsetX = null;
  7031. this._offsetY = null;
  7032. this._orientationGamma = 0;
  7033. this._orientationBeta = 0;
  7034. this._initialOrientationGamma = 0;
  7035. this._initialOrientationBeta = 0;
  7036. this.angularSensibility = 10000.0;
  7037. this.moveSensibility = 50.0;
  7038. window.addEventListener("resize", function () {
  7039. _this._initialOrientationGamma = null;
  7040. }, false);
  7041. }
  7042. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7043. var _this = this;
  7044. if (this._attachedCanvas) {
  7045. return;
  7046. }
  7047. this._attachedCanvas = canvas;
  7048. if (!this._orientationChanged) {
  7049. this._orientationChanged = function (evt) {
  7050. if (!_this._initialOrientationGamma) {
  7051. _this._initialOrientationGamma = evt.gamma;
  7052. _this._initialOrientationBeta = evt.beta;
  7053. }
  7054. _this._orientationGamma = evt.gamma;
  7055. _this._orientationBeta = evt.beta;
  7056. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7057. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7058. };
  7059. }
  7060. window.addEventListener("deviceorientation", this._orientationChanged);
  7061. };
  7062. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7063. if (this._attachedCanvas != canvas) {
  7064. return;
  7065. }
  7066. window.removeEventListener("deviceorientation", this._orientationChanged);
  7067. this._attachedCanvas = null;
  7068. this._orientationGamma = 0;
  7069. this._orientationBeta = 0;
  7070. this._initialOrientationGamma = 0;
  7071. this._initialOrientationBeta = 0;
  7072. };
  7073. DeviceOrientationCamera.prototype._checkInputs = function () {
  7074. if (!this._offsetX) {
  7075. return;
  7076. }
  7077. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7078. var speed = this._computeLocalCameraSpeed();
  7079. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7080. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7081. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7082. };
  7083. return DeviceOrientationCamera;
  7084. })(BABYLON.FreeCamera);
  7085. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7086. })(BABYLON || (BABYLON = {}));
  7087. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7088. var BABYLON;
  7089. (function (BABYLON) {
  7090. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7091. var ArcRotateCamera = (function (_super) {
  7092. __extends(ArcRotateCamera, _super);
  7093. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7094. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7095. this.alpha = alpha;
  7096. this.beta = beta;
  7097. this.radius = radius;
  7098. this.target = target;
  7099. this.inertialAlphaOffset = 0;
  7100. this.inertialBetaOffset = 0;
  7101. this.inertialRadiusOffset = 0;
  7102. this.lowerAlphaLimit = null;
  7103. this.upperAlphaLimit = null;
  7104. this.lowerBetaLimit = 0.01;
  7105. this.upperBetaLimit = Math.PI;
  7106. this.lowerRadiusLimit = null;
  7107. this.upperRadiusLimit = null;
  7108. this.angularSensibility = 1000.0;
  7109. this.wheelPrecision = 3.0;
  7110. this.keysUp = [38];
  7111. this.keysDown = [40];
  7112. this.keysLeft = [37];
  7113. this.keysRight = [39];
  7114. this.zoomOnFactor = 1;
  7115. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7116. this._keys = [];
  7117. this._viewMatrix = new BABYLON.Matrix();
  7118. this.checkCollisions = false;
  7119. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7120. this._collider = new BABYLON.Collider();
  7121. this._previousPosition = BABYLON.Vector3.Zero();
  7122. this._collisionVelocity = BABYLON.Vector3.Zero();
  7123. this._newPosition = BABYLON.Vector3.Zero();
  7124. // Pinch
  7125. // value for pinch step scaling
  7126. // set to 20 by default
  7127. this.pinchPrecision = 20;
  7128. this.getViewMatrix();
  7129. }
  7130. ArcRotateCamera.prototype._getTargetPosition = function () {
  7131. return this.target.position || this.target;
  7132. };
  7133. // Cache
  7134. ArcRotateCamera.prototype._initCache = function () {
  7135. _super.prototype._initCache.call(this);
  7136. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7137. this._cache.alpha = undefined;
  7138. this._cache.beta = undefined;
  7139. this._cache.radius = undefined;
  7140. this._cache.targetScreenOffset = undefined;
  7141. };
  7142. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7143. if (!ignoreParentClass) {
  7144. _super.prototype._updateCache.call(this);
  7145. }
  7146. this._cache.target.copyFrom(this._getTargetPosition());
  7147. this._cache.alpha = this.alpha;
  7148. this._cache.beta = this.beta;
  7149. this._cache.radius = this.radius;
  7150. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7151. };
  7152. // Synchronized
  7153. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7154. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7155. return false;
  7156. 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);
  7157. };
  7158. // Methods
  7159. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7160. var _this = this;
  7161. var previousPosition;
  7162. var pointerId;
  7163. // to know if pinch started
  7164. var pinchStarted = false;
  7165. // two pinch point on X
  7166. // that will use for find if user action is pinch open or pinch close
  7167. var pinchPointX1, pinchPointX2;
  7168. if (this._attachedElement) {
  7169. return;
  7170. }
  7171. this._attachedElement = element;
  7172. var engine = this.getEngine();
  7173. if (this._onPointerDown === undefined) {
  7174. this._onPointerDown = function (evt) {
  7175. if (pointerId) {
  7176. return;
  7177. }
  7178. pointerId = evt.pointerId;
  7179. previousPosition = {
  7180. x: evt.clientX,
  7181. y: evt.clientY
  7182. };
  7183. if (!noPreventDefault) {
  7184. evt.preventDefault();
  7185. }
  7186. };
  7187. this._onPointerUp = function (evt) {
  7188. previousPosition = null;
  7189. pointerId = null;
  7190. if (!noPreventDefault) {
  7191. evt.preventDefault();
  7192. }
  7193. };
  7194. this._onPointerMove = function (evt) {
  7195. if (!previousPosition) {
  7196. return;
  7197. }
  7198. if (pointerId !== evt.pointerId) {
  7199. return;
  7200. }
  7201. // return pinch is started
  7202. if (pinchStarted) {
  7203. return;
  7204. }
  7205. var offsetX = evt.clientX - previousPosition.x;
  7206. var offsetY = evt.clientY - previousPosition.y;
  7207. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7208. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7209. previousPosition = {
  7210. x: evt.clientX,
  7211. y: evt.clientY
  7212. };
  7213. if (!noPreventDefault) {
  7214. evt.preventDefault();
  7215. }
  7216. };
  7217. this._onMouseMove = function (evt) {
  7218. if (!engine.isPointerLock) {
  7219. return;
  7220. }
  7221. // return pinch is started
  7222. if (pinchStarted) {
  7223. return;
  7224. }
  7225. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7226. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7227. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7228. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7229. if (!noPreventDefault) {
  7230. evt.preventDefault();
  7231. }
  7232. };
  7233. this._wheel = function (event) {
  7234. var delta = 0;
  7235. if (event.wheelDelta) {
  7236. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7237. }
  7238. else if (event.detail) {
  7239. delta = -event.detail / _this.wheelPrecision;
  7240. }
  7241. if (delta)
  7242. _this.inertialRadiusOffset += delta;
  7243. if (event.preventDefault) {
  7244. if (!noPreventDefault) {
  7245. event.preventDefault();
  7246. }
  7247. }
  7248. };
  7249. this._onKeyDown = function (evt) {
  7250. 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) {
  7251. var index = _this._keys.indexOf(evt.keyCode);
  7252. if (index === -1) {
  7253. _this._keys.push(evt.keyCode);
  7254. }
  7255. if (evt.preventDefault) {
  7256. if (!noPreventDefault) {
  7257. evt.preventDefault();
  7258. }
  7259. }
  7260. }
  7261. };
  7262. this._onKeyUp = function (evt) {
  7263. 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) {
  7264. var index = _this._keys.indexOf(evt.keyCode);
  7265. if (index >= 0) {
  7266. _this._keys.splice(index, 1);
  7267. }
  7268. if (evt.preventDefault) {
  7269. if (!noPreventDefault) {
  7270. evt.preventDefault();
  7271. }
  7272. }
  7273. }
  7274. };
  7275. this._onLostFocus = function () {
  7276. _this._keys = [];
  7277. pointerId = null;
  7278. };
  7279. this._onGestureStart = function (e) {
  7280. if (window.MSGesture === undefined) {
  7281. return;
  7282. }
  7283. if (!_this._MSGestureHandler) {
  7284. _this._MSGestureHandler = new MSGesture();
  7285. _this._MSGestureHandler.target = element;
  7286. }
  7287. _this._MSGestureHandler.addPointer(e.pointerId);
  7288. };
  7289. this._onGesture = function (e) {
  7290. _this.radius *= e.scale;
  7291. if (e.preventDefault) {
  7292. if (!noPreventDefault) {
  7293. e.stopPropagation();
  7294. e.preventDefault();
  7295. }
  7296. }
  7297. };
  7298. this._reset = function () {
  7299. _this._keys = [];
  7300. _this.inertialAlphaOffset = 0;
  7301. _this.inertialBetaOffset = 0;
  7302. _this.inertialRadiusOffset = 0;
  7303. previousPosition = null;
  7304. pointerId = null;
  7305. };
  7306. this._touchStart = function (event) {
  7307. if (event.touches.length === 2) {
  7308. //-- start pinch if two fingers on the screen
  7309. pinchStarted = true;
  7310. _this._pinchStart(event);
  7311. }
  7312. };
  7313. this._touchMove = function (event) {
  7314. if (pinchStarted) {
  7315. //-- make scaling
  7316. _this._pinchMove(event);
  7317. }
  7318. };
  7319. this._touchEnd = function (event) {
  7320. if (pinchStarted) {
  7321. //-- end of pinch
  7322. _this._pinchEnd(event);
  7323. }
  7324. };
  7325. this._pinchStart = function (event) {
  7326. // save origin touch point
  7327. pinchPointX1 = event.touches[0].clientX;
  7328. pinchPointX2 = event.touches[1].clientX;
  7329. // block the camera
  7330. // if not it rotate around target during pinch
  7331. pinchStarted = true;
  7332. };
  7333. this._pinchMove = function (event) {
  7334. // variable for new camera's radius
  7335. var delta = 0;
  7336. // variables to know if pinch open or pinch close
  7337. var direction = 1;
  7338. var distanceXOrigine, distanceXNow;
  7339. if (event.touches.length !== 2)
  7340. return;
  7341. // calculate absolute distances of the two fingers
  7342. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7343. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7344. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7345. if (distanceXNow < distanceXOrigine) {
  7346. direction = -1;
  7347. }
  7348. // calculate new radius
  7349. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7350. // set new radius
  7351. _this.inertialRadiusOffset -= delta;
  7352. // save origin touch point
  7353. pinchPointX1 = event.touches[0].clientX;
  7354. pinchPointX2 = event.touches[1].clientX;
  7355. };
  7356. this._pinchEnd = function (event) {
  7357. // cancel pinch and deblock camera rotation
  7358. pinchStarted = false;
  7359. };
  7360. }
  7361. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7362. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7363. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7364. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7365. element.addEventListener("mousemove", this._onMouseMove, false);
  7366. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7367. element.addEventListener("MSGestureChange", this._onGesture, false);
  7368. element.addEventListener('mousewheel', this._wheel, false);
  7369. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7370. // pinch
  7371. element.addEventListener('touchstart', this._touchStart, false);
  7372. element.addEventListener('touchmove', this._touchMove, false);
  7373. element.addEventListener('touchend', this._touchEnd, false);
  7374. BABYLON.Tools.RegisterTopRootEvents([
  7375. { name: "keydown", handler: this._onKeyDown },
  7376. { name: "keyup", handler: this._onKeyUp },
  7377. { name: "blur", handler: this._onLostFocus }
  7378. ]);
  7379. };
  7380. ArcRotateCamera.prototype.detachControl = function (element) {
  7381. if (this._attachedElement != element) {
  7382. return;
  7383. }
  7384. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7385. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7386. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7387. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7388. element.removeEventListener("mousemove", this._onMouseMove);
  7389. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7390. element.removeEventListener("MSGestureChange", this._onGesture);
  7391. element.removeEventListener('mousewheel', this._wheel);
  7392. element.removeEventListener('DOMMouseScroll', this._wheel);
  7393. // pinch
  7394. element.removeEventListener('touchstart', this._touchStart);
  7395. element.removeEventListener('touchmove', this._touchMove);
  7396. element.removeEventListener('touchend', this._touchEnd);
  7397. BABYLON.Tools.UnregisterTopRootEvents([
  7398. { name: "keydown", handler: this._onKeyDown },
  7399. { name: "keyup", handler: this._onKeyUp },
  7400. { name: "blur", handler: this._onLostFocus }
  7401. ]);
  7402. this._MSGestureHandler = null;
  7403. this._attachedElement = null;
  7404. if (this._reset) {
  7405. this._reset();
  7406. }
  7407. };
  7408. ArcRotateCamera.prototype._update = function () {
  7409. for (var index = 0; index < this._keys.length; index++) {
  7410. var keyCode = this._keys[index];
  7411. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7412. this.inertialAlphaOffset -= 0.01;
  7413. }
  7414. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7415. this.inertialBetaOffset -= 0.01;
  7416. }
  7417. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7418. this.inertialAlphaOffset += 0.01;
  7419. }
  7420. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7421. this.inertialBetaOffset += 0.01;
  7422. }
  7423. }
  7424. // Inertia
  7425. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7426. this.alpha += this.inertialAlphaOffset;
  7427. this.beta += this.inertialBetaOffset;
  7428. this.radius -= this.inertialRadiusOffset;
  7429. this.inertialAlphaOffset *= this.inertia;
  7430. this.inertialBetaOffset *= this.inertia;
  7431. this.inertialRadiusOffset *= this.inertia;
  7432. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7433. this.inertialAlphaOffset = 0;
  7434. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7435. this.inertialBetaOffset = 0;
  7436. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7437. this.inertialRadiusOffset = 0;
  7438. }
  7439. // Limits
  7440. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7441. this.alpha = this.lowerAlphaLimit;
  7442. }
  7443. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7444. this.alpha = this.upperAlphaLimit;
  7445. }
  7446. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7447. this.beta = this.lowerBetaLimit;
  7448. }
  7449. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7450. this.beta = this.upperBetaLimit;
  7451. }
  7452. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7453. this.radius = this.lowerRadiusLimit;
  7454. }
  7455. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7456. this.radius = this.upperRadiusLimit;
  7457. }
  7458. };
  7459. ArcRotateCamera.prototype.setPosition = function (position) {
  7460. var radiusv3 = position.subtract(this._getTargetPosition());
  7461. this.radius = radiusv3.length();
  7462. // Alpha
  7463. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7464. if (radiusv3.z < 0) {
  7465. this.alpha = 2 * Math.PI - this.alpha;
  7466. }
  7467. // Beta
  7468. this.beta = Math.acos(radiusv3.y / this.radius);
  7469. };
  7470. ArcRotateCamera.prototype._getViewMatrix = function () {
  7471. // Compute
  7472. var cosa = Math.cos(this.alpha);
  7473. var sina = Math.sin(this.alpha);
  7474. var cosb = Math.cos(this.beta);
  7475. var sinb = Math.sin(this.beta);
  7476. var target = this._getTargetPosition();
  7477. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7478. if (this.checkCollisions) {
  7479. this._collider.radius = this.collisionRadius;
  7480. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7481. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7482. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7483. this.position.copyFrom(this._previousPosition);
  7484. this.alpha = this._previousAlpha;
  7485. this.beta = this._previousBeta;
  7486. this.radius = this._previousRadius;
  7487. if (this.onCollide) {
  7488. this.onCollide(this._collider.collidedMesh);
  7489. }
  7490. }
  7491. }
  7492. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7493. this._previousAlpha = this.alpha;
  7494. this._previousBeta = this.beta;
  7495. this._previousRadius = this.radius;
  7496. this._previousPosition.copyFrom(this.position);
  7497. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7498. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7499. return this._viewMatrix;
  7500. };
  7501. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7502. meshes = meshes || this.getScene().meshes;
  7503. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7504. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7505. this.radius = distance * this.zoomOnFactor;
  7506. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7507. };
  7508. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7509. var meshesOrMinMaxVector;
  7510. var distance;
  7511. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7512. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7513. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7514. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7515. }
  7516. else {
  7517. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7518. distance = meshesOrMinMaxVectorAndDistance.distance;
  7519. }
  7520. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7521. this.maxZ = distance * 2;
  7522. };
  7523. return ArcRotateCamera;
  7524. })(BABYLON.Camera);
  7525. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7526. })(BABYLON || (BABYLON = {}));
  7527. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7528. (function (BABYLON) {
  7529. /**
  7530. * Represents a scene to be rendered by the engine.
  7531. * @see http://doc.babylonjs.com/page.php?p=21911
  7532. */
  7533. var Scene = (function () {
  7534. /**
  7535. * @constructor
  7536. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7537. */
  7538. function Scene(engine) {
  7539. // Members
  7540. this.autoClear = true;
  7541. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7543. this.forceWireframe = false;
  7544. this.forcePointsCloud = false;
  7545. this.forceShowBoundingBoxes = false;
  7546. this.animationsEnabled = true;
  7547. 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
  7548. // Fog
  7549. /**
  7550. * is fog enabled on this scene.
  7551. * @type {boolean}
  7552. */
  7553. this.fogEnabled = true;
  7554. this.fogMode = Scene.FOGMODE_NONE;
  7555. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7556. this.fogDensity = 0.1;
  7557. this.fogStart = 0;
  7558. this.fogEnd = 1000.0;
  7559. // Lights
  7560. /**
  7561. * is shadow enabled on this scene.
  7562. * @type {boolean}
  7563. */
  7564. this.shadowsEnabled = true;
  7565. /**
  7566. * is light enabled on this scene.
  7567. * @type {boolean}
  7568. */
  7569. this.lightsEnabled = true;
  7570. /**
  7571. * All of the lights added to this scene.
  7572. * @see BABYLON.Light
  7573. * @type {BABYLON.Light[]}
  7574. */
  7575. this.lights = new Array();
  7576. // Cameras
  7577. /**
  7578. * All of the cameras added to this scene.
  7579. * @see BABYLON.Camera
  7580. * @type {BABYLON.Camera[]}
  7581. */
  7582. this.cameras = new Array();
  7583. this.activeCameras = new Array();
  7584. // Meshes
  7585. /**
  7586. * All of the (abstract) meshes added to this scene.
  7587. * @see BABYLON.AbstractMesh
  7588. * @type {BABYLON.AbstractMesh[]}
  7589. */
  7590. this.meshes = new Array();
  7591. // Geometries
  7592. this._geometries = new Array();
  7593. this.materials = new Array();
  7594. this.multiMaterials = new Array();
  7595. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7596. // Textures
  7597. this.texturesEnabled = true;
  7598. this.textures = new Array();
  7599. // Particles
  7600. this.particlesEnabled = true;
  7601. this.particleSystems = new Array();
  7602. // Sprites
  7603. this.spritesEnabled = true;
  7604. this.spriteManagers = new Array();
  7605. // Layers
  7606. this.layers = new Array();
  7607. // Skeletons
  7608. this.skeletonsEnabled = true;
  7609. this.skeletons = new Array();
  7610. // Lens flares
  7611. this.lensFlaresEnabled = true;
  7612. this.lensFlareSystems = new Array();
  7613. // Collisions
  7614. this.collisionsEnabled = true;
  7615. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7616. // Postprocesses
  7617. this.postProcessesEnabled = true;
  7618. // Customs render targets
  7619. this.renderTargetsEnabled = true;
  7620. this.customRenderTargets = new Array();
  7621. // Imported meshes
  7622. this.importedMeshesFiles = new Array();
  7623. this._actionManagers = new Array();
  7624. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7625. // Procedural textures
  7626. this.proceduralTexturesEnabled = true;
  7627. this._proceduralTextures = new Array();
  7628. this.soundTracks = new Array();
  7629. this._totalVertices = 0;
  7630. this._activeVertices = 0;
  7631. this._activeParticles = 0;
  7632. this._lastFrameDuration = 0;
  7633. this._evaluateActiveMeshesDuration = 0;
  7634. this._renderTargetsDuration = 0;
  7635. this._particlesDuration = 0;
  7636. this._renderDuration = 0;
  7637. this._spritesDuration = 0;
  7638. this._animationRatio = 0;
  7639. this._renderId = 0;
  7640. this._executeWhenReadyTimeoutId = -1;
  7641. this._toBeDisposed = new BABYLON.SmartArray(256);
  7642. this._onReadyCallbacks = new Array();
  7643. this._pendingData = []; //ANY
  7644. this._onBeforeRenderCallbacks = new Array();
  7645. this._onAfterRenderCallbacks = new Array();
  7646. this._activeMeshes = new BABYLON.SmartArray(256);
  7647. this._processedMaterials = new BABYLON.SmartArray(256);
  7648. this._renderTargets = new BABYLON.SmartArray(256);
  7649. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7650. this._activeSkeletons = new BABYLON.SmartArray(32);
  7651. this._activeBones = 0;
  7652. this._activeAnimatables = new Array();
  7653. this._transformMatrix = BABYLON.Matrix.Zero();
  7654. this._scaledPosition = BABYLON.Vector3.Zero();
  7655. this._scaledVelocity = BABYLON.Vector3.Zero();
  7656. this._engine = engine;
  7657. engine.scenes.push(this);
  7658. this._renderingManager = new BABYLON.RenderingManager(this);
  7659. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7660. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7661. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7662. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7663. this.attachControl();
  7664. this._debugLayer = new BABYLON.DebugLayer(this);
  7665. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7666. }
  7667. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7668. get: function () {
  7669. return Scene._FOGMODE_NONE;
  7670. },
  7671. enumerable: true,
  7672. configurable: true
  7673. });
  7674. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7675. get: function () {
  7676. return Scene._FOGMODE_EXP;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7682. get: function () {
  7683. return Scene._FOGMODE_EXP2;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7689. get: function () {
  7690. return Scene._FOGMODE_LINEAR;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Scene.prototype, "debugLayer", {
  7696. // Properties
  7697. get: function () {
  7698. return this._debugLayer;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7704. /**
  7705. * The mesh that is currently under the pointer.
  7706. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7707. */
  7708. get: function () {
  7709. return this._meshUnderPointer;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(Scene.prototype, "pointerX", {
  7715. /**
  7716. * Current on-screen X position of the pointer
  7717. * @return {number} X position of the pointer
  7718. */
  7719. get: function () {
  7720. return this._pointerX;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(Scene.prototype, "pointerY", {
  7726. /**
  7727. * Current on-screen Y position of the pointer
  7728. * @return {number} Y position of the pointer
  7729. */
  7730. get: function () {
  7731. return this._pointerY;
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. Scene.prototype.getCachedMaterial = function () {
  7737. return this._cachedMaterial;
  7738. };
  7739. Scene.prototype.getBoundingBoxRenderer = function () {
  7740. return this._boundingBoxRenderer;
  7741. };
  7742. Scene.prototype.getOutlineRenderer = function () {
  7743. return this._outlineRenderer;
  7744. };
  7745. Scene.prototype.getEngine = function () {
  7746. return this._engine;
  7747. };
  7748. Scene.prototype.getTotalVertices = function () {
  7749. return this._totalVertices;
  7750. };
  7751. Scene.prototype.getActiveVertices = function () {
  7752. return this._activeVertices;
  7753. };
  7754. Scene.prototype.getActiveParticles = function () {
  7755. return this._activeParticles;
  7756. };
  7757. Scene.prototype.getActiveBones = function () {
  7758. return this._activeBones;
  7759. };
  7760. // Stats
  7761. Scene.prototype.getLastFrameDuration = function () {
  7762. return this._lastFrameDuration;
  7763. };
  7764. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7765. return this._evaluateActiveMeshesDuration;
  7766. };
  7767. Scene.prototype.getActiveMeshes = function () {
  7768. return this._activeMeshes;
  7769. };
  7770. Scene.prototype.getRenderTargetsDuration = function () {
  7771. return this._renderTargetsDuration;
  7772. };
  7773. Scene.prototype.getRenderDuration = function () {
  7774. return this._renderDuration;
  7775. };
  7776. Scene.prototype.getParticlesDuration = function () {
  7777. return this._particlesDuration;
  7778. };
  7779. Scene.prototype.getSpritesDuration = function () {
  7780. return this._spritesDuration;
  7781. };
  7782. Scene.prototype.getAnimationRatio = function () {
  7783. return this._animationRatio;
  7784. };
  7785. Scene.prototype.getRenderId = function () {
  7786. return this._renderId;
  7787. };
  7788. Scene.prototype.incrementRenderId = function () {
  7789. this._renderId++;
  7790. };
  7791. Scene.prototype._updatePointerPosition = function (evt) {
  7792. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7793. this._pointerX = evt.clientX - canvasRect.left;
  7794. this._pointerY = evt.clientY - canvasRect.top;
  7795. if (this.cameraToUseForPointers) {
  7796. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7797. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7798. }
  7799. };
  7800. // Pointers handling
  7801. Scene.prototype.attachControl = function () {
  7802. var _this = this;
  7803. this._onPointerMove = function (evt) {
  7804. var canvas = _this._engine.getRenderingCanvas();
  7805. _this._updatePointerPosition(evt);
  7806. 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);
  7807. if (pickResult.hit) {
  7808. _this._meshUnderPointer = pickResult.pickedMesh;
  7809. _this.setPointerOverMesh(pickResult.pickedMesh);
  7810. canvas.style.cursor = "pointer";
  7811. }
  7812. else {
  7813. _this.setPointerOverMesh(null);
  7814. canvas.style.cursor = "";
  7815. _this._meshUnderPointer = null;
  7816. }
  7817. };
  7818. this._onPointerDown = function (evt) {
  7819. var predicate = null;
  7820. if (!_this.onPointerDown) {
  7821. predicate = function (mesh) {
  7822. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7823. };
  7824. }
  7825. _this._updatePointerPosition(evt);
  7826. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7827. if (pickResult.hit) {
  7828. if (pickResult.pickedMesh.actionManager) {
  7829. switch (evt.button) {
  7830. case 0:
  7831. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7832. break;
  7833. case 1:
  7834. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7835. break;
  7836. case 2:
  7837. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7838. break;
  7839. }
  7840. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7841. }
  7842. }
  7843. if (_this.onPointerDown) {
  7844. _this.onPointerDown(evt, pickResult);
  7845. }
  7846. };
  7847. this._onKeyDown = function (evt) {
  7848. if (_this.actionManager) {
  7849. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7850. }
  7851. };
  7852. this._onKeyUp = function (evt) {
  7853. if (_this.actionManager) {
  7854. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7855. }
  7856. };
  7857. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7858. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7859. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7860. BABYLON.Tools.RegisterTopRootEvents([
  7861. { name: "keydown", handler: this._onKeyDown },
  7862. { name: "keyup", handler: this._onKeyUp }
  7863. ]);
  7864. };
  7865. Scene.prototype.detachControl = function () {
  7866. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7867. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7868. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7869. BABYLON.Tools.UnregisterTopRootEvents([
  7870. { name: "keydown", handler: this._onKeyDown },
  7871. { name: "keyup", handler: this._onKeyUp }
  7872. ]);
  7873. };
  7874. // Ready
  7875. Scene.prototype.isReady = function () {
  7876. if (this._pendingData.length > 0) {
  7877. return false;
  7878. }
  7879. for (var index = 0; index < this._geometries.length; index++) {
  7880. var geometry = this._geometries[index];
  7881. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7882. return false;
  7883. }
  7884. }
  7885. for (index = 0; index < this.meshes.length; index++) {
  7886. var mesh = this.meshes[index];
  7887. if (!mesh.isReady()) {
  7888. return false;
  7889. }
  7890. var mat = mesh.material;
  7891. if (mat) {
  7892. if (!mat.isReady(mesh)) {
  7893. return false;
  7894. }
  7895. }
  7896. }
  7897. return true;
  7898. };
  7899. Scene.prototype.resetCachedMaterial = function () {
  7900. this._cachedMaterial = null;
  7901. };
  7902. Scene.prototype.registerBeforeRender = function (func) {
  7903. this._onBeforeRenderCallbacks.push(func);
  7904. };
  7905. Scene.prototype.unregisterBeforeRender = function (func) {
  7906. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7907. if (index > -1) {
  7908. this._onBeforeRenderCallbacks.splice(index, 1);
  7909. }
  7910. };
  7911. Scene.prototype.registerAfterRender = function (func) {
  7912. this._onAfterRenderCallbacks.push(func);
  7913. };
  7914. Scene.prototype.unregisterAfterRender = function (func) {
  7915. var index = this._onAfterRenderCallbacks.indexOf(func);
  7916. if (index > -1) {
  7917. this._onAfterRenderCallbacks.splice(index, 1);
  7918. }
  7919. };
  7920. Scene.prototype._addPendingData = function (data) {
  7921. this._pendingData.push(data);
  7922. };
  7923. Scene.prototype._removePendingData = function (data) {
  7924. var index = this._pendingData.indexOf(data);
  7925. if (index !== -1) {
  7926. this._pendingData.splice(index, 1);
  7927. }
  7928. };
  7929. Scene.prototype.getWaitingItemsCount = function () {
  7930. return this._pendingData.length;
  7931. };
  7932. /**
  7933. * Registers a function to be executed when the scene is ready.
  7934. * @param {Function} func - the function to be executed.
  7935. */
  7936. Scene.prototype.executeWhenReady = function (func) {
  7937. var _this = this;
  7938. this._onReadyCallbacks.push(func);
  7939. if (this._executeWhenReadyTimeoutId !== -1) {
  7940. return;
  7941. }
  7942. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7943. _this._checkIsReady();
  7944. }, 150);
  7945. };
  7946. Scene.prototype._checkIsReady = function () {
  7947. var _this = this;
  7948. if (this.isReady()) {
  7949. this._onReadyCallbacks.forEach(function (func) {
  7950. func();
  7951. });
  7952. this._onReadyCallbacks = [];
  7953. this._executeWhenReadyTimeoutId = -1;
  7954. return;
  7955. }
  7956. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7957. _this._checkIsReady();
  7958. }, 150);
  7959. };
  7960. // Animations
  7961. /**
  7962. * Will start the animation sequence of a given target
  7963. * @param target - the target
  7964. * @param {number} from - from which frame should animation start
  7965. * @param {number} to - till which frame should animation run.
  7966. * @param {boolean} [loop] - should the animation loop
  7967. * @param {number} [speedRatio] - the speed in which to run the animation
  7968. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7969. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7970. * @return {BABYLON.Animatable} the animatable object created for this animation
  7971. * @see BABYLON.Animatable
  7972. * @see http://doc.babylonjs.com/page.php?p=22081
  7973. */
  7974. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7975. if (speedRatio === undefined) {
  7976. speedRatio = 1.0;
  7977. }
  7978. this.stopAnimation(target);
  7979. if (!animatable) {
  7980. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7981. }
  7982. // Local animations
  7983. if (target.animations) {
  7984. animatable.appendAnimations(target, target.animations);
  7985. }
  7986. // Children animations
  7987. if (target.getAnimatables) {
  7988. var animatables = target.getAnimatables();
  7989. for (var index = 0; index < animatables.length; index++) {
  7990. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7991. }
  7992. }
  7993. return animatable;
  7994. };
  7995. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7996. if (speedRatio === undefined) {
  7997. speedRatio = 1.0;
  7998. }
  7999. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8000. return animatable;
  8001. };
  8002. Scene.prototype.getAnimatableByTarget = function (target) {
  8003. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8004. if (this._activeAnimatables[index].target === target) {
  8005. return this._activeAnimatables[index];
  8006. }
  8007. }
  8008. return null;
  8009. };
  8010. /**
  8011. * Will stop the animation of the given target
  8012. * @param target - the target
  8013. * @see beginAnimation
  8014. */
  8015. Scene.prototype.stopAnimation = function (target) {
  8016. var animatable = this.getAnimatableByTarget(target);
  8017. if (animatable) {
  8018. animatable.stop();
  8019. }
  8020. };
  8021. Scene.prototype._animate = function () {
  8022. if (!this.animationsEnabled) {
  8023. return;
  8024. }
  8025. if (!this._animationStartDate) {
  8026. this._animationStartDate = BABYLON.Tools.Now;
  8027. }
  8028. // Getting time
  8029. var now = BABYLON.Tools.Now;
  8030. var delay = now - this._animationStartDate;
  8031. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8032. if (!this._activeAnimatables[index]._animate(delay)) {
  8033. this._activeAnimatables.splice(index, 1);
  8034. index--;
  8035. }
  8036. }
  8037. };
  8038. // Matrix
  8039. Scene.prototype.getViewMatrix = function () {
  8040. return this._viewMatrix;
  8041. };
  8042. Scene.prototype.getProjectionMatrix = function () {
  8043. return this._projectionMatrix;
  8044. };
  8045. Scene.prototype.getTransformMatrix = function () {
  8046. return this._transformMatrix;
  8047. };
  8048. Scene.prototype.setTransformMatrix = function (view, projection) {
  8049. this._viewMatrix = view;
  8050. this._projectionMatrix = projection;
  8051. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8052. };
  8053. // Methods
  8054. /**
  8055. * sets the active camera of the scene using its ID
  8056. * @param {string} id - the camera's ID
  8057. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8058. * @see activeCamera
  8059. */
  8060. Scene.prototype.setActiveCameraByID = function (id) {
  8061. var camera = this.getCameraByID(id);
  8062. if (camera) {
  8063. this.activeCamera = camera;
  8064. return camera;
  8065. }
  8066. return null;
  8067. };
  8068. /**
  8069. * sets the active camera of the scene using its name
  8070. * @param {string} name - the camera's name
  8071. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8072. * @see activeCamera
  8073. */
  8074. Scene.prototype.setActiveCameraByName = function (name) {
  8075. var camera = this.getCameraByName(name);
  8076. if (camera) {
  8077. this.activeCamera = camera;
  8078. return camera;
  8079. }
  8080. return null;
  8081. };
  8082. /**
  8083. * get a material using its id
  8084. * @param {string} the material's ID
  8085. * @return {BABYLON.Material|null} the material or null if none found.
  8086. */
  8087. Scene.prototype.getMaterialByID = function (id) {
  8088. for (var index = 0; index < this.materials.length; index++) {
  8089. if (this.materials[index].id === id) {
  8090. return this.materials[index];
  8091. }
  8092. }
  8093. return null;
  8094. };
  8095. /**
  8096. * get a material using its name
  8097. * @param {string} the material's name
  8098. * @return {BABYLON.Material|null} the material or null if none found.
  8099. */
  8100. Scene.prototype.getMaterialByName = function (name) {
  8101. for (var index = 0; index < this.materials.length; index++) {
  8102. if (this.materials[index].name === name) {
  8103. return this.materials[index];
  8104. }
  8105. }
  8106. return null;
  8107. };
  8108. Scene.prototype.getCameraByID = function (id) {
  8109. for (var index = 0; index < this.cameras.length; index++) {
  8110. if (this.cameras[index].id === id) {
  8111. return this.cameras[index];
  8112. }
  8113. }
  8114. return null;
  8115. };
  8116. /**
  8117. * get a camera using its name
  8118. * @param {string} the camera's name
  8119. * @return {BABYLON.Camera|null} the camera or null if none found.
  8120. */
  8121. Scene.prototype.getCameraByName = function (name) {
  8122. for (var index = 0; index < this.cameras.length; index++) {
  8123. if (this.cameras[index].name === name) {
  8124. return this.cameras[index];
  8125. }
  8126. }
  8127. return null;
  8128. };
  8129. /**
  8130. * get a light node using its name
  8131. * @param {string} the light's name
  8132. * @return {BABYLON.Light|null} the light or null if none found.
  8133. */
  8134. Scene.prototype.getLightByName = function (name) {
  8135. for (var index = 0; index < this.lights.length; index++) {
  8136. if (this.lights[index].name === name) {
  8137. return this.lights[index];
  8138. }
  8139. }
  8140. return null;
  8141. };
  8142. /**
  8143. * get a light node using its ID
  8144. * @param {string} the light's id
  8145. * @return {BABYLON.Light|null} the light or null if none found.
  8146. */
  8147. Scene.prototype.getLightByID = function (id) {
  8148. for (var index = 0; index < this.lights.length; index++) {
  8149. if (this.lights[index].id === id) {
  8150. return this.lights[index];
  8151. }
  8152. }
  8153. return null;
  8154. };
  8155. /**
  8156. * get a geometry using its ID
  8157. * @param {string} the geometry's id
  8158. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8159. */
  8160. Scene.prototype.getGeometryByID = function (id) {
  8161. for (var index = 0; index < this._geometries.length; index++) {
  8162. if (this._geometries[index].id === id) {
  8163. return this._geometries[index];
  8164. }
  8165. }
  8166. return null;
  8167. };
  8168. /**
  8169. * add a new geometry to this scene.
  8170. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8171. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8172. * @return {boolean} was the geometry added or not
  8173. */
  8174. Scene.prototype.pushGeometry = function (geometry, force) {
  8175. if (!force && this.getGeometryByID(geometry.id)) {
  8176. return false;
  8177. }
  8178. this._geometries.push(geometry);
  8179. return true;
  8180. };
  8181. Scene.prototype.getGeometries = function () {
  8182. return this._geometries;
  8183. };
  8184. /**
  8185. * Get a the first added mesh found of a given ID
  8186. * @param {string} id - the id to search for
  8187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8188. */
  8189. Scene.prototype.getMeshByID = function (id) {
  8190. for (var index = 0; index < this.meshes.length; index++) {
  8191. if (this.meshes[index].id === id) {
  8192. return this.meshes[index];
  8193. }
  8194. }
  8195. return null;
  8196. };
  8197. /**
  8198. * Get a the last added mesh found of a given ID
  8199. * @param {string} id - the id to search for
  8200. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8201. */
  8202. Scene.prototype.getLastMeshByID = function (id) {
  8203. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8204. if (this.meshes[index].id === id) {
  8205. return this.meshes[index];
  8206. }
  8207. }
  8208. return null;
  8209. };
  8210. /**
  8211. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8212. * @param {string} id - the id to search for
  8213. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8214. */
  8215. Scene.prototype.getLastEntryByID = function (id) {
  8216. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8217. if (this.meshes[index].id === id) {
  8218. return this.meshes[index];
  8219. }
  8220. }
  8221. for (index = this.cameras.length - 1; index >= 0; index--) {
  8222. if (this.cameras[index].id === id) {
  8223. return this.cameras[index];
  8224. }
  8225. }
  8226. for (index = this.lights.length - 1; index >= 0; index--) {
  8227. if (this.lights[index].id === id) {
  8228. return this.lights[index];
  8229. }
  8230. }
  8231. return null;
  8232. };
  8233. Scene.prototype.getNodeByName = function (name) {
  8234. var mesh = this.getMeshByName(name);
  8235. if (mesh) {
  8236. return mesh;
  8237. }
  8238. var light = this.getLightByName(name);
  8239. if (light) {
  8240. return light;
  8241. }
  8242. return this.getCameraByName(name);
  8243. };
  8244. Scene.prototype.getMeshByName = function (name) {
  8245. for (var index = 0; index < this.meshes.length; index++) {
  8246. if (this.meshes[index].name === name) {
  8247. return this.meshes[index];
  8248. }
  8249. }
  8250. return null;
  8251. };
  8252. Scene.prototype.getSoundByName = function (name) {
  8253. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8254. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8255. return this.mainSoundTrack.soundCollection[index];
  8256. }
  8257. }
  8258. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8259. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8260. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8261. return this.soundTracks[sdIndex].soundCollection[index];
  8262. }
  8263. }
  8264. }
  8265. return null;
  8266. };
  8267. Scene.prototype.getLastSkeletonByID = function (id) {
  8268. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8269. if (this.skeletons[index].id === id) {
  8270. return this.skeletons[index];
  8271. }
  8272. }
  8273. return null;
  8274. };
  8275. Scene.prototype.getSkeletonById = function (id) {
  8276. for (var index = 0; index < this.skeletons.length; index++) {
  8277. if (this.skeletons[index].id === id) {
  8278. return this.skeletons[index];
  8279. }
  8280. }
  8281. return null;
  8282. };
  8283. Scene.prototype.getSkeletonByName = function (name) {
  8284. for (var index = 0; index < this.skeletons.length; index++) {
  8285. if (this.skeletons[index].name === name) {
  8286. return this.skeletons[index];
  8287. }
  8288. }
  8289. return null;
  8290. };
  8291. Scene.prototype.isActiveMesh = function (mesh) {
  8292. return (this._activeMeshes.indexOf(mesh) !== -1);
  8293. };
  8294. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8295. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8296. var material = subMesh.getMaterial();
  8297. if (mesh.showSubMeshesBoundingBox) {
  8298. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8299. }
  8300. if (material) {
  8301. // Render targets
  8302. if (material.getRenderTargetTextures) {
  8303. if (this._processedMaterials.indexOf(material) === -1) {
  8304. this._processedMaterials.push(material);
  8305. this._renderTargets.concat(material.getRenderTargetTextures());
  8306. }
  8307. }
  8308. // Dispatch
  8309. this._activeVertices += subMesh.indexCount;
  8310. this._renderingManager.dispatch(subMesh);
  8311. }
  8312. }
  8313. };
  8314. Scene.prototype._evaluateActiveMeshes = function () {
  8315. this.activeCamera._activeMeshes.reset();
  8316. this._activeMeshes.reset();
  8317. this._renderingManager.reset();
  8318. this._processedMaterials.reset();
  8319. this._activeParticleSystems.reset();
  8320. this._activeSkeletons.reset();
  8321. this._boundingBoxRenderer.reset();
  8322. if (!this._frustumPlanes) {
  8323. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8324. }
  8325. else {
  8326. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8327. }
  8328. // Meshes
  8329. var meshes;
  8330. var len;
  8331. if (this._selectionOctree) {
  8332. var selection = this._selectionOctree.select(this._frustumPlanes);
  8333. meshes = selection.data;
  8334. len = selection.length;
  8335. }
  8336. else {
  8337. len = this.meshes.length;
  8338. meshes = this.meshes;
  8339. }
  8340. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8341. var mesh = meshes[meshIndex];
  8342. if (mesh.isBlocked) {
  8343. continue;
  8344. }
  8345. this._totalVertices += mesh.getTotalVertices();
  8346. if (!mesh.isReady()) {
  8347. continue;
  8348. }
  8349. mesh.computeWorldMatrix();
  8350. // Intersections
  8351. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8352. this._meshesForIntersections.pushNoDuplicate(mesh);
  8353. }
  8354. // Switch to current LOD
  8355. var meshLOD = mesh.getLOD(this.activeCamera);
  8356. if (!meshLOD) {
  8357. continue;
  8358. }
  8359. mesh._preActivate();
  8360. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8361. this._activeMeshes.push(mesh);
  8362. this.activeCamera._activeMeshes.push(mesh);
  8363. mesh._activate(this._renderId);
  8364. this._activeMesh(meshLOD);
  8365. }
  8366. }
  8367. // Particle systems
  8368. var beforeParticlesDate = BABYLON.Tools.Now;
  8369. if (this.particlesEnabled) {
  8370. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8371. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8372. var particleSystem = this.particleSystems[particleIndex];
  8373. if (!particleSystem.isStarted()) {
  8374. continue;
  8375. }
  8376. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8377. this._activeParticleSystems.push(particleSystem);
  8378. particleSystem.animate();
  8379. }
  8380. }
  8381. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8382. }
  8383. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8384. };
  8385. Scene.prototype._activeMesh = function (mesh) {
  8386. if (mesh.skeleton && this.skeletonsEnabled) {
  8387. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8388. }
  8389. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8390. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8391. }
  8392. if (mesh && mesh.subMeshes) {
  8393. // Submeshes Octrees
  8394. var len;
  8395. var subMeshes;
  8396. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8397. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8398. len = intersections.length;
  8399. subMeshes = intersections.data;
  8400. }
  8401. else {
  8402. subMeshes = mesh.subMeshes;
  8403. len = subMeshes.length;
  8404. }
  8405. for (var subIndex = 0; subIndex < len; subIndex++) {
  8406. var subMesh = subMeshes[subIndex];
  8407. this._evaluateSubMesh(subMesh, mesh);
  8408. }
  8409. }
  8410. };
  8411. Scene.prototype.updateTransformMatrix = function (force) {
  8412. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8413. };
  8414. Scene.prototype._renderForCamera = function (camera) {
  8415. var engine = this._engine;
  8416. this.activeCamera = camera;
  8417. if (!this.activeCamera)
  8418. throw new Error("Active camera not set");
  8419. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8420. // Viewport
  8421. engine.setViewport(this.activeCamera.viewport);
  8422. // Camera
  8423. this._renderId++;
  8424. this.updateTransformMatrix();
  8425. if (this.beforeCameraRender) {
  8426. this.beforeCameraRender(this.activeCamera);
  8427. }
  8428. // Meshes
  8429. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8430. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8431. this._evaluateActiveMeshes();
  8432. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8433. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8434. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8435. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8436. skeleton.prepare();
  8437. }
  8438. // Render targets
  8439. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8440. if (this.renderTargetsEnabled) {
  8441. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8442. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8443. var renderTarget = this._renderTargets.data[renderIndex];
  8444. if (renderTarget._shouldRender()) {
  8445. this._renderId++;
  8446. renderTarget.render();
  8447. }
  8448. }
  8449. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8450. this._renderId++;
  8451. }
  8452. if (this._renderTargets.length > 0) {
  8453. engine.restoreDefaultFramebuffer();
  8454. }
  8455. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8456. // Prepare Frame
  8457. this.postProcessManager._prepareFrame();
  8458. var beforeRenderDate = BABYLON.Tools.Now;
  8459. // Backgrounds
  8460. if (this.layers.length) {
  8461. engine.setDepthBuffer(false);
  8462. var layerIndex;
  8463. var layer;
  8464. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8465. layer = this.layers[layerIndex];
  8466. if (layer.isBackground) {
  8467. layer.render();
  8468. }
  8469. }
  8470. engine.setDepthBuffer(true);
  8471. }
  8472. // Render
  8473. BABYLON.Tools.StartPerformanceCounter("Main render");
  8474. this._renderingManager.render(null, null, true, true);
  8475. BABYLON.Tools.EndPerformanceCounter("Main render");
  8476. // Bounding boxes
  8477. this._boundingBoxRenderer.render();
  8478. // Lens flares
  8479. if (this.lensFlaresEnabled) {
  8480. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8481. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8482. this.lensFlareSystems[lensFlareSystemIndex].render();
  8483. }
  8484. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8485. }
  8486. // Foregrounds
  8487. if (this.layers.length) {
  8488. engine.setDepthBuffer(false);
  8489. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8490. layer = this.layers[layerIndex];
  8491. if (!layer.isBackground) {
  8492. layer.render();
  8493. }
  8494. }
  8495. engine.setDepthBuffer(true);
  8496. }
  8497. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8498. // Finalize frame
  8499. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8500. // Update camera
  8501. this.activeCamera._updateFromScene();
  8502. // Reset some special arrays
  8503. this._renderTargets.reset();
  8504. if (this.afterCameraRender) {
  8505. this.afterCameraRender(this.activeCamera);
  8506. }
  8507. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8508. };
  8509. Scene.prototype._processSubCameras = function (camera) {
  8510. if (camera.subCameras.length === 0) {
  8511. this._renderForCamera(camera);
  8512. return;
  8513. }
  8514. for (var index = 0; index < camera.subCameras.length; index++) {
  8515. this._renderForCamera(camera.subCameras[index]);
  8516. }
  8517. this.activeCamera = camera;
  8518. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8519. // Update camera
  8520. this.activeCamera._updateFromScene();
  8521. };
  8522. Scene.prototype._checkIntersections = function () {
  8523. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8524. var sourceMesh = this._meshesForIntersections.data[index];
  8525. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8526. var action = sourceMesh.actionManager.actions[actionIndex];
  8527. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8528. var parameters = action.getTriggerParameter();
  8529. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8530. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8531. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8532. if (areIntersecting && currentIntersectionInProgress === -1) {
  8533. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8534. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8535. sourceMesh._intersectionsInProgress.push(otherMesh);
  8536. }
  8537. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8538. sourceMesh._intersectionsInProgress.push(otherMesh);
  8539. }
  8540. }
  8541. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8542. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8543. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8544. if (indexOfOther > -1) {
  8545. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8546. }
  8547. }
  8548. }
  8549. }
  8550. }
  8551. };
  8552. Scene.prototype.render = function () {
  8553. var startDate = BABYLON.Tools.Now;
  8554. this._particlesDuration = 0;
  8555. this._spritesDuration = 0;
  8556. this._activeParticles = 0;
  8557. this._renderDuration = 0;
  8558. this._renderTargetsDuration = 0;
  8559. this._evaluateActiveMeshesDuration = 0;
  8560. this._totalVertices = 0;
  8561. this._activeVertices = 0;
  8562. this._activeBones = 0;
  8563. this.getEngine().resetDrawCalls();
  8564. this._meshesForIntersections.reset();
  8565. this.resetCachedMaterial();
  8566. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8567. // Actions
  8568. if (this.actionManager) {
  8569. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8570. }
  8571. // Before render
  8572. if (this.beforeRender) {
  8573. this.beforeRender();
  8574. }
  8575. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8576. this._onBeforeRenderCallbacks[callbackIndex]();
  8577. }
  8578. // Animations
  8579. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8580. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8581. this._animate();
  8582. // Physics
  8583. if (this._physicsEngine) {
  8584. BABYLON.Tools.StartPerformanceCounter("Physics");
  8585. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8586. BABYLON.Tools.EndPerformanceCounter("Physics");
  8587. }
  8588. // Customs render targets
  8589. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8590. var engine = this.getEngine();
  8591. var currentActiveCamera = this.activeCamera;
  8592. if (this.renderTargetsEnabled) {
  8593. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8594. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8595. var renderTarget = this.customRenderTargets[customIndex];
  8596. if (renderTarget._shouldRender()) {
  8597. this._renderId++;
  8598. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8599. if (!this.activeCamera)
  8600. throw new Error("Active camera not set");
  8601. // Viewport
  8602. engine.setViewport(this.activeCamera.viewport);
  8603. // Camera
  8604. this.updateTransformMatrix();
  8605. renderTarget.render();
  8606. }
  8607. }
  8608. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8609. this._renderId++;
  8610. }
  8611. if (this.customRenderTargets.length > 0) {
  8612. engine.restoreDefaultFramebuffer();
  8613. }
  8614. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8615. this.activeCamera = currentActiveCamera;
  8616. // Procedural textures
  8617. if (this.proceduralTexturesEnabled) {
  8618. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8619. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8620. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8621. if (proceduralTexture._shouldRender()) {
  8622. proceduralTexture.render();
  8623. }
  8624. }
  8625. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8626. }
  8627. // Clear
  8628. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8629. // Shadows
  8630. if (this.shadowsEnabled) {
  8631. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8632. var light = this.lights[lightIndex];
  8633. var shadowGenerator = light.getShadowGenerator();
  8634. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8635. this._renderTargets.push(shadowGenerator.getShadowMap());
  8636. }
  8637. }
  8638. }
  8639. // Depth renderer
  8640. if (this._depthRenderer) {
  8641. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8642. }
  8643. // RenderPipeline
  8644. this.postProcessRenderPipelineManager.update();
  8645. // Multi-cameras?
  8646. if (this.activeCameras.length > 0) {
  8647. var currentRenderId = this._renderId;
  8648. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8649. this._renderId = currentRenderId;
  8650. this._processSubCameras(this.activeCameras[cameraIndex]);
  8651. }
  8652. }
  8653. else {
  8654. if (!this.activeCamera) {
  8655. throw new Error("No camera defined");
  8656. }
  8657. this._processSubCameras(this.activeCamera);
  8658. }
  8659. // Intersection checks
  8660. this._checkIntersections();
  8661. // Update the audio listener attached to the camera
  8662. this._updateAudioParameters();
  8663. // After render
  8664. if (this.afterRender) {
  8665. this.afterRender();
  8666. }
  8667. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8668. this._onAfterRenderCallbacks[callbackIndex]();
  8669. }
  8670. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8671. this._toBeDisposed.data[index].dispose();
  8672. this._toBeDisposed[index] = null;
  8673. }
  8674. this._toBeDisposed.reset();
  8675. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8676. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8677. };
  8678. Scene.prototype._updateAudioParameters = function () {
  8679. if (this.mainSoundTrack.soundCollection.length === 0 || this.soundTracks.length === 0) {
  8680. return;
  8681. }
  8682. var listeningCamera;
  8683. var audioEngine = BABYLON.Engine.audioEngine;
  8684. if (this.activeCameras.length > 0) {
  8685. listeningCamera = this.activeCameras[0];
  8686. }
  8687. else {
  8688. listeningCamera = this.activeCamera;
  8689. }
  8690. if (listeningCamera && audioEngine.canUseWebAudio) {
  8691. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8692. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8693. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8694. cameraDirection.normalize();
  8695. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8696. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8697. var sound = this.mainSoundTrack.soundCollection[i];
  8698. if (sound.useCustomAttenuation) {
  8699. sound.updateDistanceFromListener();
  8700. }
  8701. }
  8702. for (i = 0; i < this.soundTracks.length; i++) {
  8703. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8704. sound = this.soundTracks[i].soundCollection[j];
  8705. if (sound.useCustomAttenuation) {
  8706. sound.updateDistanceFromListener();
  8707. }
  8708. }
  8709. }
  8710. }
  8711. };
  8712. Scene.prototype.enableDepthRenderer = function () {
  8713. if (this._depthRenderer) {
  8714. return this._depthRenderer;
  8715. }
  8716. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8717. return this._depthRenderer;
  8718. };
  8719. Scene.prototype.disableDepthRenderer = function () {
  8720. if (!this._depthRenderer) {
  8721. return;
  8722. }
  8723. this._depthRenderer.dispose();
  8724. this._depthRenderer = null;
  8725. };
  8726. Scene.prototype.dispose = function () {
  8727. this.beforeRender = null;
  8728. this.afterRender = null;
  8729. this.skeletons = [];
  8730. this._boundingBoxRenderer.dispose();
  8731. if (this._depthRenderer) {
  8732. this._depthRenderer.dispose();
  8733. }
  8734. // Debug layer
  8735. this.debugLayer.hide();
  8736. // Events
  8737. if (this.onDispose) {
  8738. this.onDispose();
  8739. }
  8740. this._onBeforeRenderCallbacks = [];
  8741. this._onAfterRenderCallbacks = [];
  8742. this.detachControl();
  8743. // Release sounds & sounds tracks
  8744. this.mainSoundTrack.dispose();
  8745. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8746. this.soundTracks[scIndex].dispose();
  8747. }
  8748. // Detach cameras
  8749. var canvas = this._engine.getRenderingCanvas();
  8750. var index;
  8751. for (index = 0; index < this.cameras.length; index++) {
  8752. this.cameras[index].detachControl(canvas);
  8753. }
  8754. while (this.lights.length) {
  8755. this.lights[0].dispose();
  8756. }
  8757. while (this.meshes.length) {
  8758. this.meshes[0].dispose(true);
  8759. }
  8760. while (this.cameras.length) {
  8761. this.cameras[0].dispose();
  8762. }
  8763. while (this.materials.length) {
  8764. this.materials[0].dispose();
  8765. }
  8766. while (this.particleSystems.length) {
  8767. this.particleSystems[0].dispose();
  8768. }
  8769. while (this.spriteManagers.length) {
  8770. this.spriteManagers[0].dispose();
  8771. }
  8772. while (this.layers.length) {
  8773. this.layers[0].dispose();
  8774. }
  8775. while (this.textures.length) {
  8776. this.textures[0].dispose();
  8777. }
  8778. // Post-processes
  8779. this.postProcessManager.dispose();
  8780. // Physics
  8781. if (this._physicsEngine) {
  8782. this.disablePhysicsEngine();
  8783. }
  8784. // Remove from engine
  8785. index = this._engine.scenes.indexOf(this);
  8786. if (index > -1) {
  8787. this._engine.scenes.splice(index, 1);
  8788. }
  8789. this._engine.wipeCaches();
  8790. };
  8791. // Collisions
  8792. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8793. if (excludedMesh === void 0) { excludedMesh = null; }
  8794. position.divideToRef(collider.radius, this._scaledPosition);
  8795. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8796. collider.retry = 0;
  8797. collider.initialVelocity = this._scaledVelocity;
  8798. collider.initialPosition = this._scaledPosition;
  8799. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8800. finalPosition.multiplyInPlace(collider.radius);
  8801. };
  8802. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8803. if (excludedMesh === void 0) { excludedMesh = null; }
  8804. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8805. if (collider.retry >= maximumRetry) {
  8806. finalPosition.copyFrom(position);
  8807. return;
  8808. }
  8809. collider._initialize(position, velocity, closeDistance);
  8810. for (var index = 0; index < this.meshes.length; index++) {
  8811. var mesh = this.meshes[index];
  8812. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8813. mesh._checkCollision(collider);
  8814. }
  8815. }
  8816. if (!collider.collisionFound) {
  8817. position.addToRef(velocity, finalPosition);
  8818. return;
  8819. }
  8820. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8821. collider._getResponse(position, velocity);
  8822. }
  8823. if (velocity.length() <= closeDistance) {
  8824. finalPosition.copyFrom(position);
  8825. return;
  8826. }
  8827. collider.retry++;
  8828. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8829. };
  8830. // Octrees
  8831. Scene.prototype.getWorldExtends = function () {
  8832. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8833. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8834. for (var index = 0; index < this.meshes.length; index++) {
  8835. var mesh = this.meshes[index];
  8836. mesh.computeWorldMatrix(true);
  8837. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8838. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8839. BABYLON.Tools.CheckExtends(minBox, min, max);
  8840. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8841. }
  8842. return {
  8843. min: min,
  8844. max: max
  8845. };
  8846. };
  8847. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8848. if (maxCapacity === void 0) { maxCapacity = 64; }
  8849. if (maxDepth === void 0) { maxDepth = 2; }
  8850. if (!this._selectionOctree) {
  8851. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8852. }
  8853. var worldExtends = this.getWorldExtends();
  8854. // Update octree
  8855. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8856. return this._selectionOctree;
  8857. };
  8858. // Picking
  8859. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8860. var engine = this._engine;
  8861. if (!camera) {
  8862. if (!this.activeCamera)
  8863. throw new Error("Active camera not set");
  8864. camera = this.activeCamera;
  8865. }
  8866. var cameraViewport = camera.viewport;
  8867. var viewport = cameraViewport.toGlobal(engine);
  8868. // Moving coordinates to local viewport world
  8869. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8870. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8871. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8872. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8873. };
  8874. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8875. var pickingInfo = null;
  8876. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8877. var mesh = this.meshes[meshIndex];
  8878. if (predicate) {
  8879. if (!predicate(mesh)) {
  8880. continue;
  8881. }
  8882. }
  8883. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8884. continue;
  8885. }
  8886. var world = mesh.getWorldMatrix();
  8887. var ray = rayFunction(world);
  8888. var result = mesh.intersects(ray, fastCheck);
  8889. if (!result || !result.hit)
  8890. continue;
  8891. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8892. continue;
  8893. pickingInfo = result;
  8894. if (fastCheck) {
  8895. break;
  8896. }
  8897. }
  8898. return pickingInfo || new BABYLON.PickingInfo();
  8899. };
  8900. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8901. var _this = this;
  8902. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8903. /// <param name="x">X position on screen</param>
  8904. /// <param name="y">Y position on screen</param>
  8905. /// <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>
  8906. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8907. /// <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>
  8908. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8909. };
  8910. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8911. var _this = this;
  8912. return this._internalPick(function (world) {
  8913. if (!_this._pickWithRayInverseMatrix) {
  8914. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8915. }
  8916. world.invertToRef(_this._pickWithRayInverseMatrix);
  8917. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8918. }, predicate, fastCheck);
  8919. };
  8920. Scene.prototype.setPointerOverMesh = function (mesh) {
  8921. if (this._pointerOverMesh === mesh) {
  8922. return;
  8923. }
  8924. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8925. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8926. }
  8927. this._pointerOverMesh = mesh;
  8928. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8929. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8930. }
  8931. };
  8932. Scene.prototype.getPointerOverMesh = function () {
  8933. return this._pointerOverMesh;
  8934. };
  8935. // Physics
  8936. Scene.prototype.getPhysicsEngine = function () {
  8937. return this._physicsEngine;
  8938. };
  8939. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8940. if (this._physicsEngine) {
  8941. return true;
  8942. }
  8943. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8944. if (!this._physicsEngine.isSupported()) {
  8945. this._physicsEngine = null;
  8946. return false;
  8947. }
  8948. this._physicsEngine._initialize(gravity);
  8949. return true;
  8950. };
  8951. Scene.prototype.disablePhysicsEngine = function () {
  8952. if (!this._physicsEngine) {
  8953. return;
  8954. }
  8955. this._physicsEngine.dispose();
  8956. this._physicsEngine = undefined;
  8957. };
  8958. Scene.prototype.isPhysicsEnabled = function () {
  8959. return this._physicsEngine !== undefined;
  8960. };
  8961. Scene.prototype.setGravity = function (gravity) {
  8962. if (!this._physicsEngine) {
  8963. return;
  8964. }
  8965. this._physicsEngine._setGravity(gravity);
  8966. };
  8967. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8968. if (parts.parts) {
  8969. options = parts;
  8970. parts = parts.parts;
  8971. }
  8972. if (!this._physicsEngine) {
  8973. return null;
  8974. }
  8975. for (var index = 0; index < parts.length; index++) {
  8976. var mesh = parts[index].mesh;
  8977. mesh._physicImpostor = parts[index].impostor;
  8978. mesh._physicsMass = options.mass / parts.length;
  8979. mesh._physicsFriction = options.friction;
  8980. mesh._physicRestitution = options.restitution;
  8981. }
  8982. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8983. };
  8984. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8985. for (var index = 0; index < compound.parts.length; index++) {
  8986. var mesh = compound.parts[index].mesh;
  8987. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8988. this._physicsEngine._unregisterMesh(mesh);
  8989. }
  8990. };
  8991. // Misc.
  8992. Scene.prototype.createDefaultCameraOrLight = function () {
  8993. // Light
  8994. if (this.lights.length === 0) {
  8995. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8996. }
  8997. // Camera
  8998. if (!this.activeCamera) {
  8999. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9000. // Compute position
  9001. var worldExtends = this.getWorldExtends();
  9002. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9003. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9004. camera.setTarget(worldCenter);
  9005. this.activeCamera = camera;
  9006. }
  9007. };
  9008. // Tags
  9009. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9010. if (tagsQuery === undefined) {
  9011. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9012. return list;
  9013. }
  9014. var listByTags = [];
  9015. forEach = forEach || (function (item) {
  9016. return;
  9017. });
  9018. for (var i in list) {
  9019. var item = list[i];
  9020. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9021. listByTags.push(item);
  9022. forEach(item);
  9023. }
  9024. }
  9025. return listByTags;
  9026. };
  9027. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9028. return this._getByTags(this.meshes, tagsQuery, forEach);
  9029. };
  9030. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9031. return this._getByTags(this.cameras, tagsQuery, forEach);
  9032. };
  9033. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9034. return this._getByTags(this.lights, tagsQuery, forEach);
  9035. };
  9036. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9037. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9038. };
  9039. // Statics
  9040. Scene._FOGMODE_NONE = 0;
  9041. Scene._FOGMODE_EXP = 1;
  9042. Scene._FOGMODE_EXP2 = 2;
  9043. Scene._FOGMODE_LINEAR = 3;
  9044. Scene.MinDeltaTime = 1.0;
  9045. Scene.MaxDeltaTime = 1000.0;
  9046. return Scene;
  9047. })();
  9048. BABYLON.Scene = Scene;
  9049. })(BABYLON || (BABYLON = {}));
  9050. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9051. (function (BABYLON) {
  9052. var VertexBuffer = (function () {
  9053. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9054. if (engine instanceof BABYLON.Mesh) {
  9055. this._engine = engine.getScene().getEngine();
  9056. }
  9057. else {
  9058. this._engine = engine;
  9059. }
  9060. this._updatable = updatable;
  9061. this._data = data;
  9062. if (!postponeInternalCreation) {
  9063. this.create();
  9064. }
  9065. this._kind = kind;
  9066. if (stride) {
  9067. this._strideSize = stride;
  9068. return;
  9069. }
  9070. switch (kind) {
  9071. case VertexBuffer.PositionKind:
  9072. this._strideSize = 3;
  9073. break;
  9074. case VertexBuffer.NormalKind:
  9075. this._strideSize = 3;
  9076. break;
  9077. case VertexBuffer.UVKind:
  9078. this._strideSize = 2;
  9079. break;
  9080. case VertexBuffer.UV2Kind:
  9081. this._strideSize = 2;
  9082. break;
  9083. case VertexBuffer.ColorKind:
  9084. this._strideSize = 4;
  9085. break;
  9086. case VertexBuffer.MatricesIndicesKind:
  9087. this._strideSize = 4;
  9088. break;
  9089. case VertexBuffer.MatricesWeightsKind:
  9090. this._strideSize = 4;
  9091. break;
  9092. }
  9093. }
  9094. // Properties
  9095. VertexBuffer.prototype.isUpdatable = function () {
  9096. return this._updatable;
  9097. };
  9098. VertexBuffer.prototype.getData = function () {
  9099. return this._data;
  9100. };
  9101. VertexBuffer.prototype.getBuffer = function () {
  9102. return this._buffer;
  9103. };
  9104. VertexBuffer.prototype.getStrideSize = function () {
  9105. return this._strideSize;
  9106. };
  9107. // Methods
  9108. VertexBuffer.prototype.create = function (data) {
  9109. if (!data && this._buffer) {
  9110. return; // nothing to do
  9111. }
  9112. data = data || this._data;
  9113. if (!this._buffer) {
  9114. if (this._updatable) {
  9115. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9116. }
  9117. else {
  9118. this._buffer = this._engine.createVertexBuffer(data);
  9119. }
  9120. }
  9121. if (this._updatable) {
  9122. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9123. this._data = data;
  9124. }
  9125. };
  9126. VertexBuffer.prototype.update = function (data) {
  9127. this.create(data);
  9128. };
  9129. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9130. if (!this._buffer) {
  9131. return;
  9132. }
  9133. if (this._updatable) {
  9134. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9135. this._data = null;
  9136. }
  9137. };
  9138. VertexBuffer.prototype.dispose = function () {
  9139. if (!this._buffer) {
  9140. return;
  9141. }
  9142. if (this._engine._releaseBuffer(this._buffer)) {
  9143. this._buffer = null;
  9144. }
  9145. };
  9146. Object.defineProperty(VertexBuffer, "PositionKind", {
  9147. get: function () {
  9148. return VertexBuffer._PositionKind;
  9149. },
  9150. enumerable: true,
  9151. configurable: true
  9152. });
  9153. Object.defineProperty(VertexBuffer, "NormalKind", {
  9154. get: function () {
  9155. return VertexBuffer._NormalKind;
  9156. },
  9157. enumerable: true,
  9158. configurable: true
  9159. });
  9160. Object.defineProperty(VertexBuffer, "UVKind", {
  9161. get: function () {
  9162. return VertexBuffer._UVKind;
  9163. },
  9164. enumerable: true,
  9165. configurable: true
  9166. });
  9167. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9168. get: function () {
  9169. return VertexBuffer._UV2Kind;
  9170. },
  9171. enumerable: true,
  9172. configurable: true
  9173. });
  9174. Object.defineProperty(VertexBuffer, "ColorKind", {
  9175. get: function () {
  9176. return VertexBuffer._ColorKind;
  9177. },
  9178. enumerable: true,
  9179. configurable: true
  9180. });
  9181. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9182. get: function () {
  9183. return VertexBuffer._MatricesIndicesKind;
  9184. },
  9185. enumerable: true,
  9186. configurable: true
  9187. });
  9188. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9189. get: function () {
  9190. return VertexBuffer._MatricesWeightsKind;
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. // Enums
  9196. VertexBuffer._PositionKind = "position";
  9197. VertexBuffer._NormalKind = "normal";
  9198. VertexBuffer._UVKind = "uv";
  9199. VertexBuffer._UV2Kind = "uv2";
  9200. VertexBuffer._ColorKind = "color";
  9201. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9202. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9203. return VertexBuffer;
  9204. })();
  9205. BABYLON.VertexBuffer = VertexBuffer;
  9206. })(BABYLON || (BABYLON = {}));
  9207. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9208. var BABYLON;
  9209. (function (BABYLON) {
  9210. var AbstractMesh = (function (_super) {
  9211. __extends(AbstractMesh, _super);
  9212. function AbstractMesh(name, scene) {
  9213. _super.call(this, name, scene);
  9214. // Properties
  9215. this.definedFacingForward = true; // orientation for POV movement & rotation
  9216. this.position = new BABYLON.Vector3(0, 0, 0);
  9217. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9218. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9219. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9220. this.visibility = 1.0;
  9221. this.alphaIndex = Number.MAX_VALUE;
  9222. this.infiniteDistance = false;
  9223. this.isVisible = true;
  9224. this.isPickable = true;
  9225. this.showBoundingBox = false;
  9226. this.showSubMeshesBoundingBox = false;
  9227. this.onDispose = null;
  9228. this.checkCollisions = false;
  9229. this.isBlocker = false;
  9230. this.renderingGroupId = 0;
  9231. this.receiveShadows = false;
  9232. this.renderOutline = false;
  9233. this.outlineColor = BABYLON.Color3.Red();
  9234. this.outlineWidth = 0.02;
  9235. this.renderOverlay = false;
  9236. this.overlayColor = BABYLON.Color3.Red();
  9237. this.overlayAlpha = 0.5;
  9238. this.hasVertexAlpha = false;
  9239. this.useVertexColors = true;
  9240. this.applyFog = true;
  9241. this.useOctreeForRenderingSelection = true;
  9242. this.useOctreeForPicking = true;
  9243. this.useOctreeForCollisions = true;
  9244. this.layerMask = 0xFFFFFFFF;
  9245. // Physics
  9246. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9247. // Collisions
  9248. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9249. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9250. this._collider = new BABYLON.Collider();
  9251. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9252. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9253. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9254. // Cache
  9255. this._localScaling = BABYLON.Matrix.Zero();
  9256. this._localRotation = BABYLON.Matrix.Zero();
  9257. this._localTranslation = BABYLON.Matrix.Zero();
  9258. this._localBillboard = BABYLON.Matrix.Zero();
  9259. this._localPivotScaling = BABYLON.Matrix.Zero();
  9260. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9261. this._localWorld = BABYLON.Matrix.Zero();
  9262. this._worldMatrix = BABYLON.Matrix.Zero();
  9263. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9264. this._absolutePosition = BABYLON.Vector3.Zero();
  9265. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9266. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9267. this._isDirty = false;
  9268. this._pivotMatrix = BABYLON.Matrix.Identity();
  9269. this._isDisposed = false;
  9270. this._renderId = 0;
  9271. this._intersectionsInProgress = new Array();
  9272. this._onAfterWorldMatrixUpdate = new Array();
  9273. scene.meshes.push(this);
  9274. }
  9275. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9276. get: function () {
  9277. return AbstractMesh._BILLBOARDMODE_NONE;
  9278. },
  9279. enumerable: true,
  9280. configurable: true
  9281. });
  9282. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9283. get: function () {
  9284. return AbstractMesh._BILLBOARDMODE_X;
  9285. },
  9286. enumerable: true,
  9287. configurable: true
  9288. });
  9289. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9290. get: function () {
  9291. return AbstractMesh._BILLBOARDMODE_Y;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9297. get: function () {
  9298. return AbstractMesh._BILLBOARDMODE_Z;
  9299. },
  9300. enumerable: true,
  9301. configurable: true
  9302. });
  9303. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9304. get: function () {
  9305. return AbstractMesh._BILLBOARDMODE_ALL;
  9306. },
  9307. enumerable: true,
  9308. configurable: true
  9309. });
  9310. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9311. // Methods
  9312. get: function () {
  9313. return false;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. AbstractMesh.prototype.getLOD = function (camera) {
  9319. return this;
  9320. };
  9321. AbstractMesh.prototype.getTotalVertices = function () {
  9322. return 0;
  9323. };
  9324. AbstractMesh.prototype.getIndices = function () {
  9325. return null;
  9326. };
  9327. AbstractMesh.prototype.getVerticesData = function (kind) {
  9328. return null;
  9329. };
  9330. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9331. return false;
  9332. };
  9333. AbstractMesh.prototype.getBoundingInfo = function () {
  9334. if (this._masterMesh) {
  9335. return this._masterMesh.getBoundingInfo();
  9336. }
  9337. if (!this._boundingInfo) {
  9338. this._updateBoundingInfo();
  9339. }
  9340. return this._boundingInfo;
  9341. };
  9342. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9343. get: function () {
  9344. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9345. },
  9346. enumerable: true,
  9347. configurable: true
  9348. });
  9349. AbstractMesh.prototype._preActivate = function () {
  9350. };
  9351. AbstractMesh.prototype._activate = function (renderId) {
  9352. this._renderId = renderId;
  9353. };
  9354. AbstractMesh.prototype.getWorldMatrix = function () {
  9355. if (this._masterMesh) {
  9356. return this._masterMesh.getWorldMatrix();
  9357. }
  9358. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9359. this.computeWorldMatrix();
  9360. }
  9361. return this._worldMatrix;
  9362. };
  9363. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9364. get: function () {
  9365. return this._worldMatrix;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9371. get: function () {
  9372. return this._absolutePosition;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9378. if (!this.rotationQuaternion) {
  9379. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9380. this.rotation = BABYLON.Vector3.Zero();
  9381. }
  9382. if (!space || space == 0 /* LOCAL */) {
  9383. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9384. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9385. }
  9386. else {
  9387. if (this.parent) {
  9388. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9389. invertParentWorldMatrix.invert();
  9390. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9391. }
  9392. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9393. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9394. }
  9395. };
  9396. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9397. var displacementVector = axis.scale(distance);
  9398. if (!space || space == 0 /* LOCAL */) {
  9399. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9400. this.setPositionWithLocalVector(tempV3);
  9401. }
  9402. else {
  9403. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9404. }
  9405. };
  9406. AbstractMesh.prototype.getAbsolutePosition = function () {
  9407. this.computeWorldMatrix();
  9408. return this._absolutePosition;
  9409. };
  9410. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9411. if (!absolutePosition) {
  9412. return;
  9413. }
  9414. var absolutePositionX;
  9415. var absolutePositionY;
  9416. var absolutePositionZ;
  9417. if (absolutePosition.x === undefined) {
  9418. if (arguments.length < 3) {
  9419. return;
  9420. }
  9421. absolutePositionX = arguments[0];
  9422. absolutePositionY = arguments[1];
  9423. absolutePositionZ = arguments[2];
  9424. }
  9425. else {
  9426. absolutePositionX = absolutePosition.x;
  9427. absolutePositionY = absolutePosition.y;
  9428. absolutePositionZ = absolutePosition.z;
  9429. }
  9430. if (this.parent) {
  9431. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9432. invertParentWorldMatrix.invert();
  9433. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9434. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9435. }
  9436. else {
  9437. this.position.x = absolutePositionX;
  9438. this.position.y = absolutePositionY;
  9439. this.position.z = absolutePositionZ;
  9440. }
  9441. };
  9442. // ================================== Point of View Movement =================================
  9443. /**
  9444. * Perform relative position change from the point of view of behind the front of the mesh.
  9445. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9446. * Supports definition of mesh facing forward or backward.
  9447. * @param {number} amountRight
  9448. * @param {number} amountUp
  9449. * @param {number} amountForward
  9450. */
  9451. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9452. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9453. };
  9454. /**
  9455. * Calculate relative position change from the point of view of behind the front of the mesh.
  9456. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9457. * Supports definition of mesh facing forward or backward.
  9458. * @param {number} amountRight
  9459. * @param {number} amountUp
  9460. * @param {number} amountForward
  9461. */
  9462. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9463. var rotMatrix = new BABYLON.Matrix();
  9464. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9465. rotQuaternion.toRotationMatrix(rotMatrix);
  9466. var translationDelta = BABYLON.Vector3.Zero();
  9467. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9469. return translationDelta;
  9470. };
  9471. // ================================== Point of View Rotation =================================
  9472. /**
  9473. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9474. * Supports definition of mesh facing forward or backward.
  9475. * @param {number} flipBack
  9476. * @param {number} twirlClockwise
  9477. * @param {number} tiltRight
  9478. */
  9479. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9480. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9481. };
  9482. /**
  9483. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9484. * Supports definition of mesh facing forward or backward.
  9485. * @param {number} flipBack
  9486. * @param {number} twirlClockwise
  9487. * @param {number} tiltRight
  9488. */
  9489. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9490. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9491. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9492. };
  9493. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9494. this._pivotMatrix = matrix;
  9495. this._cache.pivotMatrixUpdated = true;
  9496. };
  9497. AbstractMesh.prototype.getPivotMatrix = function () {
  9498. return this._pivotMatrix;
  9499. };
  9500. AbstractMesh.prototype._isSynchronized = function () {
  9501. if (this._isDirty) {
  9502. return false;
  9503. }
  9504. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9505. return false;
  9506. if (this._cache.pivotMatrixUpdated) {
  9507. return false;
  9508. }
  9509. if (this.infiniteDistance) {
  9510. return false;
  9511. }
  9512. if (!this._cache.position.equals(this.position))
  9513. return false;
  9514. if (this.rotationQuaternion) {
  9515. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9516. return false;
  9517. }
  9518. else {
  9519. if (!this._cache.rotation.equals(this.rotation))
  9520. return false;
  9521. }
  9522. if (!this._cache.scaling.equals(this.scaling))
  9523. return false;
  9524. return true;
  9525. };
  9526. AbstractMesh.prototype._initCache = function () {
  9527. _super.prototype._initCache.call(this);
  9528. this._cache.localMatrixUpdated = false;
  9529. this._cache.position = BABYLON.Vector3.Zero();
  9530. this._cache.scaling = BABYLON.Vector3.Zero();
  9531. this._cache.rotation = BABYLON.Vector3.Zero();
  9532. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9533. };
  9534. AbstractMesh.prototype.markAsDirty = function (property) {
  9535. if (property === "rotation") {
  9536. this.rotationQuaternion = null;
  9537. }
  9538. this._currentRenderId = Number.MAX_VALUE;
  9539. this._isDirty = true;
  9540. };
  9541. AbstractMesh.prototype._updateBoundingInfo = function () {
  9542. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9543. this._boundingInfo._update(this.worldMatrixFromCache);
  9544. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9545. };
  9546. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9547. if (!this.subMeshes) {
  9548. return;
  9549. }
  9550. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9551. var subMesh = this.subMeshes[subIndex];
  9552. subMesh.updateBoundingInfo(matrix);
  9553. }
  9554. };
  9555. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9556. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9557. return this._worldMatrix;
  9558. }
  9559. this._cache.position.copyFrom(this.position);
  9560. this._cache.scaling.copyFrom(this.scaling);
  9561. this._cache.pivotMatrixUpdated = false;
  9562. this._currentRenderId = this.getScene().getRenderId();
  9563. this._isDirty = false;
  9564. // Scaling
  9565. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9566. // Rotation
  9567. if (this.rotationQuaternion) {
  9568. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9569. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9570. }
  9571. else {
  9572. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9573. this._cache.rotation.copyFrom(this.rotation);
  9574. }
  9575. // Translation
  9576. if (this.infiniteDistance && !this.parent) {
  9577. var camera = this.getScene().activeCamera;
  9578. var cameraWorldMatrix = camera.getWorldMatrix();
  9579. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9580. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9581. }
  9582. else {
  9583. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9584. }
  9585. // Composing transformations
  9586. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9587. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9588. // Billboarding
  9589. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9590. var localPosition = this.position.clone();
  9591. var zero = this.getScene().activeCamera.position.clone();
  9592. if (this.parent && this.parent.position) {
  9593. localPosition.addInPlace(this.parent.position);
  9594. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9595. }
  9596. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9597. zero = this.getScene().activeCamera.position;
  9598. }
  9599. else {
  9600. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9601. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9602. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9603. zero.y = localPosition.y + 0.001;
  9604. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9605. zero.z = localPosition.z + 0.001;
  9606. }
  9607. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9608. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9609. this._localBillboard.invert();
  9610. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9611. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9612. }
  9613. // Local world
  9614. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9615. // Parent
  9616. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9617. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9618. }
  9619. else {
  9620. this._worldMatrix.copyFrom(this._localWorld);
  9621. }
  9622. // Bounding info
  9623. this._updateBoundingInfo();
  9624. // Absolute position
  9625. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9626. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9627. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9628. }
  9629. return this._worldMatrix;
  9630. };
  9631. /**
  9632. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9633. * @param func: callback function to add
  9634. */
  9635. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9636. this._onAfterWorldMatrixUpdate.push(func);
  9637. };
  9638. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9639. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9640. if (index > -1) {
  9641. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9642. }
  9643. };
  9644. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9645. this.computeWorldMatrix();
  9646. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9647. };
  9648. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9649. this.computeWorldMatrix();
  9650. var invLocalWorldMatrix = this._localWorld.clone();
  9651. invLocalWorldMatrix.invert();
  9652. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9653. };
  9654. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9655. this.computeWorldMatrix();
  9656. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9657. };
  9658. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9659. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9660. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9661. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9662. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9663. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9664. /// <returns>Mesh oriented towards targetMesh</returns>
  9665. yawCor = yawCor || 0; // default to zero if undefined
  9666. pitchCor = pitchCor || 0;
  9667. rollCor = rollCor || 0;
  9668. var dv = targetPoint.subtract(this.position);
  9669. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9670. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9671. var pitch = Math.atan2(dv.y, len);
  9672. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9673. };
  9674. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9675. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9676. return false;
  9677. }
  9678. return true;
  9679. };
  9680. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9681. if (!camera) {
  9682. camera = this.getScene().activeCamera;
  9683. }
  9684. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9685. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9686. return false;
  9687. }
  9688. return true;
  9689. };
  9690. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9691. if (!this._boundingInfo || !mesh._boundingInfo) {
  9692. return false;
  9693. }
  9694. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9695. };
  9696. AbstractMesh.prototype.intersectsPoint = function (point) {
  9697. if (!this._boundingInfo) {
  9698. return false;
  9699. }
  9700. return this._boundingInfo.intersectsPoint(point);
  9701. };
  9702. // Physics
  9703. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9704. var physicsEngine = this.getScene().getPhysicsEngine();
  9705. if (!physicsEngine) {
  9706. return;
  9707. }
  9708. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9709. if (impostor.impostor) {
  9710. // Old API
  9711. options = impostor;
  9712. impostor = impostor.impostor;
  9713. }
  9714. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9715. physicsEngine._unregisterMesh(this);
  9716. return;
  9717. }
  9718. if (!options) {
  9719. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9720. }
  9721. else {
  9722. if (!options.mass && options.mass !== 0)
  9723. options.mass = 0;
  9724. if (!options.friction && options.friction !== 0)
  9725. options.friction = 0.2;
  9726. if (!options.restitution && options.restitution !== 0)
  9727. options.restitution = 0.2;
  9728. }
  9729. this._physicImpostor = impostor;
  9730. this._physicsMass = options.mass;
  9731. this._physicsFriction = options.friction;
  9732. this._physicRestitution = options.restitution;
  9733. return physicsEngine._registerMesh(this, impostor, options);
  9734. };
  9735. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9736. if (!this._physicImpostor) {
  9737. return BABYLON.PhysicsEngine.NoImpostor;
  9738. }
  9739. return this._physicImpostor;
  9740. };
  9741. AbstractMesh.prototype.getPhysicsMass = function () {
  9742. if (!this._physicsMass) {
  9743. return 0;
  9744. }
  9745. return this._physicsMass;
  9746. };
  9747. AbstractMesh.prototype.getPhysicsFriction = function () {
  9748. if (!this._physicsFriction) {
  9749. return 0;
  9750. }
  9751. return this._physicsFriction;
  9752. };
  9753. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9754. if (!this._physicRestitution) {
  9755. return 0;
  9756. }
  9757. return this._physicRestitution;
  9758. };
  9759. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9760. if (!camera) {
  9761. camera = this.getScene().activeCamera;
  9762. }
  9763. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9764. };
  9765. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9766. if (!camera) {
  9767. camera = this.getScene().activeCamera;
  9768. }
  9769. return this.absolutePosition.subtract(camera.position).length();
  9770. };
  9771. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9772. if (!this._physicImpostor) {
  9773. return;
  9774. }
  9775. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9776. };
  9777. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9778. if (!this._physicImpostor) {
  9779. return;
  9780. }
  9781. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9782. };
  9783. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9784. if (!this._physicImpostor) {
  9785. return;
  9786. }
  9787. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9788. };
  9789. // Collisions
  9790. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9791. var globalPosition = this.getAbsolutePosition();
  9792. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9793. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9794. this._collider.radius = this.ellipsoid;
  9795. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9796. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9797. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9798. this.position.addInPlace(this._diffPositionForCollisions);
  9799. }
  9800. };
  9801. // Submeshes octree
  9802. /**
  9803. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9804. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9805. */
  9806. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9807. if (maxCapacity === void 0) { maxCapacity = 64; }
  9808. if (maxDepth === void 0) { maxDepth = 2; }
  9809. if (!this._submeshesOctree) {
  9810. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9811. }
  9812. this.computeWorldMatrix(true);
  9813. // Update octree
  9814. var bbox = this.getBoundingInfo().boundingBox;
  9815. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9816. return this._submeshesOctree;
  9817. };
  9818. // Collisions
  9819. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9820. this._generatePointsArray();
  9821. // Transformation
  9822. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9823. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9824. subMesh._lastColliderWorldVertices = [];
  9825. subMesh._trianglePlanes = [];
  9826. var start = subMesh.verticesStart;
  9827. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9828. for (var i = start; i < end; i++) {
  9829. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9830. }
  9831. }
  9832. // Collide
  9833. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9834. };
  9835. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9836. var subMeshes;
  9837. var len;
  9838. // Octrees
  9839. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9840. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9841. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9842. len = intersections.length;
  9843. subMeshes = intersections.data;
  9844. }
  9845. else {
  9846. subMeshes = this.subMeshes;
  9847. len = subMeshes.length;
  9848. }
  9849. for (var index = 0; index < len; index++) {
  9850. var subMesh = subMeshes[index];
  9851. // Bounding test
  9852. if (len > 1 && !subMesh._checkCollision(collider))
  9853. continue;
  9854. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9855. }
  9856. };
  9857. AbstractMesh.prototype._checkCollision = function (collider) {
  9858. // Bounding box test
  9859. if (!this._boundingInfo._checkCollision(collider))
  9860. return;
  9861. // Transformation matrix
  9862. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9863. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9864. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9865. };
  9866. // Picking
  9867. AbstractMesh.prototype._generatePointsArray = function () {
  9868. return false;
  9869. };
  9870. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9871. var pickingInfo = new BABYLON.PickingInfo();
  9872. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9873. return pickingInfo;
  9874. }
  9875. if (!this._generatePointsArray()) {
  9876. return pickingInfo;
  9877. }
  9878. var intersectInfo = null;
  9879. // Octrees
  9880. var subMeshes;
  9881. var len;
  9882. if (this._submeshesOctree && this.useOctreeForPicking) {
  9883. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9884. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9885. len = intersections.length;
  9886. subMeshes = intersections.data;
  9887. }
  9888. else {
  9889. subMeshes = this.subMeshes;
  9890. len = subMeshes.length;
  9891. }
  9892. for (var index = 0; index < len; index++) {
  9893. var subMesh = subMeshes[index];
  9894. // Bounding test
  9895. if (len > 1 && !subMesh.canIntersects(ray))
  9896. continue;
  9897. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9898. if (currentIntersectInfo) {
  9899. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9900. intersectInfo = currentIntersectInfo;
  9901. intersectInfo.subMeshId = index;
  9902. if (fastCheck) {
  9903. break;
  9904. }
  9905. }
  9906. }
  9907. }
  9908. if (intersectInfo) {
  9909. // Get picked point
  9910. var world = this.getWorldMatrix();
  9911. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9912. var direction = ray.direction.clone();
  9913. direction = direction.scale(intersectInfo.distance);
  9914. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9915. var pickedPoint = worldOrigin.add(worldDirection);
  9916. // Return result
  9917. pickingInfo.hit = true;
  9918. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9919. pickingInfo.pickedPoint = pickedPoint;
  9920. pickingInfo.pickedMesh = this;
  9921. pickingInfo.bu = intersectInfo.bu;
  9922. pickingInfo.bv = intersectInfo.bv;
  9923. pickingInfo.faceId = intersectInfo.faceId;
  9924. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9925. return pickingInfo;
  9926. }
  9927. return pickingInfo;
  9928. };
  9929. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9930. return null;
  9931. };
  9932. AbstractMesh.prototype.releaseSubMeshes = function () {
  9933. if (this.subMeshes) {
  9934. while (this.subMeshes.length) {
  9935. this.subMeshes[0].dispose();
  9936. }
  9937. }
  9938. else {
  9939. this.subMeshes = new Array();
  9940. }
  9941. };
  9942. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9943. // Physics
  9944. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9945. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9946. }
  9947. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9948. var other = this._intersectionsInProgress[index];
  9949. var pos = other._intersectionsInProgress.indexOf(this);
  9950. other._intersectionsInProgress.splice(pos, 1);
  9951. }
  9952. this._intersectionsInProgress = [];
  9953. // SubMeshes
  9954. this.releaseSubMeshes();
  9955. // Remove from scene
  9956. var index = this.getScene().meshes.indexOf(this);
  9957. if (index != -1) {
  9958. // Remove from the scene if mesh found
  9959. this.getScene().meshes.splice(index, 1);
  9960. }
  9961. if (!doNotRecurse) {
  9962. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9963. if (this.getScene().particleSystems[index].emitter == this) {
  9964. this.getScene().particleSystems[index].dispose();
  9965. index--;
  9966. }
  9967. }
  9968. // Children
  9969. var objects = this.getScene().meshes.slice(0);
  9970. for (index = 0; index < objects.length; index++) {
  9971. if (objects[index].parent == this) {
  9972. objects[index].dispose();
  9973. }
  9974. }
  9975. }
  9976. else {
  9977. for (index = 0; index < this.getScene().meshes.length; index++) {
  9978. var obj = this.getScene().meshes[index];
  9979. if (obj.parent === this) {
  9980. obj.parent = null;
  9981. obj.computeWorldMatrix(true);
  9982. }
  9983. }
  9984. }
  9985. this._onAfterWorldMatrixUpdate = [];
  9986. this._isDisposed = true;
  9987. // Callback
  9988. if (this.onDispose) {
  9989. this.onDispose();
  9990. }
  9991. };
  9992. // Statics
  9993. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9994. AbstractMesh._BILLBOARDMODE_X = 1;
  9995. AbstractMesh._BILLBOARDMODE_Y = 2;
  9996. AbstractMesh._BILLBOARDMODE_Z = 4;
  9997. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9998. return AbstractMesh;
  9999. })(BABYLON.Node);
  10000. BABYLON.AbstractMesh = AbstractMesh;
  10001. })(BABYLON || (BABYLON = {}));
  10002. //# sourceMappingURL=babylon.abstractMesh.js.map
  10003. var BABYLON;
  10004. (function (BABYLON) {
  10005. var _InstancesBatch = (function () {
  10006. function _InstancesBatch() {
  10007. this.mustReturn = false;
  10008. this.visibleInstances = new Array();
  10009. this.renderSelf = new Array();
  10010. }
  10011. return _InstancesBatch;
  10012. })();
  10013. BABYLON._InstancesBatch = _InstancesBatch;
  10014. var Mesh = (function (_super) {
  10015. __extends(Mesh, _super);
  10016. /**
  10017. * @constructor
  10018. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10019. * @param {Scene} scene - The scene to add this mesh to.
  10020. * @param {Node} parent - The parent of this mesh, if it has one
  10021. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10022. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10023. * When false, achieved by calling a clone(), also passing False.
  10024. * This will make creation of children, recursive.
  10025. */
  10026. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10027. if (parent === void 0) { parent = null; }
  10028. _super.call(this, name, scene);
  10029. // Members
  10030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10031. this.instances = new Array();
  10032. this._LODLevels = new Array();
  10033. this._onBeforeRenderCallbacks = new Array();
  10034. this._onAfterRenderCallbacks = new Array();
  10035. this._visibleInstances = {};
  10036. this._renderIdForInstances = new Array();
  10037. this._batchCache = new _InstancesBatch();
  10038. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10039. if (source) {
  10040. // Geometry
  10041. if (source._geometry) {
  10042. source._geometry.applyToMesh(this);
  10043. }
  10044. // Deep copy
  10045. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10046. // Material
  10047. this.material = source.material;
  10048. if (!doNotCloneChildren) {
  10049. for (var index = 0; index < scene.meshes.length; index++) {
  10050. var mesh = scene.meshes[index];
  10051. if (mesh.parent === source) {
  10052. // doNotCloneChildren is always going to be False
  10053. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10054. }
  10055. }
  10056. }
  10057. for (index = 0; index < scene.particleSystems.length; index++) {
  10058. var system = scene.particleSystems[index];
  10059. if (system.emitter === source) {
  10060. system.clone(system.name, this);
  10061. }
  10062. }
  10063. this.computeWorldMatrix(true);
  10064. }
  10065. // Parent
  10066. if (parent !== null) {
  10067. this.parent = parent;
  10068. }
  10069. }
  10070. Object.defineProperty(Mesh, "FRONTSIDE", {
  10071. get: function () {
  10072. return Mesh._FRONTSIDE;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(Mesh, "BACKSIDE", {
  10078. get: function () {
  10079. return Mesh._BACKSIDE;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10085. get: function () {
  10086. return Mesh._DOUBLESIDE;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10092. get: function () {
  10093. return Mesh._DEFAULTSIDE;
  10094. },
  10095. enumerable: true,
  10096. configurable: true
  10097. });
  10098. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10099. // Methods
  10100. get: function () {
  10101. return this._LODLevels.length > 0;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Mesh.prototype._sortLODLevels = function () {
  10107. this._LODLevels.sort(function (a, b) {
  10108. if (a.distance < b.distance) {
  10109. return 1;
  10110. }
  10111. if (a.distance > b.distance) {
  10112. return -1;
  10113. }
  10114. return 0;
  10115. });
  10116. };
  10117. /**
  10118. * Add a mesh as LOD level triggered at the given distance.
  10119. * @param {number} distance - the distance from the center of the object to show this level
  10120. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10121. * @return {BABYLON.Mesh} this mesh (for chaining)
  10122. */
  10123. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10124. if (mesh && mesh._masterMesh) {
  10125. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10126. return this;
  10127. }
  10128. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10129. this._LODLevels.push(level);
  10130. if (mesh) {
  10131. mesh._masterMesh = this;
  10132. }
  10133. this._sortLODLevels();
  10134. return this;
  10135. };
  10136. /**
  10137. * Remove a mesh from the LOD array
  10138. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10139. * @return {BABYLON.Mesh} this mesh (for chaining)
  10140. */
  10141. Mesh.prototype.removeLODLevel = function (mesh) {
  10142. for (var index = 0; index < this._LODLevels.length; index++) {
  10143. if (this._LODLevels[index].mesh === mesh) {
  10144. this._LODLevels.splice(index, 1);
  10145. if (mesh) {
  10146. mesh._masterMesh = null;
  10147. }
  10148. }
  10149. }
  10150. this._sortLODLevels();
  10151. return this;
  10152. };
  10153. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10154. if (!this._LODLevels || this._LODLevels.length === 0) {
  10155. return this;
  10156. }
  10157. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10158. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10159. return this;
  10160. }
  10161. for (var index = 0; index < this._LODLevels.length; index++) {
  10162. var level = this._LODLevels[index];
  10163. if (level.distance < distanceToCamera) {
  10164. if (level.mesh) {
  10165. level.mesh._preActivate();
  10166. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10167. }
  10168. return level.mesh;
  10169. }
  10170. }
  10171. return this;
  10172. };
  10173. Object.defineProperty(Mesh.prototype, "geometry", {
  10174. get: function () {
  10175. return this._geometry;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. Mesh.prototype.getTotalVertices = function () {
  10181. if (!this._geometry) {
  10182. return 0;
  10183. }
  10184. return this._geometry.getTotalVertices();
  10185. };
  10186. Mesh.prototype.getVerticesData = function (kind) {
  10187. if (!this._geometry) {
  10188. return null;
  10189. }
  10190. return this._geometry.getVerticesData(kind);
  10191. };
  10192. Mesh.prototype.getVertexBuffer = function (kind) {
  10193. if (!this._geometry) {
  10194. return undefined;
  10195. }
  10196. return this._geometry.getVertexBuffer(kind);
  10197. };
  10198. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10199. if (!this._geometry) {
  10200. if (this._delayInfo) {
  10201. return this._delayInfo.indexOf(kind) !== -1;
  10202. }
  10203. return false;
  10204. }
  10205. return this._geometry.isVerticesDataPresent(kind);
  10206. };
  10207. Mesh.prototype.getVerticesDataKinds = function () {
  10208. if (!this._geometry) {
  10209. var result = [];
  10210. if (this._delayInfo) {
  10211. for (var kind in this._delayInfo) {
  10212. result.push(kind);
  10213. }
  10214. }
  10215. return result;
  10216. }
  10217. return this._geometry.getVerticesDataKinds();
  10218. };
  10219. Mesh.prototype.getTotalIndices = function () {
  10220. if (!this._geometry) {
  10221. return 0;
  10222. }
  10223. return this._geometry.getTotalIndices();
  10224. };
  10225. Mesh.prototype.getIndices = function () {
  10226. if (!this._geometry) {
  10227. return [];
  10228. }
  10229. return this._geometry.getIndices();
  10230. };
  10231. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10232. get: function () {
  10233. return this._masterMesh !== null && this._masterMesh !== undefined;
  10234. },
  10235. enumerable: true,
  10236. configurable: true
  10237. });
  10238. Mesh.prototype.isReady = function () {
  10239. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10240. return false;
  10241. }
  10242. return _super.prototype.isReady.call(this);
  10243. };
  10244. Mesh.prototype.isDisposed = function () {
  10245. return this._isDisposed;
  10246. };
  10247. // Methods
  10248. Mesh.prototype._preActivate = function () {
  10249. var sceneRenderId = this.getScene().getRenderId();
  10250. if (this._preActivateId == sceneRenderId) {
  10251. return;
  10252. }
  10253. this._preActivateId = sceneRenderId;
  10254. this._visibleInstances = null;
  10255. };
  10256. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10257. if (!this._visibleInstances) {
  10258. this._visibleInstances = {};
  10259. this._visibleInstances.defaultRenderId = renderId;
  10260. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10261. }
  10262. if (!this._visibleInstances[renderId]) {
  10263. this._visibleInstances[renderId] = new Array();
  10264. }
  10265. this._visibleInstances[renderId].push(instance);
  10266. };
  10267. Mesh.prototype.refreshBoundingInfo = function () {
  10268. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10269. if (data) {
  10270. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10271. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10272. }
  10273. if (this.subMeshes) {
  10274. for (var index = 0; index < this.subMeshes.length; index++) {
  10275. this.subMeshes[index].refreshBoundingInfo();
  10276. }
  10277. }
  10278. this._updateBoundingInfo();
  10279. };
  10280. Mesh.prototype._createGlobalSubMesh = function () {
  10281. var totalVertices = this.getTotalVertices();
  10282. if (!totalVertices || !this.getIndices()) {
  10283. return null;
  10284. }
  10285. this.releaseSubMeshes();
  10286. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10287. };
  10288. Mesh.prototype.subdivide = function (count) {
  10289. if (count < 1) {
  10290. return;
  10291. }
  10292. var totalIndices = this.getTotalIndices();
  10293. var subdivisionSize = (totalIndices / count) | 0;
  10294. var offset = 0;
  10295. while (subdivisionSize % 3 !== 0) {
  10296. subdivisionSize++;
  10297. }
  10298. this.releaseSubMeshes();
  10299. for (var index = 0; index < count; index++) {
  10300. if (offset >= totalIndices) {
  10301. break;
  10302. }
  10303. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10304. offset += subdivisionSize;
  10305. }
  10306. this.synchronizeInstances();
  10307. };
  10308. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10309. if (kind instanceof Array) {
  10310. var temp = data;
  10311. data = kind;
  10312. kind = temp;
  10313. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10314. }
  10315. if (!this._geometry) {
  10316. var vertexData = new BABYLON.VertexData();
  10317. vertexData.set(data, kind);
  10318. var scene = this.getScene();
  10319. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10320. }
  10321. else {
  10322. this._geometry.setVerticesData(kind, data, updatable, stride);
  10323. }
  10324. };
  10325. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10326. if (!this._geometry) {
  10327. return;
  10328. }
  10329. if (!makeItUnique) {
  10330. this._geometry.updateVerticesData(kind, data, updateExtends);
  10331. }
  10332. else {
  10333. this.makeGeometryUnique();
  10334. this.updateVerticesData(kind, data, updateExtends, false);
  10335. }
  10336. };
  10337. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10338. if (!this._geometry) {
  10339. return;
  10340. }
  10341. if (!makeItUnique) {
  10342. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10343. }
  10344. else {
  10345. this.makeGeometryUnique();
  10346. this.updateVerticesDataDirectly(kind, data, offset, false);
  10347. }
  10348. };
  10349. Mesh.prototype.makeGeometryUnique = function () {
  10350. if (!this._geometry) {
  10351. return;
  10352. }
  10353. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10354. geometry.applyToMesh(this);
  10355. };
  10356. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10357. if (!this._geometry) {
  10358. var vertexData = new BABYLON.VertexData();
  10359. vertexData.indices = indices;
  10360. var scene = this.getScene();
  10361. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10362. }
  10363. else {
  10364. this._geometry.setIndices(indices, totalVertices);
  10365. }
  10366. };
  10367. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10368. var engine = this.getScene().getEngine();
  10369. // Wireframe
  10370. var indexToBind;
  10371. switch (fillMode) {
  10372. case BABYLON.Material.PointFillMode:
  10373. indexToBind = null;
  10374. break;
  10375. case BABYLON.Material.WireFrameFillMode:
  10376. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10377. break;
  10378. default:
  10379. case BABYLON.Material.TriangleFillMode:
  10380. indexToBind = this._geometry.getIndexBuffer();
  10381. break;
  10382. }
  10383. // VBOs
  10384. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10385. };
  10386. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10387. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10388. return;
  10389. }
  10390. var engine = this.getScene().getEngine();
  10391. switch (fillMode) {
  10392. case BABYLON.Material.PointFillMode:
  10393. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10394. break;
  10395. case BABYLON.Material.WireFrameFillMode:
  10396. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10397. break;
  10398. default:
  10399. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10400. }
  10401. };
  10402. Mesh.prototype.registerBeforeRender = function (func) {
  10403. this._onBeforeRenderCallbacks.push(func);
  10404. };
  10405. Mesh.prototype.unregisterBeforeRender = function (func) {
  10406. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10407. if (index > -1) {
  10408. this._onBeforeRenderCallbacks.splice(index, 1);
  10409. }
  10410. };
  10411. Mesh.prototype.registerAfterRender = function (func) {
  10412. this._onAfterRenderCallbacks.push(func);
  10413. };
  10414. Mesh.prototype.unregisterAfterRender = function (func) {
  10415. var index = this._onAfterRenderCallbacks.indexOf(func);
  10416. if (index > -1) {
  10417. this._onAfterRenderCallbacks.splice(index, 1);
  10418. }
  10419. };
  10420. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10421. var scene = this.getScene();
  10422. this._batchCache.mustReturn = false;
  10423. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10424. this._batchCache.visibleInstances[subMeshId] = null;
  10425. if (this._visibleInstances) {
  10426. var currentRenderId = scene.getRenderId();
  10427. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10428. var selfRenderId = this._renderId;
  10429. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10430. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10431. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10432. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10433. }
  10434. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10435. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10436. this._batchCache.mustReturn = true;
  10437. return this._batchCache;
  10438. }
  10439. if (currentRenderId !== selfRenderId) {
  10440. this._batchCache.renderSelf[subMeshId] = false;
  10441. }
  10442. }
  10443. this._renderIdForInstances[subMeshId] = currentRenderId;
  10444. }
  10445. return this._batchCache;
  10446. };
  10447. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10448. var visibleInstances = batch.visibleInstances[subMesh._id];
  10449. var matricesCount = visibleInstances.length + 1;
  10450. var bufferSize = matricesCount * 16 * 4;
  10451. while (this._instancesBufferSize < bufferSize) {
  10452. this._instancesBufferSize *= 2;
  10453. }
  10454. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10455. if (this._worldMatricesInstancesBuffer) {
  10456. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10457. }
  10458. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10459. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10460. }
  10461. var offset = 0;
  10462. var instancesCount = 0;
  10463. var world = this.getWorldMatrix();
  10464. if (batch.renderSelf[subMesh._id]) {
  10465. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10466. offset += 16;
  10467. instancesCount++;
  10468. }
  10469. if (visibleInstances) {
  10470. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10471. var instance = visibleInstances[instanceIndex];
  10472. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10473. offset += 16;
  10474. instancesCount++;
  10475. }
  10476. }
  10477. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10478. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10479. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10480. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10481. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10482. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10483. this._draw(subMesh, fillMode, instancesCount);
  10484. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10485. };
  10486. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10487. var scene = this.getScene();
  10488. var engine = scene.getEngine();
  10489. if (hardwareInstancedRendering) {
  10490. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10491. }
  10492. else {
  10493. if (batch.renderSelf[subMesh._id]) {
  10494. // Draw
  10495. if (onBeforeDraw) {
  10496. onBeforeDraw(false, this.getWorldMatrix());
  10497. }
  10498. this._draw(subMesh, fillMode);
  10499. }
  10500. if (batch.visibleInstances[subMesh._id]) {
  10501. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10502. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10503. // World
  10504. var world = instance.getWorldMatrix();
  10505. if (onBeforeDraw) {
  10506. onBeforeDraw(true, world);
  10507. }
  10508. // Draw
  10509. this._draw(subMesh, fillMode);
  10510. }
  10511. }
  10512. }
  10513. };
  10514. Mesh.prototype.render = function (subMesh) {
  10515. var scene = this.getScene();
  10516. // Managing instances
  10517. var batch = this._getInstancesRenderList(subMesh._id);
  10518. if (batch.mustReturn) {
  10519. return;
  10520. }
  10521. // Checking geometry state
  10522. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10523. return;
  10524. }
  10525. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10526. this._onBeforeRenderCallbacks[callbackIndex]();
  10527. }
  10528. var engine = scene.getEngine();
  10529. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10530. // Material
  10531. var effectiveMaterial = subMesh.getMaterial();
  10532. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10533. return;
  10534. }
  10535. // Outline - step 1
  10536. var savedDepthWrite = engine.getDepthWrite();
  10537. if (this.renderOutline) {
  10538. engine.setDepthWrite(false);
  10539. scene.getOutlineRenderer().render(subMesh, batch);
  10540. engine.setDepthWrite(savedDepthWrite);
  10541. }
  10542. effectiveMaterial._preBind();
  10543. var effect = effectiveMaterial.getEffect();
  10544. // Bind
  10545. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10546. this._bind(subMesh, effect, fillMode);
  10547. var world = this.getWorldMatrix();
  10548. effectiveMaterial.bind(world, this);
  10549. // Draw
  10550. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10551. if (isInstance) {
  10552. effectiveMaterial.bindOnlyWorldMatrix(world);
  10553. }
  10554. });
  10555. // Unbind
  10556. effectiveMaterial.unbind();
  10557. // Outline - step 2
  10558. if (this.renderOutline && savedDepthWrite) {
  10559. engine.setDepthWrite(true);
  10560. engine.setColorWrite(false);
  10561. scene.getOutlineRenderer().render(subMesh, batch);
  10562. engine.setColorWrite(true);
  10563. }
  10564. // Overlay
  10565. if (this.renderOverlay) {
  10566. var currentMode = engine.getAlphaMode();
  10567. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10568. scene.getOutlineRenderer().render(subMesh, batch, true);
  10569. engine.setAlphaMode(currentMode);
  10570. }
  10571. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10572. this._onAfterRenderCallbacks[callbackIndex]();
  10573. }
  10574. };
  10575. Mesh.prototype.getEmittedParticleSystems = function () {
  10576. var results = new Array();
  10577. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10578. var particleSystem = this.getScene().particleSystems[index];
  10579. if (particleSystem.emitter === this) {
  10580. results.push(particleSystem);
  10581. }
  10582. }
  10583. return results;
  10584. };
  10585. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10586. var results = new Array();
  10587. var descendants = this.getDescendants();
  10588. descendants.push(this);
  10589. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10590. var particleSystem = this.getScene().particleSystems[index];
  10591. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10592. results.push(particleSystem);
  10593. }
  10594. }
  10595. return results;
  10596. };
  10597. Mesh.prototype.getChildren = function () {
  10598. var results = [];
  10599. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10600. var mesh = this.getScene().meshes[index];
  10601. if (mesh.parent === this) {
  10602. results.push(mesh);
  10603. }
  10604. }
  10605. return results;
  10606. };
  10607. Mesh.prototype._checkDelayState = function () {
  10608. var _this = this;
  10609. var that = this;
  10610. var scene = this.getScene();
  10611. if (this._geometry) {
  10612. this._geometry.load(scene);
  10613. }
  10614. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10615. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10616. scene._addPendingData(that);
  10617. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10618. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10619. if (data instanceof ArrayBuffer) {
  10620. _this._delayLoadingFunction(data, _this);
  10621. }
  10622. else {
  10623. _this._delayLoadingFunction(JSON.parse(data), _this);
  10624. }
  10625. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10626. scene._removePendingData(_this);
  10627. }, function () {
  10628. }, scene.database, getBinaryData);
  10629. }
  10630. };
  10631. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10632. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10633. return false;
  10634. }
  10635. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10636. return false;
  10637. }
  10638. this._checkDelayState();
  10639. return true;
  10640. };
  10641. Mesh.prototype.setMaterialByID = function (id) {
  10642. var materials = this.getScene().materials;
  10643. for (var index = 0; index < materials.length; index++) {
  10644. if (materials[index].id === id) {
  10645. this.material = materials[index];
  10646. return;
  10647. }
  10648. }
  10649. // Multi
  10650. var multiMaterials = this.getScene().multiMaterials;
  10651. for (index = 0; index < multiMaterials.length; index++) {
  10652. if (multiMaterials[index].id === id) {
  10653. this.material = multiMaterials[index];
  10654. return;
  10655. }
  10656. }
  10657. };
  10658. Mesh.prototype.getAnimatables = function () {
  10659. var results = [];
  10660. if (this.material) {
  10661. results.push(this.material);
  10662. }
  10663. if (this.skeleton) {
  10664. results.push(this.skeleton);
  10665. }
  10666. return results;
  10667. };
  10668. // Geometry
  10669. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10670. // Position
  10671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10672. return;
  10673. }
  10674. this._resetPointsArrayCache();
  10675. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10676. var temp = [];
  10677. for (var index = 0; index < data.length; index += 3) {
  10678. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10679. }
  10680. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10681. // Normals
  10682. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10683. return;
  10684. }
  10685. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10686. for (index = 0; index < data.length; index += 3) {
  10687. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10688. }
  10689. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10690. };
  10691. // Cache
  10692. Mesh.prototype._resetPointsArrayCache = function () {
  10693. this._positions = null;
  10694. };
  10695. Mesh.prototype._generatePointsArray = function () {
  10696. if (this._positions)
  10697. return true;
  10698. this._positions = [];
  10699. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10700. if (!data) {
  10701. return false;
  10702. }
  10703. for (var index = 0; index < data.length; index += 3) {
  10704. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10705. }
  10706. return true;
  10707. };
  10708. // Clone
  10709. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10710. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10711. };
  10712. // Dispose
  10713. Mesh.prototype.dispose = function (doNotRecurse) {
  10714. if (this._geometry) {
  10715. this._geometry.releaseForMesh(this, true);
  10716. }
  10717. // Instances
  10718. if (this._worldMatricesInstancesBuffer) {
  10719. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10720. this._worldMatricesInstancesBuffer = null;
  10721. }
  10722. while (this.instances.length) {
  10723. this.instances[0].dispose();
  10724. }
  10725. _super.prototype.dispose.call(this, doNotRecurse);
  10726. };
  10727. // Geometric tools
  10728. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10729. var _this = this;
  10730. var scene = this.getScene();
  10731. var onload = function (img) {
  10732. // Getting height map data
  10733. var canvas = document.createElement("canvas");
  10734. var context = canvas.getContext("2d");
  10735. var heightMapWidth = img.width;
  10736. var heightMapHeight = img.height;
  10737. canvas.width = heightMapWidth;
  10738. canvas.height = heightMapHeight;
  10739. context.drawImage(img, 0, 0);
  10740. // Create VertexData from map data
  10741. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  10742. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10743. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10744. //execute success callback, if set
  10745. if (onSuccess) {
  10746. onSuccess(_this);
  10747. }
  10748. };
  10749. BABYLON.Tools.LoadImage(url, onload, function () {
  10750. }, scene.database);
  10751. };
  10752. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10753. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10754. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10755. return;
  10756. }
  10757. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10758. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10759. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10760. var position = BABYLON.Vector3.Zero();
  10761. var normal = BABYLON.Vector3.Zero();
  10762. var uv = BABYLON.Vector2.Zero();
  10763. for (var index = 0; index < positions.length; index += 3) {
  10764. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10765. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10766. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10767. // Compute height
  10768. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10769. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10770. var pos = (u + v * heightMapWidth) * 4;
  10771. var r = buffer[pos] / 255.0;
  10772. var g = buffer[pos + 1] / 255.0;
  10773. var b = buffer[pos + 2] / 255.0;
  10774. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10775. normal.normalize();
  10776. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10777. position = position.add(normal);
  10778. position.toArray(positions, index);
  10779. }
  10780. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10781. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10782. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10783. };
  10784. Mesh.prototype.convertToFlatShadedMesh = function () {
  10785. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10786. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10787. var kinds = this.getVerticesDataKinds();
  10788. var vbs = [];
  10789. var data = [];
  10790. var newdata = [];
  10791. var updatableNormals = false;
  10792. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10793. var kind = kinds[kindIndex];
  10794. var vertexBuffer = this.getVertexBuffer(kind);
  10795. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10796. updatableNormals = vertexBuffer.isUpdatable();
  10797. kinds.splice(kindIndex, 1);
  10798. kindIndex--;
  10799. continue;
  10800. }
  10801. vbs[kind] = vertexBuffer;
  10802. data[kind] = vbs[kind].getData();
  10803. newdata[kind] = [];
  10804. }
  10805. // Save previous submeshes
  10806. var previousSubmeshes = this.subMeshes.slice(0);
  10807. var indices = this.getIndices();
  10808. var totalIndices = this.getTotalIndices();
  10809. for (var index = 0; index < totalIndices; index++) {
  10810. var vertexIndex = indices[index];
  10811. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10812. kind = kinds[kindIndex];
  10813. var stride = vbs[kind].getStrideSize();
  10814. for (var offset = 0; offset < stride; offset++) {
  10815. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10816. }
  10817. }
  10818. }
  10819. // Updating faces & normal
  10820. var normals = [];
  10821. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10822. for (index = 0; index < totalIndices; index += 3) {
  10823. indices[index] = index;
  10824. indices[index + 1] = index + 1;
  10825. indices[index + 2] = index + 2;
  10826. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10827. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10828. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10829. var p1p2 = p1.subtract(p2);
  10830. var p3p2 = p3.subtract(p2);
  10831. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10832. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10833. normals.push(normal.x);
  10834. normals.push(normal.y);
  10835. normals.push(normal.z);
  10836. }
  10837. }
  10838. this.setIndices(indices);
  10839. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10840. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10841. kind = kinds[kindIndex];
  10842. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10843. }
  10844. // Updating submeshes
  10845. this.releaseSubMeshes();
  10846. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10847. var previousOne = previousSubmeshes[submeshIndex];
  10848. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10849. }
  10850. this.synchronizeInstances();
  10851. };
  10852. // Instances
  10853. Mesh.prototype.createInstance = function (name) {
  10854. return new BABYLON.InstancedMesh(name, this);
  10855. };
  10856. Mesh.prototype.synchronizeInstances = function () {
  10857. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10858. var instance = this.instances[instanceIndex];
  10859. instance._syncSubMeshes();
  10860. }
  10861. };
  10862. /**
  10863. * Simplify the mesh according to the given array of settings.
  10864. * Function will return immediately and will simplify async.
  10865. * @param settings a collection of simplification settings.
  10866. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10867. * @param type the type of simplification to run.
  10868. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10869. */
  10870. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10871. var _this = this;
  10872. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10873. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10874. var getSimplifier = function () {
  10875. switch (type) {
  10876. case 0 /* QUADRATIC */:
  10877. default:
  10878. return new BABYLON.QuadraticErrorSimplification(_this);
  10879. }
  10880. };
  10881. if (parallelProcessing) {
  10882. //parallel simplifier
  10883. settings.forEach(function (setting) {
  10884. var simplifier = getSimplifier();
  10885. simplifier.simplify(setting, function (newMesh) {
  10886. _this.addLODLevel(setting.distance, newMesh);
  10887. //check if it is the last
  10888. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10889. //all done, run the success callback.
  10890. successCallback();
  10891. }
  10892. });
  10893. });
  10894. }
  10895. else {
  10896. //single simplifier.
  10897. var simplifier = getSimplifier();
  10898. var runDecimation = function (setting, callback) {
  10899. simplifier.simplify(setting, function (newMesh) {
  10900. _this.addLODLevel(setting.distance, newMesh);
  10901. //run the next quality level
  10902. callback();
  10903. });
  10904. };
  10905. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10906. runDecimation(settings[loop.index], function () {
  10907. loop.executeNext();
  10908. });
  10909. }, function () {
  10910. //execution ended, run the success callback.
  10911. if (successCallback) {
  10912. successCallback();
  10913. }
  10914. });
  10915. }
  10916. };
  10917. // Statics
  10918. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  10919. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10920. var ribbon = new Mesh(name, scene);
  10921. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  10922. vertexData.applyToMesh(ribbon, updatable);
  10923. return ribbon;
  10924. };
  10925. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  10926. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10927. var box = new Mesh(name, scene);
  10928. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  10929. vertexData.applyToMesh(box, updatable);
  10930. return box;
  10931. };
  10932. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  10933. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10934. var sphere = new Mesh(name, scene);
  10935. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  10936. vertexData.applyToMesh(sphere, updatable);
  10937. return sphere;
  10938. };
  10939. // Cylinder and cone (Code inspired by SharpDX.org)
  10940. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  10941. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10942. // subdivisions is a new parameter, we need to support old signature
  10943. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10944. if (scene !== undefined) {
  10945. updatable = scene;
  10946. }
  10947. scene = subdivisions;
  10948. subdivisions = 1;
  10949. }
  10950. var cylinder = new Mesh(name, scene);
  10951. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10952. vertexData.applyToMesh(cylinder, updatable);
  10953. return cylinder;
  10954. };
  10955. // Torus (Code from SharpDX.org)
  10956. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  10957. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10958. var torus = new Mesh(name, scene);
  10959. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  10960. vertexData.applyToMesh(torus, updatable);
  10961. return torus;
  10962. };
  10963. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  10964. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10965. var torusKnot = new Mesh(name, scene);
  10966. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  10967. vertexData.applyToMesh(torusKnot, updatable);
  10968. return torusKnot;
  10969. };
  10970. // Lines
  10971. Mesh.CreateLines = function (name, points, scene, updatable) {
  10972. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10973. var vertexData = BABYLON.VertexData.CreateLines(points);
  10974. vertexData.applyToMesh(lines, updatable);
  10975. return lines;
  10976. };
  10977. // Plane & ground
  10978. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  10979. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  10980. var plane = new Mesh(name, scene);
  10981. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  10982. vertexData.applyToMesh(plane, updatable);
  10983. return plane;
  10984. };
  10985. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10986. var ground = new BABYLON.GroundMesh(name, scene);
  10987. ground._setReady(false);
  10988. ground._subdivisions = subdivisions;
  10989. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10990. vertexData.applyToMesh(ground, updatable);
  10991. ground._setReady(true);
  10992. return ground;
  10993. };
  10994. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10995. var tiledGround = new Mesh(name, scene);
  10996. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10997. vertexData.applyToMesh(tiledGround, updatable);
  10998. return tiledGround;
  10999. };
  11000. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11001. var ground = new BABYLON.GroundMesh(name, scene);
  11002. ground._subdivisions = subdivisions;
  11003. ground._setReady(false);
  11004. var onload = function (img) {
  11005. // Getting height map data
  11006. var canvas = document.createElement("canvas");
  11007. var context = canvas.getContext("2d");
  11008. var heightMapWidth = img.width;
  11009. var heightMapHeight = img.height;
  11010. canvas.width = heightMapWidth;
  11011. canvas.height = heightMapHeight;
  11012. context.drawImage(img, 0, 0);
  11013. // Create VertexData from map data
  11014. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11015. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11016. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11017. vertexData.applyToMesh(ground, updatable);
  11018. ground._setReady(true);
  11019. //execute ready callback, if set
  11020. if (onReady) {
  11021. onReady(ground);
  11022. }
  11023. };
  11024. BABYLON.Tools.LoadImage(url, onload, function () {
  11025. }, scene.database);
  11026. return ground;
  11027. };
  11028. // Tools
  11029. Mesh.MinMax = function (meshes) {
  11030. var minVector = null;
  11031. var maxVector = null;
  11032. for (var i in meshes) {
  11033. var mesh = meshes[i];
  11034. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11035. if (!minVector) {
  11036. minVector = boundingBox.minimumWorld;
  11037. maxVector = boundingBox.maximumWorld;
  11038. continue;
  11039. }
  11040. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11041. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11042. }
  11043. return {
  11044. min: minVector,
  11045. max: maxVector
  11046. };
  11047. };
  11048. Mesh.Center = function (meshesOrMinMaxVector) {
  11049. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11050. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11051. };
  11052. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11053. if (disposeSource === void 0) { disposeSource = true; }
  11054. var source = meshes[0];
  11055. var material = source.material;
  11056. var scene = source.getScene();
  11057. if (!allow32BitsIndices) {
  11058. var totalVertices = 0;
  11059. for (var index = 0; index < meshes.length; index++) {
  11060. totalVertices += meshes[index].getTotalVertices();
  11061. if (totalVertices > 65536) {
  11062. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11063. return null;
  11064. }
  11065. }
  11066. }
  11067. // Merge
  11068. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11069. vertexData.transform(source.getWorldMatrix());
  11070. for (index = 1; index < meshes.length; index++) {
  11071. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11072. otherVertexData.transform(meshes[index].getWorldMatrix());
  11073. vertexData.merge(otherVertexData);
  11074. }
  11075. var newMesh = new Mesh(source.name + "_merged", scene);
  11076. vertexData.applyToMesh(newMesh);
  11077. // Setting properties
  11078. newMesh.material = material;
  11079. newMesh.checkCollisions = source.checkCollisions;
  11080. // Cleaning
  11081. if (disposeSource) {
  11082. for (index = 0; index < meshes.length; index++) {
  11083. meshes[index].dispose();
  11084. }
  11085. }
  11086. return newMesh;
  11087. };
  11088. // Consts
  11089. Mesh._FRONTSIDE = 0;
  11090. Mesh._BACKSIDE = 1;
  11091. Mesh._DOUBLESIDE = 2;
  11092. Mesh._DEFAULTSIDE = 0;
  11093. return Mesh;
  11094. })(BABYLON.AbstractMesh);
  11095. BABYLON.Mesh = Mesh;
  11096. })(BABYLON || (BABYLON = {}));
  11097. //# sourceMappingURL=babylon.mesh.js.map
  11098. var BABYLON;
  11099. (function (BABYLON) {
  11100. var GroundMesh = (function (_super) {
  11101. __extends(GroundMesh, _super);
  11102. function GroundMesh(name, scene) {
  11103. _super.call(this, name, scene);
  11104. this.generateOctree = false;
  11105. this._worldInverse = new BABYLON.Matrix();
  11106. }
  11107. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11108. get: function () {
  11109. return this._subdivisions;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. GroundMesh.prototype.optimize = function (chunksCount) {
  11115. this.subdivide(this._subdivisions);
  11116. this.createOrUpdateSubmeshesOctree(32);
  11117. };
  11118. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11119. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11120. this.getWorldMatrix().invertToRef(this._worldInverse);
  11121. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11122. var pickInfo = this.intersects(ray);
  11123. if (pickInfo.hit) {
  11124. return pickInfo.pickedPoint.y;
  11125. }
  11126. return 0;
  11127. };
  11128. return GroundMesh;
  11129. })(BABYLON.Mesh);
  11130. BABYLON.GroundMesh = GroundMesh;
  11131. })(BABYLON || (BABYLON = {}));
  11132. //# sourceMappingURL=babylon.groundMesh.js.map
  11133. var BABYLON;
  11134. (function (BABYLON) {
  11135. /**
  11136. * Creates an instance based on a source mesh.
  11137. */
  11138. var InstancedMesh = (function (_super) {
  11139. __extends(InstancedMesh, _super);
  11140. function InstancedMesh(name, source) {
  11141. _super.call(this, name, source.getScene());
  11142. source.instances.push(this);
  11143. this._sourceMesh = source;
  11144. this.position.copyFrom(source.position);
  11145. this.rotation.copyFrom(source.rotation);
  11146. this.scaling.copyFrom(source.scaling);
  11147. if (source.rotationQuaternion) {
  11148. this.rotationQuaternion = source.rotationQuaternion.clone();
  11149. }
  11150. this.infiniteDistance = source.infiniteDistance;
  11151. this.setPivotMatrix(source.getPivotMatrix());
  11152. this.refreshBoundingInfo();
  11153. this._syncSubMeshes();
  11154. }
  11155. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11156. // Methods
  11157. get: function () {
  11158. return this._sourceMesh.receiveShadows;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(InstancedMesh.prototype, "material", {
  11164. get: function () {
  11165. return this._sourceMesh.material;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11171. get: function () {
  11172. return this._sourceMesh.visibility;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11178. get: function () {
  11179. return this._sourceMesh.skeleton;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. InstancedMesh.prototype.getTotalVertices = function () {
  11185. return this._sourceMesh.getTotalVertices();
  11186. };
  11187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11188. get: function () {
  11189. return this._sourceMesh;
  11190. },
  11191. enumerable: true,
  11192. configurable: true
  11193. });
  11194. InstancedMesh.prototype.getVerticesData = function (kind) {
  11195. return this._sourceMesh.getVerticesData(kind);
  11196. };
  11197. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11198. return this._sourceMesh.isVerticesDataPresent(kind);
  11199. };
  11200. InstancedMesh.prototype.getIndices = function () {
  11201. return this._sourceMesh.getIndices();
  11202. };
  11203. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11204. get: function () {
  11205. return this._sourceMesh._positions;
  11206. },
  11207. enumerable: true,
  11208. configurable: true
  11209. });
  11210. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11211. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11212. if (data) {
  11213. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11214. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11215. }
  11216. this._updateBoundingInfo();
  11217. };
  11218. InstancedMesh.prototype._preActivate = function () {
  11219. if (this._currentLOD) {
  11220. this._currentLOD._preActivate();
  11221. }
  11222. };
  11223. InstancedMesh.prototype._activate = function (renderId) {
  11224. if (this._currentLOD) {
  11225. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11226. }
  11227. };
  11228. InstancedMesh.prototype.getLOD = function (camera) {
  11229. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11230. if (this._currentLOD === this.sourceMesh) {
  11231. return this;
  11232. }
  11233. return this._currentLOD;
  11234. };
  11235. InstancedMesh.prototype._syncSubMeshes = function () {
  11236. this.releaseSubMeshes();
  11237. if (this._sourceMesh.subMeshes) {
  11238. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11239. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11240. }
  11241. }
  11242. };
  11243. InstancedMesh.prototype._generatePointsArray = function () {
  11244. return this._sourceMesh._generatePointsArray();
  11245. };
  11246. // Clone
  11247. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11248. var result = this._sourceMesh.createInstance(name);
  11249. // Deep copy
  11250. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11251. // Bounding info
  11252. this.refreshBoundingInfo();
  11253. // Parent
  11254. if (newParent) {
  11255. result.parent = newParent;
  11256. }
  11257. if (!doNotCloneChildren) {
  11258. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11259. var mesh = this.getScene().meshes[index];
  11260. if (mesh.parent === this) {
  11261. mesh.clone(mesh.name, result);
  11262. }
  11263. }
  11264. }
  11265. result.computeWorldMatrix(true);
  11266. return result;
  11267. };
  11268. // Dispoe
  11269. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11270. // Remove from mesh
  11271. var index = this._sourceMesh.instances.indexOf(this);
  11272. this._sourceMesh.instances.splice(index, 1);
  11273. _super.prototype.dispose.call(this, doNotRecurse);
  11274. };
  11275. return InstancedMesh;
  11276. })(BABYLON.AbstractMesh);
  11277. BABYLON.InstancedMesh = InstancedMesh;
  11278. })(BABYLON || (BABYLON = {}));
  11279. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11280. (function (BABYLON) {
  11281. var SubMesh = (function () {
  11282. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11283. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11284. this.materialIndex = materialIndex;
  11285. this.verticesStart = verticesStart;
  11286. this.verticesCount = verticesCount;
  11287. this.indexStart = indexStart;
  11288. this.indexCount = indexCount;
  11289. this._renderId = 0;
  11290. this._mesh = mesh;
  11291. this._renderingMesh = renderingMesh || mesh;
  11292. mesh.subMeshes.push(this);
  11293. this._id = mesh.subMeshes.length - 1;
  11294. if (createBoundingBox) {
  11295. this.refreshBoundingInfo();
  11296. }
  11297. }
  11298. SubMesh.prototype.getBoundingInfo = function () {
  11299. return this._boundingInfo;
  11300. };
  11301. SubMesh.prototype.getMesh = function () {
  11302. return this._mesh;
  11303. };
  11304. SubMesh.prototype.getRenderingMesh = function () {
  11305. return this._renderingMesh;
  11306. };
  11307. SubMesh.prototype.getMaterial = function () {
  11308. var rootMaterial = this._renderingMesh.material;
  11309. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11310. var multiMaterial = rootMaterial;
  11311. return multiMaterial.getSubMaterial(this.materialIndex);
  11312. }
  11313. if (!rootMaterial) {
  11314. return this._mesh.getScene().defaultMaterial;
  11315. }
  11316. return rootMaterial;
  11317. };
  11318. // Methods
  11319. SubMesh.prototype.refreshBoundingInfo = function () {
  11320. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11321. if (!data) {
  11322. this._boundingInfo = this._mesh._boundingInfo;
  11323. return;
  11324. }
  11325. var indices = this._renderingMesh.getIndices();
  11326. var extend;
  11327. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11328. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11329. }
  11330. else {
  11331. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11332. }
  11333. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11334. };
  11335. SubMesh.prototype._checkCollision = function (collider) {
  11336. return this._boundingInfo._checkCollision(collider);
  11337. };
  11338. SubMesh.prototype.updateBoundingInfo = function (world) {
  11339. if (!this._boundingInfo) {
  11340. this.refreshBoundingInfo();
  11341. }
  11342. this._boundingInfo._update(world);
  11343. };
  11344. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11345. return this._boundingInfo.isInFrustum(frustumPlanes);
  11346. };
  11347. SubMesh.prototype.render = function () {
  11348. this._renderingMesh.render(this);
  11349. };
  11350. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11351. if (!this._linesIndexBuffer) {
  11352. var linesIndices = [];
  11353. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11354. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11355. }
  11356. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11357. this.linesIndexCount = linesIndices.length;
  11358. }
  11359. return this._linesIndexBuffer;
  11360. };
  11361. SubMesh.prototype.canIntersects = function (ray) {
  11362. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11363. };
  11364. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11365. var intersectInfo = null;
  11366. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11367. var p0 = positions[indices[index]];
  11368. var p1 = positions[indices[index + 1]];
  11369. var p2 = positions[indices[index + 2]];
  11370. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11371. if (currentIntersectInfo) {
  11372. if (currentIntersectInfo.distance < 0) {
  11373. continue;
  11374. }
  11375. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11376. intersectInfo = currentIntersectInfo;
  11377. intersectInfo.faceId = index / 3;
  11378. if (fastCheck) {
  11379. break;
  11380. }
  11381. }
  11382. }
  11383. }
  11384. return intersectInfo;
  11385. };
  11386. // Clone
  11387. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11388. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11389. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11390. return result;
  11391. };
  11392. // Dispose
  11393. SubMesh.prototype.dispose = function () {
  11394. if (this._linesIndexBuffer) {
  11395. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11396. this._linesIndexBuffer = null;
  11397. }
  11398. // Remove from mesh
  11399. var index = this._mesh.subMeshes.indexOf(this);
  11400. this._mesh.subMeshes.splice(index, 1);
  11401. };
  11402. // Statics
  11403. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11404. var minVertexIndex = Number.MAX_VALUE;
  11405. var maxVertexIndex = -Number.MAX_VALUE;
  11406. renderingMesh = renderingMesh || mesh;
  11407. var indices = renderingMesh.getIndices();
  11408. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11409. var vertexIndex = indices[index];
  11410. if (vertexIndex < minVertexIndex)
  11411. minVertexIndex = vertexIndex;
  11412. if (vertexIndex > maxVertexIndex)
  11413. maxVertexIndex = vertexIndex;
  11414. }
  11415. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11416. };
  11417. return SubMesh;
  11418. })();
  11419. BABYLON.SubMesh = SubMesh;
  11420. })(BABYLON || (BABYLON = {}));
  11421. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11422. (function (BABYLON) {
  11423. var BaseTexture = (function () {
  11424. function BaseTexture(scene) {
  11425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11426. this.hasAlpha = false;
  11427. this.getAlphaFromRGB = false;
  11428. this.level = 1;
  11429. this.isCube = false;
  11430. this.isRenderTarget = false;
  11431. this.animations = new Array();
  11432. this.coordinatesIndex = 0;
  11433. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11434. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11435. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11436. this.anisotropicFilteringLevel = 4;
  11437. this._scene = scene;
  11438. this._scene.textures.push(this);
  11439. }
  11440. BaseTexture.prototype.getScene = function () {
  11441. return this._scene;
  11442. };
  11443. BaseTexture.prototype.getTextureMatrix = function () {
  11444. return null;
  11445. };
  11446. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11447. return null;
  11448. };
  11449. BaseTexture.prototype.getInternalTexture = function () {
  11450. return this._texture;
  11451. };
  11452. BaseTexture.prototype.isReady = function () {
  11453. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11454. return true;
  11455. }
  11456. if (this._texture) {
  11457. return this._texture.isReady;
  11458. }
  11459. return false;
  11460. };
  11461. BaseTexture.prototype.getSize = function () {
  11462. if (this._texture._width) {
  11463. return { width: this._texture._width, height: this._texture._height };
  11464. }
  11465. if (this._texture._size) {
  11466. return { width: this._texture._size, height: this._texture._size };
  11467. }
  11468. return { width: 0, height: 0 };
  11469. };
  11470. BaseTexture.prototype.getBaseSize = function () {
  11471. if (!this.isReady())
  11472. return { width: 0, height: 0 };
  11473. if (this._texture._size) {
  11474. return { width: this._texture._size, height: this._texture._size };
  11475. }
  11476. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11477. };
  11478. BaseTexture.prototype.scale = function (ratio) {
  11479. };
  11480. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11481. get: function () {
  11482. return false;
  11483. },
  11484. enumerable: true,
  11485. configurable: true
  11486. });
  11487. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11488. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11489. for (var index = 0; index < texturesCache.length; index++) {
  11490. var texturesCacheEntry = texturesCache[index];
  11491. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11492. texturesCache.splice(index, 1);
  11493. return;
  11494. }
  11495. }
  11496. };
  11497. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11498. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11499. for (var index = 0; index < texturesCache.length; index++) {
  11500. var texturesCacheEntry = texturesCache[index];
  11501. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11502. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11503. texturesCacheEntry.references++;
  11504. return texturesCacheEntry;
  11505. }
  11506. }
  11507. }
  11508. return null;
  11509. };
  11510. BaseTexture.prototype.delayLoad = function () {
  11511. };
  11512. BaseTexture.prototype.releaseInternalTexture = function () {
  11513. if (!this._texture) {
  11514. return;
  11515. }
  11516. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11517. this._texture.references--;
  11518. // Final reference ?
  11519. if (this._texture.references === 0) {
  11520. var index = texturesCache.indexOf(this._texture);
  11521. texturesCache.splice(index, 1);
  11522. this._scene.getEngine()._releaseTexture(this._texture);
  11523. delete this._texture;
  11524. }
  11525. };
  11526. BaseTexture.prototype.clone = function () {
  11527. return null;
  11528. };
  11529. BaseTexture.prototype.dispose = function () {
  11530. // Remove from scene
  11531. var index = this._scene.textures.indexOf(this);
  11532. if (index >= 0) {
  11533. this._scene.textures.splice(index, 1);
  11534. }
  11535. if (this._texture === undefined) {
  11536. return;
  11537. }
  11538. this.releaseInternalTexture();
  11539. // Callback
  11540. if (this.onDispose) {
  11541. this.onDispose();
  11542. }
  11543. };
  11544. return BaseTexture;
  11545. })();
  11546. BABYLON.BaseTexture = BaseTexture;
  11547. })(BABYLON || (BABYLON = {}));
  11548. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11549. (function (BABYLON) {
  11550. var RenderingGroup = (function () {
  11551. function RenderingGroup(index, scene) {
  11552. this.index = index;
  11553. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11554. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11555. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11556. this._scene = scene;
  11557. }
  11558. RenderingGroup.prototype.render = function (customRenderFunction) {
  11559. if (customRenderFunction) {
  11560. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11561. return true;
  11562. }
  11563. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11564. return false;
  11565. }
  11566. var engine = this._scene.getEngine();
  11567. // Opaque
  11568. var subIndex;
  11569. var submesh;
  11570. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11571. submesh = this._opaqueSubMeshes.data[subIndex];
  11572. submesh.render();
  11573. }
  11574. // Alpha test
  11575. engine.setAlphaTesting(true);
  11576. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11577. submesh = this._alphaTestSubMeshes.data[subIndex];
  11578. submesh.render();
  11579. }
  11580. engine.setAlphaTesting(false);
  11581. // Transparent
  11582. if (this._transparentSubMeshes.length) {
  11583. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11584. submesh = this._transparentSubMeshes.data[subIndex];
  11585. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11586. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11587. }
  11588. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11589. sortedArray.sort(function (a, b) {
  11590. // Alpha index first
  11591. if (a._alphaIndex > b._alphaIndex) {
  11592. return 1;
  11593. }
  11594. if (a._alphaIndex < b._alphaIndex) {
  11595. return -1;
  11596. }
  11597. // Then distance to camera
  11598. if (a._distanceToCamera < b._distanceToCamera) {
  11599. return 1;
  11600. }
  11601. if (a._distanceToCamera > b._distanceToCamera) {
  11602. return -1;
  11603. }
  11604. return 0;
  11605. });
  11606. // Rendering
  11607. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11608. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11609. submesh = sortedArray[subIndex];
  11610. submesh.render();
  11611. }
  11612. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11613. }
  11614. return true;
  11615. };
  11616. RenderingGroup.prototype.prepare = function () {
  11617. this._opaqueSubMeshes.reset();
  11618. this._transparentSubMeshes.reset();
  11619. this._alphaTestSubMeshes.reset();
  11620. };
  11621. RenderingGroup.prototype.dispatch = function (subMesh) {
  11622. var material = subMesh.getMaterial();
  11623. var mesh = subMesh.getMesh();
  11624. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11625. this._transparentSubMeshes.push(subMesh);
  11626. }
  11627. else if (material.needAlphaTesting()) {
  11628. this._alphaTestSubMeshes.push(subMesh);
  11629. }
  11630. else {
  11631. this._opaqueSubMeshes.push(subMesh); // Opaque
  11632. }
  11633. };
  11634. return RenderingGroup;
  11635. })();
  11636. BABYLON.RenderingGroup = RenderingGroup;
  11637. })(BABYLON || (BABYLON = {}));
  11638. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11639. (function (BABYLON) {
  11640. var RenderingManager = (function () {
  11641. function RenderingManager(scene) {
  11642. this._renderingGroups = new Array();
  11643. this._scene = scene;
  11644. }
  11645. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11646. if (this._scene._activeParticleSystems.length === 0) {
  11647. return;
  11648. }
  11649. // Particles
  11650. var beforeParticlesDate = BABYLON.Tools.Now;
  11651. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11652. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11653. if (particleSystem.renderingGroupId !== index) {
  11654. continue;
  11655. }
  11656. this._clearDepthBuffer();
  11657. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11658. this._scene._activeParticles += particleSystem.render();
  11659. }
  11660. }
  11661. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11662. };
  11663. RenderingManager.prototype._renderSprites = function (index) {
  11664. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11665. return;
  11666. }
  11667. // Sprites
  11668. var beforeSpritessDate = BABYLON.Tools.Now;
  11669. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11670. var spriteManager = this._scene.spriteManagers[id];
  11671. if (spriteManager.renderingGroupId === index) {
  11672. this._clearDepthBuffer();
  11673. spriteManager.render();
  11674. }
  11675. }
  11676. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11677. };
  11678. RenderingManager.prototype._clearDepthBuffer = function () {
  11679. if (this._depthBufferAlreadyCleaned) {
  11680. return;
  11681. }
  11682. this._scene.getEngine().clear(0, false, true);
  11683. this._depthBufferAlreadyCleaned = true;
  11684. };
  11685. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11686. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11687. this._depthBufferAlreadyCleaned = false;
  11688. var renderingGroup = this._renderingGroups[index];
  11689. var needToStepBack = false;
  11690. if (renderingGroup) {
  11691. this._clearDepthBuffer();
  11692. if (!renderingGroup.render(customRenderFunction)) {
  11693. this._renderingGroups.splice(index, 1);
  11694. needToStepBack = true;
  11695. }
  11696. }
  11697. if (renderSprites) {
  11698. this._renderSprites(index);
  11699. }
  11700. if (renderParticles) {
  11701. this._renderParticles(index, activeMeshes);
  11702. }
  11703. if (needToStepBack) {
  11704. index--;
  11705. }
  11706. }
  11707. };
  11708. RenderingManager.prototype.reset = function () {
  11709. for (var index in this._renderingGroups) {
  11710. var renderingGroup = this._renderingGroups[index];
  11711. renderingGroup.prepare();
  11712. }
  11713. };
  11714. RenderingManager.prototype.dispatch = function (subMesh) {
  11715. var mesh = subMesh.getMesh();
  11716. var renderingGroupId = mesh.renderingGroupId || 0;
  11717. if (!this._renderingGroups[renderingGroupId]) {
  11718. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11719. }
  11720. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11721. };
  11722. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11723. return RenderingManager;
  11724. })();
  11725. BABYLON.RenderingManager = RenderingManager;
  11726. })(BABYLON || (BABYLON = {}));
  11727. //# sourceMappingURL=babylon.renderingManager.js.map
  11728. var BABYLON;
  11729. (function (BABYLON) {
  11730. var Texture = (function (_super) {
  11731. __extends(Texture, _super);
  11732. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11733. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11734. if (onLoad === void 0) { onLoad = null; }
  11735. if (onError === void 0) { onError = null; }
  11736. if (buffer === void 0) { buffer = null; }
  11737. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11738. _super.call(this, scene);
  11739. this.uOffset = 0;
  11740. this.vOffset = 0;
  11741. this.uScale = 1.0;
  11742. this.vScale = 1.0;
  11743. this.uAng = 0;
  11744. this.vAng = 0;
  11745. this.wAng = 0;
  11746. this.name = url;
  11747. this.url = url;
  11748. this._noMipmap = noMipmap;
  11749. this._invertY = invertY;
  11750. this._samplingMode = samplingMode;
  11751. this._buffer = buffer;
  11752. this._deleteBuffer = deleteBuffer;
  11753. if (!url) {
  11754. return;
  11755. }
  11756. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11757. if (!this._texture) {
  11758. if (!scene.useDelayedTextureLoading) {
  11759. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11760. if (deleteBuffer) {
  11761. delete this._buffer;
  11762. }
  11763. }
  11764. else {
  11765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11766. }
  11767. }
  11768. }
  11769. Texture.prototype.delayLoad = function () {
  11770. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11771. return;
  11772. }
  11773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11774. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11775. if (!this._texture) {
  11776. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11777. if (this._deleteBuffer) {
  11778. delete this._buffer;
  11779. }
  11780. }
  11781. };
  11782. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11783. x -= this.uOffset + 0.5;
  11784. y -= this.vOffset + 0.5;
  11785. z -= 0.5;
  11786. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11787. t.x *= this.uScale;
  11788. t.y *= this.vScale;
  11789. t.x += 0.5;
  11790. t.y += 0.5;
  11791. t.z += 0.5;
  11792. };
  11793. Texture.prototype.getTextureMatrix = function () {
  11794. 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) {
  11795. return this._cachedTextureMatrix;
  11796. }
  11797. this._cachedUOffset = this.uOffset;
  11798. this._cachedVOffset = this.vOffset;
  11799. this._cachedUScale = this.uScale;
  11800. this._cachedVScale = this.vScale;
  11801. this._cachedUAng = this.uAng;
  11802. this._cachedVAng = this.vAng;
  11803. this._cachedWAng = this.wAng;
  11804. if (!this._cachedTextureMatrix) {
  11805. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11806. this._rowGenerationMatrix = new BABYLON.Matrix();
  11807. this._t0 = BABYLON.Vector3.Zero();
  11808. this._t1 = BABYLON.Vector3.Zero();
  11809. this._t2 = BABYLON.Vector3.Zero();
  11810. }
  11811. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11812. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11813. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11814. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11815. this._t1.subtractInPlace(this._t0);
  11816. this._t2.subtractInPlace(this._t0);
  11817. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11818. this._cachedTextureMatrix.m[0] = this._t1.x;
  11819. this._cachedTextureMatrix.m[1] = this._t1.y;
  11820. this._cachedTextureMatrix.m[2] = this._t1.z;
  11821. this._cachedTextureMatrix.m[4] = this._t2.x;
  11822. this._cachedTextureMatrix.m[5] = this._t2.y;
  11823. this._cachedTextureMatrix.m[6] = this._t2.z;
  11824. this._cachedTextureMatrix.m[8] = this._t0.x;
  11825. this._cachedTextureMatrix.m[9] = this._t0.y;
  11826. this._cachedTextureMatrix.m[10] = this._t0.z;
  11827. return this._cachedTextureMatrix;
  11828. };
  11829. Texture.prototype.getReflectionTextureMatrix = function () {
  11830. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11831. return this._cachedTextureMatrix;
  11832. }
  11833. if (!this._cachedTextureMatrix) {
  11834. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11835. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11836. }
  11837. this._cachedCoordinatesMode = this.coordinatesMode;
  11838. switch (this.coordinatesMode) {
  11839. case BABYLON.Texture.SPHERICAL_MODE:
  11840. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11841. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11842. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11843. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11844. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11845. break;
  11846. case BABYLON.Texture.PLANAR_MODE:
  11847. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11848. this._cachedTextureMatrix[0] = this.uScale;
  11849. this._cachedTextureMatrix[5] = this.vScale;
  11850. this._cachedTextureMatrix[12] = this.uOffset;
  11851. this._cachedTextureMatrix[13] = this.vOffset;
  11852. break;
  11853. case BABYLON.Texture.PROJECTION_MODE:
  11854. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11855. this._projectionModeMatrix.m[0] = 0.5;
  11856. this._projectionModeMatrix.m[5] = -0.5;
  11857. this._projectionModeMatrix.m[10] = 0.0;
  11858. this._projectionModeMatrix.m[12] = 0.5;
  11859. this._projectionModeMatrix.m[13] = 0.5;
  11860. this._projectionModeMatrix.m[14] = 1.0;
  11861. this._projectionModeMatrix.m[15] = 1.0;
  11862. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11863. break;
  11864. default:
  11865. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11866. break;
  11867. }
  11868. return this._cachedTextureMatrix;
  11869. };
  11870. Texture.prototype.clone = function () {
  11871. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11872. // Base texture
  11873. newTexture.hasAlpha = this.hasAlpha;
  11874. newTexture.level = this.level;
  11875. newTexture.wrapU = this.wrapU;
  11876. newTexture.wrapV = this.wrapV;
  11877. newTexture.coordinatesIndex = this.coordinatesIndex;
  11878. newTexture.coordinatesMode = this.coordinatesMode;
  11879. // Texture
  11880. newTexture.uOffset = this.uOffset;
  11881. newTexture.vOffset = this.vOffset;
  11882. newTexture.uScale = this.uScale;
  11883. newTexture.vScale = this.vScale;
  11884. newTexture.uAng = this.uAng;
  11885. newTexture.vAng = this.vAng;
  11886. newTexture.wAng = this.wAng;
  11887. return newTexture;
  11888. };
  11889. // Statics
  11890. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11891. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11892. if (onLoad === void 0) { onLoad = null; }
  11893. if (onError === void 0) { onError = null; }
  11894. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11895. };
  11896. // Constants
  11897. Texture.NEAREST_SAMPLINGMODE = 1;
  11898. Texture.BILINEAR_SAMPLINGMODE = 2;
  11899. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11900. Texture.EXPLICIT_MODE = 0;
  11901. Texture.SPHERICAL_MODE = 1;
  11902. Texture.PLANAR_MODE = 2;
  11903. Texture.CUBIC_MODE = 3;
  11904. Texture.PROJECTION_MODE = 4;
  11905. Texture.SKYBOX_MODE = 5;
  11906. Texture.CLAMP_ADDRESSMODE = 0;
  11907. Texture.WRAP_ADDRESSMODE = 1;
  11908. Texture.MIRROR_ADDRESSMODE = 2;
  11909. return Texture;
  11910. })(BABYLON.BaseTexture);
  11911. BABYLON.Texture = Texture;
  11912. })(BABYLON || (BABYLON = {}));
  11913. //# sourceMappingURL=babylon.texture.js.map
  11914. var BABYLON;
  11915. (function (BABYLON) {
  11916. var CubeTexture = (function (_super) {
  11917. __extends(CubeTexture, _super);
  11918. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11919. _super.call(this, scene);
  11920. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11921. this.name = rootUrl;
  11922. this.url = rootUrl;
  11923. this._noMipmap = noMipmap;
  11924. this.hasAlpha = false;
  11925. this._texture = this._getFromCache(rootUrl, noMipmap);
  11926. if (!extensions) {
  11927. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11928. }
  11929. this._extensions = extensions;
  11930. if (!this._texture) {
  11931. if (!scene.useDelayedTextureLoading) {
  11932. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11933. }
  11934. else {
  11935. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11936. }
  11937. }
  11938. this.isCube = true;
  11939. this._textureMatrix = BABYLON.Matrix.Identity();
  11940. }
  11941. CubeTexture.prototype.clone = function () {
  11942. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11943. // Base texture
  11944. newTexture.level = this.level;
  11945. newTexture.wrapU = this.wrapU;
  11946. newTexture.wrapV = this.wrapV;
  11947. newTexture.coordinatesIndex = this.coordinatesIndex;
  11948. newTexture.coordinatesMode = this.coordinatesMode;
  11949. return newTexture;
  11950. };
  11951. // Methods
  11952. CubeTexture.prototype.delayLoad = function () {
  11953. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11954. return;
  11955. }
  11956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11957. this._texture = this._getFromCache(this.url, this._noMipmap);
  11958. if (!this._texture) {
  11959. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11960. }
  11961. };
  11962. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11963. return this._textureMatrix;
  11964. };
  11965. return CubeTexture;
  11966. })(BABYLON.BaseTexture);
  11967. BABYLON.CubeTexture = CubeTexture;
  11968. })(BABYLON || (BABYLON = {}));
  11969. //# sourceMappingURL=babylon.cubeTexture.js.map
  11970. var BABYLON;
  11971. (function (BABYLON) {
  11972. var RenderTargetTexture = (function (_super) {
  11973. __extends(RenderTargetTexture, _super);
  11974. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11975. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11976. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11977. _super.call(this, null, scene, !generateMipMaps);
  11978. this.renderList = new Array();
  11979. this.renderParticles = true;
  11980. this.renderSprites = false;
  11981. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11982. this._currentRefreshId = -1;
  11983. this._refreshRate = 1;
  11984. this.name = name;
  11985. this.isRenderTarget = true;
  11986. this._size = size;
  11987. this._generateMipMaps = generateMipMaps;
  11988. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11989. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11990. // Rendering groups
  11991. this._renderingManager = new BABYLON.RenderingManager(scene);
  11992. }
  11993. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11994. this._currentRefreshId = -1;
  11995. };
  11996. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11997. get: function () {
  11998. return this._refreshRate;
  11999. },
  12000. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12001. set: function (value) {
  12002. this._refreshRate = value;
  12003. this.resetRefreshCounter();
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. RenderTargetTexture.prototype._shouldRender = function () {
  12009. if (this._currentRefreshId === -1) {
  12010. this._currentRefreshId = 1;
  12011. return true;
  12012. }
  12013. if (this.refreshRate === this._currentRefreshId) {
  12014. this._currentRefreshId = 1;
  12015. return true;
  12016. }
  12017. this._currentRefreshId++;
  12018. return false;
  12019. };
  12020. RenderTargetTexture.prototype.isReady = function () {
  12021. if (!this.getScene().renderTargetsEnabled) {
  12022. return false;
  12023. }
  12024. return _super.prototype.isReady.call(this);
  12025. };
  12026. RenderTargetTexture.prototype.getRenderSize = function () {
  12027. return this._size;
  12028. };
  12029. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12030. get: function () {
  12031. return true;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. RenderTargetTexture.prototype.scale = function (ratio) {
  12037. var newSize = this._size * ratio;
  12038. this.resize(newSize, this._generateMipMaps);
  12039. };
  12040. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12041. this.releaseInternalTexture();
  12042. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12043. };
  12044. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  12045. var scene = this.getScene();
  12046. var engine = scene.getEngine();
  12047. if (this._waitingRenderList) {
  12048. this.renderList = [];
  12049. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12050. var id = this._waitingRenderList[index];
  12051. this.renderList.push(scene.getMeshByID(id));
  12052. }
  12053. delete this._waitingRenderList;
  12054. }
  12055. if (this.renderList && this.renderList.length === 0) {
  12056. return;
  12057. }
  12058. // Bind
  12059. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12060. engine.bindFramebuffer(this._texture);
  12061. }
  12062. this._renderingManager.reset();
  12063. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12064. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12065. var mesh = currentRenderList[meshIndex];
  12066. if (mesh) {
  12067. if (!mesh.isReady()) {
  12068. // Reset _currentRefreshId
  12069. this.resetRefreshCounter();
  12070. continue;
  12071. }
  12072. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12073. mesh._activate(scene.getRenderId());
  12074. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12075. var subMesh = mesh.subMeshes[subIndex];
  12076. scene._activeVertices += subMesh.indexCount;
  12077. this._renderingManager.dispatch(subMesh);
  12078. }
  12079. }
  12080. }
  12081. }
  12082. if (this.onBeforeRender) {
  12083. this.onBeforeRender();
  12084. }
  12085. // Clear
  12086. engine.clear(scene.clearColor, true, true);
  12087. if (!this._doNotChangeAspectRatio) {
  12088. scene.updateTransformMatrix(true);
  12089. }
  12090. // Render
  12091. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12092. if (useCameraPostProcess) {
  12093. scene.postProcessManager._finalizeFrame(false, this._texture);
  12094. }
  12095. if (!this._doNotChangeAspectRatio) {
  12096. scene.updateTransformMatrix(true);
  12097. }
  12098. if (this.onAfterRender) {
  12099. this.onAfterRender();
  12100. }
  12101. // Unbind
  12102. engine.unBindFramebuffer(this._texture);
  12103. };
  12104. RenderTargetTexture.prototype.clone = function () {
  12105. var textureSize = this.getSize();
  12106. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12107. // Base texture
  12108. newTexture.hasAlpha = this.hasAlpha;
  12109. newTexture.level = this.level;
  12110. // RenderTarget Texture
  12111. newTexture.coordinatesMode = this.coordinatesMode;
  12112. newTexture.renderList = this.renderList.slice(0);
  12113. return newTexture;
  12114. };
  12115. return RenderTargetTexture;
  12116. })(BABYLON.Texture);
  12117. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12118. })(BABYLON || (BABYLON = {}));
  12119. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12120. var BABYLON;
  12121. (function (BABYLON) {
  12122. var ProceduralTexture = (function (_super) {
  12123. __extends(ProceduralTexture, _super);
  12124. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12125. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12126. _super.call(this, null, scene, !generateMipMaps);
  12127. this._currentRefreshId = -1;
  12128. this._refreshRate = 1;
  12129. this._vertexDeclaration = [2];
  12130. this._vertexStrideSize = 2 * 4;
  12131. this._uniforms = new Array();
  12132. this._samplers = new Array();
  12133. this._textures = new Array();
  12134. this._floats = new Array();
  12135. this._floatsArrays = {};
  12136. this._colors3 = new Array();
  12137. this._colors4 = new Array();
  12138. this._vectors2 = new Array();
  12139. this._vectors3 = new Array();
  12140. this._matrices = new Array();
  12141. this._fallbackTextureUsed = false;
  12142. scene._proceduralTextures.push(this);
  12143. this.name = name;
  12144. this.isRenderTarget = true;
  12145. this._size = size;
  12146. this._generateMipMaps = generateMipMaps;
  12147. this.setFragment(fragment);
  12148. this._fallbackTexture = fallbackTexture;
  12149. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12150. // VBO
  12151. var vertices = [];
  12152. vertices.push(1, 1);
  12153. vertices.push(-1, 1);
  12154. vertices.push(-1, -1);
  12155. vertices.push(1, -1);
  12156. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12157. // Indices
  12158. var indices = [];
  12159. indices.push(0);
  12160. indices.push(1);
  12161. indices.push(2);
  12162. indices.push(0);
  12163. indices.push(2);
  12164. indices.push(3);
  12165. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12166. }
  12167. ProceduralTexture.prototype.reset = function () {
  12168. if (this._effect === undefined) {
  12169. return;
  12170. }
  12171. var engine = this.getScene().getEngine();
  12172. engine._releaseEffect(this._effect);
  12173. };
  12174. ProceduralTexture.prototype.isReady = function () {
  12175. var _this = this;
  12176. var engine = this.getScene().getEngine();
  12177. var shaders;
  12178. if (!this._fragment) {
  12179. return false;
  12180. }
  12181. if (this._fallbackTextureUsed) {
  12182. return true;
  12183. }
  12184. if (this._fragment.fragmentElement !== undefined) {
  12185. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12186. }
  12187. else {
  12188. shaders = { vertex: "procedural", fragment: this._fragment };
  12189. }
  12190. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12191. _this.releaseInternalTexture();
  12192. if (_this._fallbackTexture) {
  12193. _this._texture = _this._fallbackTexture._texture;
  12194. _this._texture.references++;
  12195. }
  12196. _this._fallbackTextureUsed = true;
  12197. });
  12198. return this._effect.isReady();
  12199. };
  12200. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12201. this._currentRefreshId = -1;
  12202. };
  12203. ProceduralTexture.prototype.setFragment = function (fragment) {
  12204. this._fragment = fragment;
  12205. };
  12206. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12207. get: function () {
  12208. return this._refreshRate;
  12209. },
  12210. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12211. set: function (value) {
  12212. this._refreshRate = value;
  12213. this.resetRefreshCounter();
  12214. },
  12215. enumerable: true,
  12216. configurable: true
  12217. });
  12218. ProceduralTexture.prototype._shouldRender = function () {
  12219. if (!this.isReady() || !this._texture) {
  12220. return false;
  12221. }
  12222. if (this._fallbackTextureUsed) {
  12223. return false;
  12224. }
  12225. if (this._currentRefreshId === -1) {
  12226. this._currentRefreshId = 1;
  12227. return true;
  12228. }
  12229. if (this.refreshRate === this._currentRefreshId) {
  12230. this._currentRefreshId = 1;
  12231. return true;
  12232. }
  12233. this._currentRefreshId++;
  12234. return false;
  12235. };
  12236. ProceduralTexture.prototype.getRenderSize = function () {
  12237. return this._size;
  12238. };
  12239. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12240. if (this._fallbackTextureUsed) {
  12241. return;
  12242. }
  12243. this.releaseInternalTexture();
  12244. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12245. };
  12246. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12247. if (this._uniforms.indexOf(uniformName) === -1) {
  12248. this._uniforms.push(uniformName);
  12249. }
  12250. };
  12251. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12252. if (this._samplers.indexOf(name) === -1) {
  12253. this._samplers.push(name);
  12254. }
  12255. this._textures[name] = texture;
  12256. return this;
  12257. };
  12258. ProceduralTexture.prototype.setFloat = function (name, value) {
  12259. this._checkUniform(name);
  12260. this._floats[name] = value;
  12261. return this;
  12262. };
  12263. ProceduralTexture.prototype.setFloats = function (name, value) {
  12264. this._checkUniform(name);
  12265. this._floatsArrays[name] = value;
  12266. return this;
  12267. };
  12268. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12269. this._checkUniform(name);
  12270. this._colors3[name] = value;
  12271. return this;
  12272. };
  12273. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12274. this._checkUniform(name);
  12275. this._colors4[name] = value;
  12276. return this;
  12277. };
  12278. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12279. this._checkUniform(name);
  12280. this._vectors2[name] = value;
  12281. return this;
  12282. };
  12283. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12284. this._checkUniform(name);
  12285. this._vectors3[name] = value;
  12286. return this;
  12287. };
  12288. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12289. this._checkUniform(name);
  12290. this._matrices[name] = value;
  12291. return this;
  12292. };
  12293. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12294. var scene = this.getScene();
  12295. var engine = scene.getEngine();
  12296. engine.bindFramebuffer(this._texture);
  12297. // Clear
  12298. engine.clear(scene.clearColor, true, true);
  12299. // Render
  12300. engine.enableEffect(this._effect);
  12301. engine.setState(false);
  12302. for (var name in this._textures) {
  12303. this._effect.setTexture(name, this._textures[name]);
  12304. }
  12305. for (name in this._floats) {
  12306. this._effect.setFloat(name, this._floats[name]);
  12307. }
  12308. for (name in this._floatsArrays) {
  12309. this._effect.setArray(name, this._floatsArrays[name]);
  12310. }
  12311. for (name in this._colors3) {
  12312. this._effect.setColor3(name, this._colors3[name]);
  12313. }
  12314. for (name in this._colors4) {
  12315. var color = this._colors4[name];
  12316. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12317. }
  12318. for (name in this._vectors2) {
  12319. this._effect.setVector2(name, this._vectors2[name]);
  12320. }
  12321. for (name in this._vectors3) {
  12322. this._effect.setVector3(name, this._vectors3[name]);
  12323. }
  12324. for (name in this._matrices) {
  12325. this._effect.setMatrix(name, this._matrices[name]);
  12326. }
  12327. // VBOs
  12328. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12329. // Draw order
  12330. engine.draw(true, 0, 6);
  12331. // Unbind
  12332. engine.unBindFramebuffer(this._texture);
  12333. };
  12334. ProceduralTexture.prototype.clone = function () {
  12335. var textureSize = this.getSize();
  12336. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12337. // Base texture
  12338. newTexture.hasAlpha = this.hasAlpha;
  12339. newTexture.level = this.level;
  12340. // RenderTarget Texture
  12341. newTexture.coordinatesMode = this.coordinatesMode;
  12342. return newTexture;
  12343. };
  12344. ProceduralTexture.prototype.dispose = function () {
  12345. var index = this.getScene()._proceduralTextures.indexOf(this);
  12346. if (index >= 0) {
  12347. this.getScene()._proceduralTextures.splice(index, 1);
  12348. }
  12349. _super.prototype.dispose.call(this);
  12350. };
  12351. return ProceduralTexture;
  12352. })(BABYLON.Texture);
  12353. BABYLON.ProceduralTexture = ProceduralTexture;
  12354. })(BABYLON || (BABYLON = {}));
  12355. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12356. var BABYLON;
  12357. (function (BABYLON) {
  12358. var WoodProceduralTexture = (function (_super) {
  12359. __extends(WoodProceduralTexture, _super);
  12360. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12361. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12362. this._ampScale = 100.0;
  12363. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12364. this.updateShaderUniforms();
  12365. this.refreshRate = 0;
  12366. }
  12367. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12368. this.setFloat("ampScale", this._ampScale);
  12369. this.setColor3("woodColor", this._woodColor);
  12370. };
  12371. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12372. get: function () {
  12373. return this._ampScale;
  12374. },
  12375. set: function (value) {
  12376. this._ampScale = value;
  12377. this.updateShaderUniforms();
  12378. },
  12379. enumerable: true,
  12380. configurable: true
  12381. });
  12382. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12383. get: function () {
  12384. return this._woodColor;
  12385. },
  12386. set: function (value) {
  12387. this._woodColor = value;
  12388. this.updateShaderUniforms();
  12389. },
  12390. enumerable: true,
  12391. configurable: true
  12392. });
  12393. return WoodProceduralTexture;
  12394. })(BABYLON.ProceduralTexture);
  12395. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12396. var FireProceduralTexture = (function (_super) {
  12397. __extends(FireProceduralTexture, _super);
  12398. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12399. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12400. this._time = 0.0;
  12401. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12402. this._shift = 1.6;
  12403. this._autoGenerateTime = true;
  12404. this._alphaThreshold = 0.5;
  12405. this._fireColors = FireProceduralTexture.RedFireColors;
  12406. this.updateShaderUniforms();
  12407. this.refreshRate = 1;
  12408. }
  12409. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12410. this.setFloat("time", this._time);
  12411. this.setVector2("speed", this._speed);
  12412. this.setFloat("shift", this._shift);
  12413. this.setColor3("c1", this._fireColors[0]);
  12414. this.setColor3("c2", this._fireColors[1]);
  12415. this.setColor3("c3", this._fireColors[2]);
  12416. this.setColor3("c4", this._fireColors[3]);
  12417. this.setColor3("c5", this._fireColors[4]);
  12418. this.setColor3("c6", this._fireColors[5]);
  12419. this.setFloat("alphaThreshold", this._alphaThreshold);
  12420. };
  12421. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12422. if (this._autoGenerateTime) {
  12423. this._time += this.getScene().getAnimationRatio() * 0.03;
  12424. this.updateShaderUniforms();
  12425. }
  12426. _super.prototype.render.call(this, useCameraPostProcess);
  12427. };
  12428. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12429. get: function () {
  12430. return [
  12431. new BABYLON.Color3(0.5, 0.0, 1.0),
  12432. new BABYLON.Color3(0.9, 0.0, 1.0),
  12433. new BABYLON.Color3(0.2, 0.0, 1.0),
  12434. new BABYLON.Color3(1.0, 0.9, 1.0),
  12435. new BABYLON.Color3(0.1, 0.1, 1.0),
  12436. new BABYLON.Color3(0.9, 0.9, 1.0)
  12437. ];
  12438. },
  12439. enumerable: true,
  12440. configurable: true
  12441. });
  12442. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12443. get: function () {
  12444. return [
  12445. new BABYLON.Color3(0.5, 1.0, 0.0),
  12446. new BABYLON.Color3(0.5, 1.0, 0.0),
  12447. new BABYLON.Color3(0.3, 0.4, 0.0),
  12448. new BABYLON.Color3(0.5, 1.0, 0.0),
  12449. new BABYLON.Color3(0.2, 0.0, 0.0),
  12450. new BABYLON.Color3(0.5, 1.0, 0.0)
  12451. ];
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12457. get: function () {
  12458. return [
  12459. new BABYLON.Color3(0.5, 0.0, 0.1),
  12460. new BABYLON.Color3(0.9, 0.0, 0.0),
  12461. new BABYLON.Color3(0.2, 0.0, 0.0),
  12462. new BABYLON.Color3(1.0, 0.9, 0.0),
  12463. new BABYLON.Color3(0.1, 0.1, 0.1),
  12464. new BABYLON.Color3(0.9, 0.9, 0.9)
  12465. ];
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12471. get: function () {
  12472. return [
  12473. new BABYLON.Color3(0.1, 0.0, 0.5),
  12474. new BABYLON.Color3(0.0, 0.0, 0.5),
  12475. new BABYLON.Color3(0.1, 0.0, 0.2),
  12476. new BABYLON.Color3(0.0, 0.0, 1.0),
  12477. new BABYLON.Color3(0.1, 0.2, 0.3),
  12478. new BABYLON.Color3(0.0, 0.2, 0.9)
  12479. ];
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12485. get: function () {
  12486. return this._fireColors;
  12487. },
  12488. set: function (value) {
  12489. this._fireColors = value;
  12490. this.updateShaderUniforms();
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12496. get: function () {
  12497. return this._time;
  12498. },
  12499. set: function (value) {
  12500. this._time = value;
  12501. this.updateShaderUniforms();
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12507. get: function () {
  12508. return this._speed;
  12509. },
  12510. set: function (value) {
  12511. this._speed = value;
  12512. this.updateShaderUniforms();
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12518. get: function () {
  12519. return this._shift;
  12520. },
  12521. set: function (value) {
  12522. this._shift = value;
  12523. this.updateShaderUniforms();
  12524. },
  12525. enumerable: true,
  12526. configurable: true
  12527. });
  12528. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12529. get: function () {
  12530. return this._alphaThreshold;
  12531. },
  12532. set: function (value) {
  12533. this._alphaThreshold = value;
  12534. this.updateShaderUniforms();
  12535. },
  12536. enumerable: true,
  12537. configurable: true
  12538. });
  12539. return FireProceduralTexture;
  12540. })(BABYLON.ProceduralTexture);
  12541. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12542. var CloudProceduralTexture = (function (_super) {
  12543. __extends(CloudProceduralTexture, _super);
  12544. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12545. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12546. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12547. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12548. this.updateShaderUniforms();
  12549. this.refreshRate = 0;
  12550. }
  12551. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12552. this.setColor3("skyColor", this._skyColor);
  12553. this.setColor3("cloudColor", this._cloudColor);
  12554. };
  12555. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12556. get: function () {
  12557. return this._skyColor;
  12558. },
  12559. set: function (value) {
  12560. this._skyColor = value;
  12561. this.updateShaderUniforms();
  12562. },
  12563. enumerable: true,
  12564. configurable: true
  12565. });
  12566. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12567. get: function () {
  12568. return this._cloudColor;
  12569. },
  12570. set: function (value) {
  12571. this._cloudColor = value;
  12572. this.updateShaderUniforms();
  12573. },
  12574. enumerable: true,
  12575. configurable: true
  12576. });
  12577. return CloudProceduralTexture;
  12578. })(BABYLON.ProceduralTexture);
  12579. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12580. var GrassProceduralTexture = (function (_super) {
  12581. __extends(GrassProceduralTexture, _super);
  12582. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12583. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12584. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12585. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12586. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12587. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12588. this._grassColors = [
  12589. new BABYLON.Color3(0.29, 0.38, 0.02),
  12590. new BABYLON.Color3(0.36, 0.49, 0.09),
  12591. new BABYLON.Color3(0.51, 0.6, 0.28)
  12592. ];
  12593. this.updateShaderUniforms();
  12594. this.refreshRate = 0;
  12595. }
  12596. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12597. this.setColor3("herb1Color", this._grassColors[0]);
  12598. this.setColor3("herb2Color", this._grassColors[1]);
  12599. this.setColor3("herb3Color", this._grassColors[2]);
  12600. this.setColor3("groundColor", this._groundColor);
  12601. };
  12602. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12603. get: function () {
  12604. return this._grassColors;
  12605. },
  12606. set: function (value) {
  12607. this._grassColors = value;
  12608. this.updateShaderUniforms();
  12609. },
  12610. enumerable: true,
  12611. configurable: true
  12612. });
  12613. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12614. get: function () {
  12615. return this._groundColor;
  12616. },
  12617. set: function (value) {
  12618. this.groundColor = value;
  12619. this.updateShaderUniforms();
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. return GrassProceduralTexture;
  12625. })(BABYLON.ProceduralTexture);
  12626. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12627. var RoadProceduralTexture = (function (_super) {
  12628. __extends(RoadProceduralTexture, _super);
  12629. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12630. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12631. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12632. this.updateShaderUniforms();
  12633. this.refreshRate = 0;
  12634. }
  12635. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12636. this.setColor3("roadColor", this._roadColor);
  12637. };
  12638. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12639. get: function () {
  12640. return this._roadColor;
  12641. },
  12642. set: function (value) {
  12643. this._roadColor = value;
  12644. this.updateShaderUniforms();
  12645. },
  12646. enumerable: true,
  12647. configurable: true
  12648. });
  12649. return RoadProceduralTexture;
  12650. })(BABYLON.ProceduralTexture);
  12651. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12652. var BrickProceduralTexture = (function (_super) {
  12653. __extends(BrickProceduralTexture, _super);
  12654. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12655. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12656. this._numberOfBricksHeight = 15;
  12657. this._numberOfBricksWidth = 5;
  12658. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12659. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12660. this.updateShaderUniforms();
  12661. this.refreshRate = 0;
  12662. }
  12663. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12664. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12665. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12666. this.setColor3("brickColor", this._brickColor);
  12667. this.setColor3("jointColor", this._jointColor);
  12668. };
  12669. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12670. get: function () {
  12671. return this._numberOfBricksHeight;
  12672. },
  12673. enumerable: true,
  12674. configurable: true
  12675. });
  12676. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12677. set: function (value) {
  12678. this._numberOfBricksHeight = value;
  12679. this.updateShaderUniforms();
  12680. },
  12681. enumerable: true,
  12682. configurable: true
  12683. });
  12684. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12685. get: function () {
  12686. return this._numberOfBricksWidth;
  12687. },
  12688. set: function (value) {
  12689. this._numberOfBricksHeight = value;
  12690. this.updateShaderUniforms();
  12691. },
  12692. enumerable: true,
  12693. configurable: true
  12694. });
  12695. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12696. get: function () {
  12697. return this._jointColor;
  12698. },
  12699. set: function (value) {
  12700. this._jointColor = value;
  12701. this.updateShaderUniforms();
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12707. get: function () {
  12708. return this._brickColor;
  12709. },
  12710. set: function (value) {
  12711. this._brickColor = value;
  12712. this.updateShaderUniforms();
  12713. },
  12714. enumerable: true,
  12715. configurable: true
  12716. });
  12717. return BrickProceduralTexture;
  12718. })(BABYLON.ProceduralTexture);
  12719. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12720. var MarbleProceduralTexture = (function (_super) {
  12721. __extends(MarbleProceduralTexture, _super);
  12722. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12723. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12724. this._numberOfTilesHeight = 3;
  12725. this._numberOfTilesWidth = 3;
  12726. this._amplitude = 9.0;
  12727. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12728. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12729. this.updateShaderUniforms();
  12730. this.refreshRate = 0;
  12731. }
  12732. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12733. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12734. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12735. this.setFloat("amplitude", this._amplitude);
  12736. this.setColor3("marbleColor", this._marbleColor);
  12737. this.setColor3("jointColor", this._jointColor);
  12738. };
  12739. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12740. get: function () {
  12741. return this._numberOfTilesHeight;
  12742. },
  12743. set: function (value) {
  12744. this._numberOfTilesHeight = value;
  12745. this.updateShaderUniforms();
  12746. },
  12747. enumerable: true,
  12748. configurable: true
  12749. });
  12750. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12751. get: function () {
  12752. return this._numberOfTilesWidth;
  12753. },
  12754. set: function (value) {
  12755. this._numberOfTilesWidth = value;
  12756. this.updateShaderUniforms();
  12757. },
  12758. enumerable: true,
  12759. configurable: true
  12760. });
  12761. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12762. get: function () {
  12763. return this._jointColor;
  12764. },
  12765. set: function (value) {
  12766. this._jointColor = value;
  12767. this.updateShaderUniforms();
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12773. get: function () {
  12774. return this._marbleColor;
  12775. },
  12776. set: function (value) {
  12777. this._marbleColor = value;
  12778. this.updateShaderUniforms();
  12779. },
  12780. enumerable: true,
  12781. configurable: true
  12782. });
  12783. return MarbleProceduralTexture;
  12784. })(BABYLON.ProceduralTexture);
  12785. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12786. })(BABYLON || (BABYLON = {}));
  12787. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12788. var BABYLON;
  12789. (function (BABYLON) {
  12790. var CustomProceduralTexture = (function (_super) {
  12791. __extends(CustomProceduralTexture, _super);
  12792. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12793. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12794. this._animate = true;
  12795. this._time = 0;
  12796. this._texturePath = texturePath;
  12797. //Try to load json
  12798. this.loadJson(texturePath);
  12799. this.refreshRate = 1;
  12800. }
  12801. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12802. var _this = this;
  12803. var that = this;
  12804. function noConfigFile() {
  12805. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  12806. try {
  12807. that.setFragment(that._texturePath);
  12808. }
  12809. catch (ex) {
  12810. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12811. }
  12812. }
  12813. var configFileUrl = jsonUrl + "/config.json";
  12814. var xhr = new XMLHttpRequest();
  12815. xhr.open("GET", configFileUrl, true);
  12816. xhr.addEventListener("load", function () {
  12817. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12818. try {
  12819. _this._config = JSON.parse(xhr.response);
  12820. _this.updateShaderUniforms();
  12821. _this.updateTextures();
  12822. _this.setFragment(_this._texturePath + "/custom");
  12823. _this._animate = _this._config.animate;
  12824. _this.refreshRate = _this._config.refreshrate;
  12825. }
  12826. catch (ex) {
  12827. noConfigFile();
  12828. }
  12829. }
  12830. else {
  12831. noConfigFile();
  12832. }
  12833. }, false);
  12834. xhr.addEventListener("error", function () {
  12835. noConfigFile();
  12836. }, false);
  12837. try {
  12838. xhr.send();
  12839. }
  12840. catch (ex) {
  12841. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12842. }
  12843. };
  12844. CustomProceduralTexture.prototype.isReady = function () {
  12845. if (!_super.prototype.isReady.call(this)) {
  12846. return false;
  12847. }
  12848. for (var name in this._textures) {
  12849. var texture = this._textures[name];
  12850. if (!texture.isReady()) {
  12851. return false;
  12852. }
  12853. }
  12854. return true;
  12855. };
  12856. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12857. if (this._animate) {
  12858. this._time += this.getScene().getAnimationRatio() * 0.03;
  12859. this.updateShaderUniforms();
  12860. }
  12861. _super.prototype.render.call(this, useCameraPostProcess);
  12862. };
  12863. CustomProceduralTexture.prototype.updateTextures = function () {
  12864. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12865. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12866. }
  12867. };
  12868. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12869. if (this._config) {
  12870. for (var j = 0; j < this._config.uniforms.length; j++) {
  12871. var uniform = this._config.uniforms[j];
  12872. switch (uniform.type) {
  12873. case "float":
  12874. this.setFloat(uniform.name, uniform.value);
  12875. break;
  12876. case "color3":
  12877. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12878. break;
  12879. case "color4":
  12880. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12881. break;
  12882. case "vector2":
  12883. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12884. break;
  12885. case "vector3":
  12886. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12887. break;
  12888. }
  12889. }
  12890. }
  12891. this.setFloat("time", this._time);
  12892. };
  12893. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12894. get: function () {
  12895. return this._animate;
  12896. },
  12897. set: function (value) {
  12898. this._animate = value;
  12899. },
  12900. enumerable: true,
  12901. configurable: true
  12902. });
  12903. return CustomProceduralTexture;
  12904. })(BABYLON.ProceduralTexture);
  12905. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12906. })(BABYLON || (BABYLON = {}));
  12907. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12908. var BABYLON;
  12909. (function (BABYLON) {
  12910. var MirrorTexture = (function (_super) {
  12911. __extends(MirrorTexture, _super);
  12912. function MirrorTexture(name, size, scene, generateMipMaps) {
  12913. var _this = this;
  12914. _super.call(this, name, size, scene, generateMipMaps, true);
  12915. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12916. this._transformMatrix = BABYLON.Matrix.Zero();
  12917. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12918. this.onBeforeRender = function () {
  12919. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12920. _this._savedViewMatrix = scene.getViewMatrix();
  12921. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12922. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12923. scene.clipPlane = _this.mirrorPlane;
  12924. scene.getEngine().cullBackFaces = false;
  12925. };
  12926. this.onAfterRender = function () {
  12927. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12928. scene.getEngine().cullBackFaces = true;
  12929. delete scene.clipPlane;
  12930. };
  12931. }
  12932. MirrorTexture.prototype.clone = function () {
  12933. var textureSize = this.getSize();
  12934. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12935. // Base texture
  12936. newTexture.hasAlpha = this.hasAlpha;
  12937. newTexture.level = this.level;
  12938. // Mirror Texture
  12939. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12940. newTexture.renderList = this.renderList.slice(0);
  12941. return newTexture;
  12942. };
  12943. return MirrorTexture;
  12944. })(BABYLON.RenderTargetTexture);
  12945. BABYLON.MirrorTexture = MirrorTexture;
  12946. })(BABYLON || (BABYLON = {}));
  12947. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12948. var BABYLON;
  12949. (function (BABYLON) {
  12950. var DynamicTexture = (function (_super) {
  12951. __extends(DynamicTexture, _super);
  12952. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12954. _super.call(this, null, scene, !generateMipMaps);
  12955. this.name = name;
  12956. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12957. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12958. this._generateMipMaps = generateMipMaps;
  12959. if (options.getContext) {
  12960. this._canvas = options;
  12961. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12962. }
  12963. else {
  12964. this._canvas = document.createElement("canvas");
  12965. if (options.width) {
  12966. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12967. }
  12968. else {
  12969. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12970. }
  12971. }
  12972. var textureSize = this.getSize();
  12973. this._canvas.width = textureSize.width;
  12974. this._canvas.height = textureSize.height;
  12975. this._context = this._canvas.getContext("2d");
  12976. }
  12977. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12978. get: function () {
  12979. return true;
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. DynamicTexture.prototype.scale = function (ratio) {
  12985. var textureSize = this.getSize();
  12986. textureSize.width *= ratio;
  12987. textureSize.height *= ratio;
  12988. this._canvas.width = textureSize.width;
  12989. this._canvas.height = textureSize.height;
  12990. this.releaseInternalTexture();
  12991. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12992. };
  12993. DynamicTexture.prototype.getContext = function () {
  12994. return this._context;
  12995. };
  12996. DynamicTexture.prototype.clear = function () {
  12997. var size = this.getSize();
  12998. this._context.fillRect(0, 0, size.width, size.height);
  12999. };
  13000. DynamicTexture.prototype.update = function (invertY) {
  13001. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13002. };
  13003. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13004. if (update === void 0) { update = true; }
  13005. var size = this.getSize();
  13006. if (clearColor) {
  13007. this._context.fillStyle = clearColor;
  13008. this._context.fillRect(0, 0, size.width, size.height);
  13009. }
  13010. this._context.font = font;
  13011. if (x === null) {
  13012. var textSize = this._context.measureText(text);
  13013. x = (size.width - textSize.width) / 2;
  13014. }
  13015. this._context.fillStyle = color;
  13016. this._context.fillText(text, x, y);
  13017. if (update) {
  13018. this.update(invertY);
  13019. }
  13020. };
  13021. DynamicTexture.prototype.clone = function () {
  13022. var textureSize = this.getSize();
  13023. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13024. // Base texture
  13025. newTexture.hasAlpha = this.hasAlpha;
  13026. newTexture.level = this.level;
  13027. // Dynamic Texture
  13028. newTexture.wrapU = this.wrapU;
  13029. newTexture.wrapV = this.wrapV;
  13030. return newTexture;
  13031. };
  13032. return DynamicTexture;
  13033. })(BABYLON.Texture);
  13034. BABYLON.DynamicTexture = DynamicTexture;
  13035. })(BABYLON || (BABYLON = {}));
  13036. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13037. var BABYLON;
  13038. (function (BABYLON) {
  13039. var VideoTexture = (function (_super) {
  13040. __extends(VideoTexture, _super);
  13041. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13042. var _this = this;
  13043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13044. _super.call(this, null, scene, !generateMipMaps, invertY);
  13045. this._autoLaunch = true;
  13046. this.name = name;
  13047. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13048. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13049. var requiredWidth = size.width || size;
  13050. var requiredHeight = size.height || size;
  13051. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13052. var textureSize = this.getSize();
  13053. this.video = document.createElement("video");
  13054. this.video.width = textureSize.width;
  13055. this.video.height = textureSize.height;
  13056. this.video.autoplay = false;
  13057. this.video.loop = true;
  13058. this.video.addEventListener("canplaythrough", function () {
  13059. if (_this._texture) {
  13060. _this._texture.isReady = true;
  13061. }
  13062. });
  13063. urls.forEach(function (url) {
  13064. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13065. var source = document.createElement("source");
  13066. source.src = url;
  13067. _this.video.appendChild(source);
  13068. });
  13069. this._lastUpdate = BABYLON.Tools.Now;
  13070. }
  13071. VideoTexture.prototype.update = function () {
  13072. if (this._autoLaunch) {
  13073. this._autoLaunch = false;
  13074. this.video.play();
  13075. }
  13076. var now = BABYLON.Tools.Now;
  13077. if (now - this._lastUpdate < 15) {
  13078. return false;
  13079. }
  13080. this._lastUpdate = now;
  13081. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13082. return true;
  13083. };
  13084. return VideoTexture;
  13085. })(BABYLON.Texture);
  13086. BABYLON.VideoTexture = VideoTexture;
  13087. })(BABYLON || (BABYLON = {}));
  13088. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13089. (function (BABYLON) {
  13090. var EffectFallbacks = (function () {
  13091. function EffectFallbacks() {
  13092. this._defines = {};
  13093. this._currentRank = 32;
  13094. this._maxRank = -1;
  13095. }
  13096. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13097. if (!this._defines[rank]) {
  13098. if (rank < this._currentRank) {
  13099. this._currentRank = rank;
  13100. }
  13101. if (rank > this._maxRank) {
  13102. this._maxRank = rank;
  13103. }
  13104. this._defines[rank] = new Array();
  13105. }
  13106. this._defines[rank].push(define);
  13107. };
  13108. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13109. get: function () {
  13110. return this._currentRank <= this._maxRank;
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13116. var currentFallbacks = this._defines[this._currentRank];
  13117. for (var index = 0; index < currentFallbacks.length; index++) {
  13118. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13119. }
  13120. this._currentRank++;
  13121. return currentDefines;
  13122. };
  13123. return EffectFallbacks;
  13124. })();
  13125. BABYLON.EffectFallbacks = EffectFallbacks;
  13126. var Effect = (function () {
  13127. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13128. var _this = this;
  13129. this._isReady = false;
  13130. this._compilationError = "";
  13131. this._valueCache = [];
  13132. this._engine = engine;
  13133. this.name = baseName;
  13134. this.defines = defines;
  13135. this._uniformsNames = uniformsNames.concat(samplers);
  13136. this._samplers = samplers;
  13137. this._attributesNames = attributesNames;
  13138. this.onError = onError;
  13139. this.onCompiled = onCompiled;
  13140. var vertexSource;
  13141. var fragmentSource;
  13142. if (baseName.vertexElement) {
  13143. vertexSource = document.getElementById(baseName.vertexElement);
  13144. if (!vertexSource) {
  13145. vertexSource = baseName.vertexElement;
  13146. }
  13147. }
  13148. else {
  13149. vertexSource = baseName.vertex || baseName;
  13150. }
  13151. if (baseName.fragmentElement) {
  13152. fragmentSource = document.getElementById(baseName.fragmentElement);
  13153. if (!fragmentSource) {
  13154. fragmentSource = baseName.fragmentElement;
  13155. }
  13156. }
  13157. else {
  13158. fragmentSource = baseName.fragment || baseName;
  13159. }
  13160. this._loadVertexShader(vertexSource, function (vertexCode) {
  13161. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13162. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13163. });
  13164. });
  13165. }
  13166. // Properties
  13167. Effect.prototype.isReady = function () {
  13168. return this._isReady;
  13169. };
  13170. Effect.prototype.getProgram = function () {
  13171. return this._program;
  13172. };
  13173. Effect.prototype.getAttributesNames = function () {
  13174. return this._attributesNames;
  13175. };
  13176. Effect.prototype.getAttributeLocation = function (index) {
  13177. return this._attributes[index];
  13178. };
  13179. Effect.prototype.getAttributeLocationByName = function (name) {
  13180. var index = this._attributesNames.indexOf(name);
  13181. return this._attributes[index];
  13182. };
  13183. Effect.prototype.getAttributesCount = function () {
  13184. return this._attributes.length;
  13185. };
  13186. Effect.prototype.getUniformIndex = function (uniformName) {
  13187. return this._uniformsNames.indexOf(uniformName);
  13188. };
  13189. Effect.prototype.getUniform = function (uniformName) {
  13190. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13191. };
  13192. Effect.prototype.getSamplers = function () {
  13193. return this._samplers;
  13194. };
  13195. Effect.prototype.getCompilationError = function () {
  13196. return this._compilationError;
  13197. };
  13198. // Methods
  13199. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13200. // DOM element ?
  13201. if (vertex instanceof HTMLElement) {
  13202. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13203. callback(vertexCode);
  13204. return;
  13205. }
  13206. // Is in local store ?
  13207. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13208. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13209. return;
  13210. }
  13211. var vertexShaderUrl;
  13212. if (vertex[0] === ".") {
  13213. vertexShaderUrl = vertex;
  13214. }
  13215. else {
  13216. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13217. }
  13218. // Vertex shader
  13219. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13220. };
  13221. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13222. // DOM element ?
  13223. if (fragment instanceof HTMLElement) {
  13224. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13225. callback(fragmentCode);
  13226. return;
  13227. }
  13228. // Is in local store ?
  13229. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13230. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13231. return;
  13232. }
  13233. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13234. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13235. return;
  13236. }
  13237. var fragmentShaderUrl;
  13238. if (fragment[0] === ".") {
  13239. fragmentShaderUrl = fragment;
  13240. }
  13241. else {
  13242. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13243. }
  13244. // Fragment shader
  13245. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13246. };
  13247. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13248. try {
  13249. var engine = this._engine;
  13250. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13251. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13252. this._attributes = engine.getAttributes(this._program, attributesNames);
  13253. for (var index = 0; index < this._samplers.length; index++) {
  13254. var sampler = this.getUniform(this._samplers[index]);
  13255. if (sampler == null) {
  13256. this._samplers.splice(index, 1);
  13257. index--;
  13258. }
  13259. }
  13260. engine.bindSamplers(this);
  13261. this._isReady = true;
  13262. if (this.onCompiled) {
  13263. this.onCompiled(this);
  13264. }
  13265. }
  13266. catch (e) {
  13267. // Is it a problem with precision?
  13268. if (e.message.indexOf("highp") !== -1) {
  13269. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13270. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13271. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13272. return;
  13273. }
  13274. // Let's go through fallbacks then
  13275. if (fallbacks && fallbacks.isMoreFallbacks) {
  13276. defines = fallbacks.reduce(defines);
  13277. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13278. }
  13279. else {
  13280. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13281. BABYLON.Tools.Error("Defines: " + defines);
  13282. BABYLON.Tools.Error("Error: " + e.message);
  13283. this._compilationError = e.message;
  13284. if (this.onError) {
  13285. this.onError(this, this._compilationError);
  13286. }
  13287. }
  13288. }
  13289. };
  13290. Effect.prototype._bindTexture = function (channel, texture) {
  13291. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13292. };
  13293. Effect.prototype.setTexture = function (channel, texture) {
  13294. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13295. };
  13296. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13297. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13298. };
  13299. //public _cacheMatrix(uniformName, matrix) {
  13300. // if (!this._valueCache[uniformName]) {
  13301. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13302. // }
  13303. // for (var index = 0; index < 16; index++) {
  13304. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13305. // }
  13306. //};
  13307. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13308. if (!this._valueCache[uniformName]) {
  13309. this._valueCache[uniformName] = [x, y];
  13310. return;
  13311. }
  13312. this._valueCache[uniformName][0] = x;
  13313. this._valueCache[uniformName][1] = y;
  13314. };
  13315. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13316. if (!this._valueCache[uniformName]) {
  13317. this._valueCache[uniformName] = [x, y, z];
  13318. return;
  13319. }
  13320. this._valueCache[uniformName][0] = x;
  13321. this._valueCache[uniformName][1] = y;
  13322. this._valueCache[uniformName][2] = z;
  13323. };
  13324. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13325. if (!this._valueCache[uniformName]) {
  13326. this._valueCache[uniformName] = [x, y, z, w];
  13327. return;
  13328. }
  13329. this._valueCache[uniformName][0] = x;
  13330. this._valueCache[uniformName][1] = y;
  13331. this._valueCache[uniformName][2] = z;
  13332. this._valueCache[uniformName][3] = w;
  13333. };
  13334. Effect.prototype.setArray = function (uniformName, array) {
  13335. this._engine.setArray(this.getUniform(uniformName), array);
  13336. return this;
  13337. };
  13338. Effect.prototype.setArray2 = function (uniformName, array) {
  13339. this._engine.setArray2(this.getUniform(uniformName), array);
  13340. return this;
  13341. };
  13342. Effect.prototype.setArray3 = function (uniformName, array) {
  13343. this._engine.setArray3(this.getUniform(uniformName), array);
  13344. return this;
  13345. };
  13346. Effect.prototype.setArray4 = function (uniformName, array) {
  13347. this._engine.setArray4(this.getUniform(uniformName), array);
  13348. return this;
  13349. };
  13350. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13351. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13352. return this;
  13353. };
  13354. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13355. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13356. // return;
  13357. //this._cacheMatrix(uniformName, matrix);
  13358. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13359. return this;
  13360. };
  13361. Effect.prototype.setFloat = function (uniformName, value) {
  13362. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13363. return this;
  13364. this._valueCache[uniformName] = value;
  13365. this._engine.setFloat(this.getUniform(uniformName), value);
  13366. return this;
  13367. };
  13368. Effect.prototype.setBool = function (uniformName, bool) {
  13369. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13370. return this;
  13371. this._valueCache[uniformName] = bool;
  13372. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13373. return this;
  13374. };
  13375. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13376. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13377. return this;
  13378. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13379. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13380. return this;
  13381. };
  13382. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13383. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13384. return this;
  13385. this._cacheFloat2(uniformName, x, y);
  13386. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13387. return this;
  13388. };
  13389. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13390. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13391. return this;
  13392. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13393. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13394. return this;
  13395. };
  13396. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13397. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13398. return this;
  13399. this._cacheFloat3(uniformName, x, y, z);
  13400. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13401. return this;
  13402. };
  13403. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13404. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13405. return this;
  13406. this._cacheFloat4(uniformName, x, y, z, w);
  13407. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13408. return this;
  13409. };
  13410. Effect.prototype.setColor3 = function (uniformName, color3) {
  13411. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13412. return this;
  13413. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13414. this._engine.setColor3(this.getUniform(uniformName), color3);
  13415. return this;
  13416. };
  13417. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13418. 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)
  13419. return this;
  13420. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13421. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13422. return this;
  13423. };
  13424. // Statics
  13425. 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}",
  13426. 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}",
  13427. 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}",
  13428. 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}",
  13429. 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}",
  13430. 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}",
  13431. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13432. 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}",
  13433. 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}",
  13434. 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 float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#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);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13435. 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}",
  13436. 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}",
  13437. 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}",
  13438. 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}",
  13439. 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}",
  13440. 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}",
  13441. 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}",
  13442. 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}",
  13443. 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}",
  13444. 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}",
  13445. 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}",
  13446. 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}",
  13447. 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}",
  13448. 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}",
  13449. 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}",
  13450. 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}",
  13451. 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}",
  13452. 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}",
  13453. 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}",
  13454. 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}",
  13455. 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}",
  13456. 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}",
  13457. 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}",
  13458. 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}",
  13459. 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}",
  13460. 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}",
  13461. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13462. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13463. 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}",
  13464. 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}",
  13465. 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}",
  13466. 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}",
  13467. 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}",
  13468. 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}",
  13469. 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}",
  13470. };
  13471. return Effect;
  13472. })();
  13473. BABYLON.Effect = Effect;
  13474. })(BABYLON || (BABYLON = {}));
  13475. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13476. (function (BABYLON) {
  13477. var Material = (function () {
  13478. function Material(name, scene, doNotAdd) {
  13479. this.name = name;
  13480. this.checkReadyOnEveryCall = true;
  13481. this.checkReadyOnlyOnce = false;
  13482. this.state = "";
  13483. this.alpha = 1.0;
  13484. this.backFaceCulling = true;
  13485. this._wasPreviouslyReady = false;
  13486. this._fillMode = Material.TriangleFillMode;
  13487. this.pointSize = 1.0;
  13488. this.id = name;
  13489. this._scene = scene;
  13490. if (!doNotAdd) {
  13491. scene.materials.push(this);
  13492. }
  13493. }
  13494. Object.defineProperty(Material, "TriangleFillMode", {
  13495. get: function () {
  13496. return Material._TriangleFillMode;
  13497. },
  13498. enumerable: true,
  13499. configurable: true
  13500. });
  13501. Object.defineProperty(Material, "WireFrameFillMode", {
  13502. get: function () {
  13503. return Material._WireFrameFillMode;
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Object.defineProperty(Material, "PointFillMode", {
  13509. get: function () {
  13510. return Material._PointFillMode;
  13511. },
  13512. enumerable: true,
  13513. configurable: true
  13514. });
  13515. Object.defineProperty(Material.prototype, "wireframe", {
  13516. get: function () {
  13517. return this._fillMode === Material.WireFrameFillMode;
  13518. },
  13519. set: function (value) {
  13520. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13521. },
  13522. enumerable: true,
  13523. configurable: true
  13524. });
  13525. Object.defineProperty(Material.prototype, "pointsCloud", {
  13526. get: function () {
  13527. return this._fillMode === Material.PointFillMode;
  13528. },
  13529. set: function (value) {
  13530. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13531. },
  13532. enumerable: true,
  13533. configurable: true
  13534. });
  13535. Object.defineProperty(Material.prototype, "fillMode", {
  13536. get: function () {
  13537. return this._fillMode;
  13538. },
  13539. set: function (value) {
  13540. this._fillMode = value;
  13541. },
  13542. enumerable: true,
  13543. configurable: true
  13544. });
  13545. Material.prototype.isReady = function (mesh, useInstances) {
  13546. return true;
  13547. };
  13548. Material.prototype.getEffect = function () {
  13549. return this._effect;
  13550. };
  13551. Material.prototype.getScene = function () {
  13552. return this._scene;
  13553. };
  13554. Material.prototype.needAlphaBlending = function () {
  13555. return (this.alpha < 1.0);
  13556. };
  13557. Material.prototype.needAlphaTesting = function () {
  13558. return false;
  13559. };
  13560. Material.prototype.getAlphaTestTexture = function () {
  13561. return null;
  13562. };
  13563. Material.prototype.trackCreation = function (onCompiled, onError) {
  13564. };
  13565. Material.prototype._preBind = function () {
  13566. var engine = this._scene.getEngine();
  13567. engine.enableEffect(this._effect);
  13568. engine.setState(this.backFaceCulling);
  13569. };
  13570. Material.prototype.bind = function (world, mesh) {
  13571. this._scene._cachedMaterial = this;
  13572. if (this.onBind) {
  13573. this.onBind(this);
  13574. }
  13575. };
  13576. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13577. };
  13578. Material.prototype.unbind = function () {
  13579. };
  13580. Material.prototype.dispose = function (forceDisposeEffect) {
  13581. // Remove from scene
  13582. var index = this._scene.materials.indexOf(this);
  13583. this._scene.materials.splice(index, 1);
  13584. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13585. if (forceDisposeEffect && this._effect) {
  13586. this._scene.getEngine()._releaseEffect(this._effect);
  13587. this._effect = null;
  13588. }
  13589. // Callback
  13590. if (this.onDispose) {
  13591. this.onDispose();
  13592. }
  13593. };
  13594. Material._TriangleFillMode = 0;
  13595. Material._WireFrameFillMode = 1;
  13596. Material._PointFillMode = 2;
  13597. return Material;
  13598. })();
  13599. BABYLON.Material = Material;
  13600. })(BABYLON || (BABYLON = {}));
  13601. //# sourceMappingURL=babylon.material.js.map
  13602. var BABYLON;
  13603. (function (BABYLON) {
  13604. var maxSimultaneousLights = 4;
  13605. var FresnelParameters = (function () {
  13606. function FresnelParameters() {
  13607. this.isEnabled = true;
  13608. this.leftColor = BABYLON.Color3.White();
  13609. this.rightColor = BABYLON.Color3.Black();
  13610. this.bias = 0;
  13611. this.power = 1;
  13612. }
  13613. return FresnelParameters;
  13614. })();
  13615. BABYLON.FresnelParameters = FresnelParameters;
  13616. var StandardMaterial = (function (_super) {
  13617. __extends(StandardMaterial, _super);
  13618. function StandardMaterial(name, scene) {
  13619. var _this = this;
  13620. _super.call(this, name, scene);
  13621. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13622. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13623. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13624. this.specularPower = 64;
  13625. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13626. this.useAlphaFromDiffuseTexture = false;
  13627. this.useSpecularOverAlpha = true;
  13628. this.fogEnabled = true;
  13629. this._cachedDefines = null;
  13630. this._renderTargets = new BABYLON.SmartArray(16);
  13631. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13632. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13633. this._scaledDiffuse = new BABYLON.Color3();
  13634. this._scaledSpecular = new BABYLON.Color3();
  13635. this.getRenderTargetTextures = function () {
  13636. _this._renderTargets.reset();
  13637. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13638. _this._renderTargets.push(_this.reflectionTexture);
  13639. }
  13640. return _this._renderTargets;
  13641. };
  13642. }
  13643. StandardMaterial.prototype.needAlphaBlending = function () {
  13644. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13645. };
  13646. StandardMaterial.prototype.needAlphaTesting = function () {
  13647. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13648. };
  13649. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13650. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13651. };
  13652. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13653. return this.diffuseTexture;
  13654. };
  13655. // Methods
  13656. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13657. if (this.checkReadyOnlyOnce) {
  13658. if (this._wasPreviouslyReady) {
  13659. return true;
  13660. }
  13661. }
  13662. var scene = this.getScene();
  13663. if (!this.checkReadyOnEveryCall) {
  13664. if (this._renderId === scene.getRenderId()) {
  13665. return true;
  13666. }
  13667. }
  13668. var engine = scene.getEngine();
  13669. var defines = [];
  13670. var fallbacks = new BABYLON.EffectFallbacks();
  13671. var needNormals = false;
  13672. var needUVs = false;
  13673. // Textures
  13674. if (scene.texturesEnabled) {
  13675. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13676. if (!this.diffuseTexture.isReady()) {
  13677. return false;
  13678. }
  13679. else {
  13680. needUVs = true;
  13681. defines.push("#define DIFFUSE");
  13682. }
  13683. }
  13684. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13685. if (!this.ambientTexture.isReady()) {
  13686. return false;
  13687. }
  13688. else {
  13689. needUVs = true;
  13690. defines.push("#define AMBIENT");
  13691. }
  13692. }
  13693. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13694. if (!this.opacityTexture.isReady()) {
  13695. return false;
  13696. }
  13697. else {
  13698. needUVs = true;
  13699. defines.push("#define OPACITY");
  13700. if (this.opacityTexture.getAlphaFromRGB) {
  13701. defines.push("#define OPACITYRGB");
  13702. }
  13703. }
  13704. }
  13705. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13706. if (!this.reflectionTexture.isReady()) {
  13707. return false;
  13708. }
  13709. else {
  13710. needNormals = true;
  13711. needUVs = true;
  13712. defines.push("#define REFLECTION");
  13713. fallbacks.addFallback(0, "REFLECTION");
  13714. }
  13715. }
  13716. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13717. if (!this.emissiveTexture.isReady()) {
  13718. return false;
  13719. }
  13720. else {
  13721. needUVs = true;
  13722. defines.push("#define EMISSIVE");
  13723. }
  13724. }
  13725. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13726. if (!this.specularTexture.isReady()) {
  13727. return false;
  13728. }
  13729. else {
  13730. needUVs = true;
  13731. defines.push("#define SPECULAR");
  13732. fallbacks.addFallback(0, "SPECULAR");
  13733. }
  13734. }
  13735. }
  13736. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13737. if (!this.bumpTexture.isReady()) {
  13738. return false;
  13739. }
  13740. else {
  13741. needUVs = true;
  13742. defines.push("#define BUMP");
  13743. fallbacks.addFallback(0, "BUMP");
  13744. }
  13745. }
  13746. // Effect
  13747. if (this.useSpecularOverAlpha) {
  13748. defines.push("#define SPECULAROVERALPHA");
  13749. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13750. }
  13751. if (scene.clipPlane) {
  13752. defines.push("#define CLIPPLANE");
  13753. }
  13754. if (engine.getAlphaTesting()) {
  13755. defines.push("#define ALPHATEST");
  13756. }
  13757. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13758. defines.push("#define ALPHAFROMDIFFUSE");
  13759. }
  13760. // Point size
  13761. if (this.pointsCloud || scene.forcePointsCloud) {
  13762. defines.push("#define POINTSIZE");
  13763. }
  13764. // Fog
  13765. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13766. defines.push("#define FOG");
  13767. fallbacks.addFallback(1, "FOG");
  13768. }
  13769. var shadowsActivated = false;
  13770. var lightIndex = 0;
  13771. if (scene.lightsEnabled) {
  13772. for (var index = 0; index < scene.lights.length; index++) {
  13773. var light = scene.lights[index];
  13774. if (!light.isEnabled()) {
  13775. continue;
  13776. }
  13777. // Excluded check
  13778. if (light._excludedMeshesIds.length > 0) {
  13779. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13780. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13781. if (excludedMesh) {
  13782. light.excludedMeshes.push(excludedMesh);
  13783. }
  13784. }
  13785. light._excludedMeshesIds = [];
  13786. }
  13787. // Included check
  13788. if (light._includedOnlyMeshesIds.length > 0) {
  13789. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13790. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13791. if (includedOnlyMesh) {
  13792. light.includedOnlyMeshes.push(includedOnlyMesh);
  13793. }
  13794. }
  13795. light._includedOnlyMeshesIds = [];
  13796. }
  13797. if (!light.canAffectMesh(mesh)) {
  13798. continue;
  13799. }
  13800. needNormals = true;
  13801. defines.push("#define LIGHT" + lightIndex);
  13802. if (lightIndex > 0) {
  13803. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13804. }
  13805. var type;
  13806. if (light instanceof BABYLON.SpotLight) {
  13807. type = "#define SPOTLIGHT" + lightIndex;
  13808. }
  13809. else if (light instanceof BABYLON.HemisphericLight) {
  13810. type = "#define HEMILIGHT" + lightIndex;
  13811. }
  13812. else {
  13813. type = "#define POINTDIRLIGHT" + lightIndex;
  13814. }
  13815. defines.push(type);
  13816. if (lightIndex > 0) {
  13817. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13818. }
  13819. // Shadows
  13820. if (scene.shadowsEnabled) {
  13821. var shadowGenerator = light.getShadowGenerator();
  13822. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13823. defines.push("#define SHADOW" + lightIndex);
  13824. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13825. if (!shadowsActivated) {
  13826. defines.push("#define SHADOWS");
  13827. shadowsActivated = true;
  13828. }
  13829. if (shadowGenerator.useVarianceShadowMap) {
  13830. defines.push("#define SHADOWVSM" + lightIndex);
  13831. if (lightIndex > 0) {
  13832. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13833. }
  13834. }
  13835. if (shadowGenerator.usePoissonSampling) {
  13836. defines.push("#define SHADOWPCF" + lightIndex);
  13837. if (lightIndex > 0) {
  13838. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13839. }
  13840. }
  13841. }
  13842. }
  13843. lightIndex++;
  13844. if (lightIndex === maxSimultaneousLights)
  13845. break;
  13846. }
  13847. }
  13848. if (StandardMaterial.FresnelEnabled) {
  13849. // Fresnel
  13850. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13851. var fresnelRank = 1;
  13852. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13853. defines.push("#define DIFFUSEFRESNEL");
  13854. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13855. fresnelRank++;
  13856. }
  13857. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13858. defines.push("#define OPACITYFRESNEL");
  13859. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13860. fresnelRank++;
  13861. }
  13862. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13863. defines.push("#define REFLECTIONFRESNEL");
  13864. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13865. fresnelRank++;
  13866. }
  13867. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13868. defines.push("#define EMISSIVEFRESNEL");
  13869. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13870. fresnelRank++;
  13871. }
  13872. needNormals = true;
  13873. defines.push("#define FRESNEL");
  13874. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13875. }
  13876. }
  13877. // Attribs
  13878. var attribs = [BABYLON.VertexBuffer.PositionKind];
  13879. if (mesh) {
  13880. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13881. attribs.push(BABYLON.VertexBuffer.NormalKind);
  13882. defines.push("#define NORMAL");
  13883. }
  13884. if (needUVs) {
  13885. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13886. attribs.push(BABYLON.VertexBuffer.UVKind);
  13887. defines.push("#define UV1");
  13888. }
  13889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13890. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13891. defines.push("#define UV2");
  13892. }
  13893. }
  13894. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13895. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13896. defines.push("#define VERTEXCOLOR");
  13897. if (mesh.hasVertexAlpha) {
  13898. defines.push("#define VERTEXALPHA");
  13899. }
  13900. }
  13901. if (mesh.useBones) {
  13902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13904. defines.push("#define BONES");
  13905. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13906. defines.push("#define BONES4");
  13907. fallbacks.addFallback(0, "BONES4");
  13908. }
  13909. // Instances
  13910. if (useInstances) {
  13911. defines.push("#define INSTANCES");
  13912. attribs.push("world0");
  13913. attribs.push("world1");
  13914. attribs.push("world2");
  13915. attribs.push("world3");
  13916. }
  13917. }
  13918. // Get correct effect
  13919. var join = defines.join("\n");
  13920. if (this._cachedDefines !== join) {
  13921. this._cachedDefines = join;
  13922. scene.resetCachedMaterial();
  13923. // Legacy browser patch
  13924. var shaderName = "default";
  13925. if (!scene.getEngine().getCaps().standardDerivatives) {
  13926. shaderName = "legacydefault";
  13927. }
  13928. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13929. }
  13930. if (!this._effect.isReady()) {
  13931. return false;
  13932. }
  13933. this._renderId = scene.getRenderId();
  13934. this._wasPreviouslyReady = true;
  13935. return true;
  13936. };
  13937. StandardMaterial.prototype.unbind = function () {
  13938. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13939. this._effect.setTexture("reflection2DSampler", null);
  13940. }
  13941. };
  13942. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13943. this._effect.setMatrix("world", world);
  13944. };
  13945. StandardMaterial.prototype.bind = function (world, mesh) {
  13946. var scene = this.getScene();
  13947. // Matrices
  13948. this.bindOnlyWorldMatrix(world);
  13949. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13950. // Bones
  13951. if (mesh.useBones) {
  13952. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13953. }
  13954. if (scene.getCachedMaterial() !== this) {
  13955. if (StandardMaterial.FresnelEnabled) {
  13956. // Fresnel
  13957. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13958. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13959. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13960. }
  13961. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13962. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13963. }
  13964. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13965. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13966. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13967. }
  13968. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13969. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13970. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13971. }
  13972. }
  13973. // Textures
  13974. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13975. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13976. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13977. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13978. }
  13979. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13980. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13981. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13982. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13983. }
  13984. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13985. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13986. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13987. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13988. }
  13989. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13990. if (this.reflectionTexture.isCube) {
  13991. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13992. }
  13993. else {
  13994. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13995. }
  13996. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13997. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13998. }
  13999. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14000. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14001. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14002. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14003. }
  14004. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14005. this._effect.setTexture("specularSampler", this.specularTexture);
  14006. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14007. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14008. }
  14009. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14010. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14011. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14012. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14013. }
  14014. // Clip plane
  14015. if (scene.clipPlane) {
  14016. var clipPlane = scene.clipPlane;
  14017. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14018. }
  14019. // Point size
  14020. if (this.pointsCloud) {
  14021. this._effect.setFloat("pointSize", this.pointSize);
  14022. }
  14023. // Colors
  14024. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14025. // Scaling down color according to emissive
  14026. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14027. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14028. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14029. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14030. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14031. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14032. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14033. }
  14034. // Scaling down color according to emissive
  14035. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14036. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14037. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14038. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14039. if (scene.lightsEnabled) {
  14040. var lightIndex = 0;
  14041. for (var index = 0; index < scene.lights.length; index++) {
  14042. var light = scene.lights[index];
  14043. if (!light.isEnabled()) {
  14044. continue;
  14045. }
  14046. if (!light.canAffectMesh(mesh)) {
  14047. continue;
  14048. }
  14049. if (light instanceof BABYLON.PointLight) {
  14050. // Point Light
  14051. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14052. }
  14053. else if (light instanceof BABYLON.DirectionalLight) {
  14054. // Directional Light
  14055. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14056. }
  14057. else if (light instanceof BABYLON.SpotLight) {
  14058. // Spot Light
  14059. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14060. }
  14061. else if (light instanceof BABYLON.HemisphericLight) {
  14062. // Hemispheric Light
  14063. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14064. }
  14065. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14066. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14067. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14068. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14069. // Shadows
  14070. if (scene.shadowsEnabled) {
  14071. var shadowGenerator = light.getShadowGenerator();
  14072. if (mesh.receiveShadows && shadowGenerator) {
  14073. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14074. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  14075. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  14076. }
  14077. }
  14078. lightIndex++;
  14079. if (lightIndex === maxSimultaneousLights)
  14080. break;
  14081. }
  14082. }
  14083. // View
  14084. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14085. this._effect.setMatrix("view", scene.getViewMatrix());
  14086. }
  14087. // Fog
  14088. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14089. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14090. this._effect.setColor3("vFogColor", scene.fogColor);
  14091. }
  14092. _super.prototype.bind.call(this, world, mesh);
  14093. };
  14094. StandardMaterial.prototype.getAnimatables = function () {
  14095. var results = [];
  14096. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14097. results.push(this.diffuseTexture);
  14098. }
  14099. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14100. results.push(this.ambientTexture);
  14101. }
  14102. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14103. results.push(this.opacityTexture);
  14104. }
  14105. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14106. results.push(this.reflectionTexture);
  14107. }
  14108. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14109. results.push(this.emissiveTexture);
  14110. }
  14111. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14112. results.push(this.specularTexture);
  14113. }
  14114. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14115. results.push(this.bumpTexture);
  14116. }
  14117. return results;
  14118. };
  14119. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14120. if (this.diffuseTexture) {
  14121. this.diffuseTexture.dispose();
  14122. }
  14123. if (this.ambientTexture) {
  14124. this.ambientTexture.dispose();
  14125. }
  14126. if (this.opacityTexture) {
  14127. this.opacityTexture.dispose();
  14128. }
  14129. if (this.reflectionTexture) {
  14130. this.reflectionTexture.dispose();
  14131. }
  14132. if (this.emissiveTexture) {
  14133. this.emissiveTexture.dispose();
  14134. }
  14135. if (this.specularTexture) {
  14136. this.specularTexture.dispose();
  14137. }
  14138. if (this.bumpTexture) {
  14139. this.bumpTexture.dispose();
  14140. }
  14141. _super.prototype.dispose.call(this, forceDisposeEffect);
  14142. };
  14143. StandardMaterial.prototype.clone = function (name) {
  14144. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14145. // Base material
  14146. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14147. newStandardMaterial.alpha = this.alpha;
  14148. newStandardMaterial.fillMode = this.fillMode;
  14149. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14150. // Standard material
  14151. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14152. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14153. }
  14154. if (this.ambientTexture && this.ambientTexture.clone) {
  14155. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14156. }
  14157. if (this.opacityTexture && this.opacityTexture.clone) {
  14158. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14159. }
  14160. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14161. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14162. }
  14163. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14164. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14165. }
  14166. if (this.specularTexture && this.specularTexture.clone) {
  14167. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14168. }
  14169. if (this.bumpTexture && this.bumpTexture.clone) {
  14170. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14171. }
  14172. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14173. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14174. newStandardMaterial.specularColor = this.specularColor.clone();
  14175. newStandardMaterial.specularPower = this.specularPower;
  14176. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14177. return newStandardMaterial;
  14178. };
  14179. // Statics
  14180. // Flags used to enable or disable a type of texture for all Standard Materials
  14181. StandardMaterial.DiffuseTextureEnabled = true;
  14182. StandardMaterial.AmbientTextureEnabled = true;
  14183. StandardMaterial.OpacityTextureEnabled = true;
  14184. StandardMaterial.ReflectionTextureEnabled = true;
  14185. StandardMaterial.EmissiveTextureEnabled = true;
  14186. StandardMaterial.SpecularTextureEnabled = true;
  14187. StandardMaterial.BumpTextureEnabled = true;
  14188. StandardMaterial.FresnelEnabled = true;
  14189. return StandardMaterial;
  14190. })(BABYLON.Material);
  14191. BABYLON.StandardMaterial = StandardMaterial;
  14192. })(BABYLON || (BABYLON = {}));
  14193. //# sourceMappingURL=babylon.standardMaterial.js.map
  14194. var BABYLON;
  14195. (function (BABYLON) {
  14196. var MultiMaterial = (function (_super) {
  14197. __extends(MultiMaterial, _super);
  14198. function MultiMaterial(name, scene) {
  14199. _super.call(this, name, scene, true);
  14200. this.subMaterials = new Array();
  14201. scene.multiMaterials.push(this);
  14202. }
  14203. // Properties
  14204. MultiMaterial.prototype.getSubMaterial = function (index) {
  14205. if (index < 0 || index >= this.subMaterials.length) {
  14206. return this.getScene().defaultMaterial;
  14207. }
  14208. return this.subMaterials[index];
  14209. };
  14210. // Methods
  14211. MultiMaterial.prototype.isReady = function (mesh) {
  14212. for (var index = 0; index < this.subMaterials.length; index++) {
  14213. var subMaterial = this.subMaterials[index];
  14214. if (subMaterial) {
  14215. if (!this.subMaterials[index].isReady(mesh)) {
  14216. return false;
  14217. }
  14218. }
  14219. }
  14220. return true;
  14221. };
  14222. return MultiMaterial;
  14223. })(BABYLON.Material);
  14224. BABYLON.MultiMaterial = MultiMaterial;
  14225. })(BABYLON || (BABYLON = {}));
  14226. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14227. (function (BABYLON) {
  14228. var Database = (function () {
  14229. function Database(urlToScene, callbackManifestChecked) {
  14230. // Handling various flavors of prefixed version of IndexedDB
  14231. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14232. this.callbackManifestChecked = callbackManifestChecked;
  14233. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14234. this.db = null;
  14235. this.enableSceneOffline = false;
  14236. this.enableTexturesOffline = false;
  14237. this.manifestVersionFound = 0;
  14238. this.mustUpdateRessources = false;
  14239. this.hasReachedQuota = false;
  14240. this.checkManifestFile();
  14241. }
  14242. Database.prototype.checkManifestFile = function () {
  14243. var _this = this;
  14244. function noManifestFile() {
  14245. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14246. that.enableSceneOffline = false;
  14247. that.enableTexturesOffline = false;
  14248. that.callbackManifestChecked(false);
  14249. }
  14250. var that = this;
  14251. var manifestURL = this.currentSceneUrl + ".manifest";
  14252. var xhr = new XMLHttpRequest();
  14253. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14254. xhr.open("GET", manifestURLTimeStamped, true);
  14255. xhr.addEventListener("load", function () {
  14256. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14257. try {
  14258. var manifestFile = JSON.parse(xhr.response);
  14259. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14260. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14261. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14262. _this.manifestVersionFound = manifestFile.version;
  14263. }
  14264. if (_this.callbackManifestChecked) {
  14265. _this.callbackManifestChecked(true);
  14266. }
  14267. }
  14268. catch (ex) {
  14269. noManifestFile();
  14270. }
  14271. }
  14272. else {
  14273. noManifestFile();
  14274. }
  14275. }, false);
  14276. xhr.addEventListener("error", function (event) {
  14277. noManifestFile();
  14278. }, false);
  14279. try {
  14280. xhr.send();
  14281. }
  14282. catch (ex) {
  14283. BABYLON.Tools.Error("Error on XHR send request.");
  14284. that.callbackManifestChecked(false);
  14285. }
  14286. };
  14287. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14288. var _this = this;
  14289. function handleError() {
  14290. that.isSupported = false;
  14291. if (errorCallback)
  14292. errorCallback();
  14293. }
  14294. var that = this;
  14295. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14296. // Your browser doesn't support IndexedDB
  14297. this.isSupported = false;
  14298. if (errorCallback)
  14299. errorCallback();
  14300. }
  14301. else {
  14302. // If the DB hasn't been opened or created yet
  14303. if (!this.db) {
  14304. this.hasReachedQuota = false;
  14305. this.isSupported = true;
  14306. var request = this.idbFactory.open("babylonjs", 1);
  14307. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14308. request.onerror = function (event) {
  14309. handleError();
  14310. };
  14311. // executes when a version change transaction cannot complete due to other active transactions
  14312. request.onblocked = function (event) {
  14313. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14314. handleError();
  14315. };
  14316. // DB has been opened successfully
  14317. request.onsuccess = function (event) {
  14318. _this.db = request.result;
  14319. successCallback();
  14320. };
  14321. // Initialization of the DB. Creating Scenes & Textures stores
  14322. request.onupgradeneeded = function (event) {
  14323. _this.db = (event.target).result;
  14324. try {
  14325. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14326. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14327. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14328. }
  14329. catch (ex) {
  14330. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14331. handleError();
  14332. }
  14333. };
  14334. }
  14335. else {
  14336. if (successCallback)
  14337. successCallback();
  14338. }
  14339. }
  14340. };
  14341. Database.prototype.loadImageFromDB = function (url, image) {
  14342. var _this = this;
  14343. var completeURL = Database.ReturnFullUrlLocation(url);
  14344. var saveAndLoadImage = function () {
  14345. if (!_this.hasReachedQuota && _this.db !== null) {
  14346. // the texture is not yet in the DB, let's try to save it
  14347. _this._saveImageIntoDBAsync(completeURL, image);
  14348. }
  14349. else {
  14350. image.src = url;
  14351. }
  14352. };
  14353. if (!this.mustUpdateRessources) {
  14354. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14355. }
  14356. else {
  14357. saveAndLoadImage();
  14358. }
  14359. };
  14360. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14361. if (this.isSupported && this.db !== null) {
  14362. var texture;
  14363. var transaction = this.db.transaction(["textures"]);
  14364. transaction.onabort = function (event) {
  14365. image.src = url;
  14366. };
  14367. transaction.oncomplete = function (event) {
  14368. var blobTextureURL;
  14369. if (texture) {
  14370. var URL = window.URL || window.webkitURL;
  14371. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14372. image.onerror = function () {
  14373. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14374. image.src = url;
  14375. };
  14376. image.src = blobTextureURL;
  14377. }
  14378. else {
  14379. notInDBCallback();
  14380. }
  14381. };
  14382. var getRequest = transaction.objectStore("textures").get(url);
  14383. getRequest.onsuccess = function (event) {
  14384. texture = (event.target).result;
  14385. };
  14386. getRequest.onerror = function (event) {
  14387. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14388. image.src = url;
  14389. };
  14390. }
  14391. else {
  14392. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14393. image.src = url;
  14394. }
  14395. };
  14396. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14397. var _this = this;
  14398. if (this.isSupported) {
  14399. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14400. var generateBlobUrl = function () {
  14401. var blobTextureURL;
  14402. if (blob) {
  14403. var URL = window.URL || window.webkitURL;
  14404. try {
  14405. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14406. }
  14407. catch (ex) {
  14408. blobTextureURL = URL.createObjectURL(blob);
  14409. }
  14410. }
  14411. image.src = blobTextureURL;
  14412. };
  14413. if (Database.isUASupportingBlobStorage) {
  14414. var xhr = new XMLHttpRequest(), blob;
  14415. xhr.open("GET", url, true);
  14416. xhr.responseType = "blob";
  14417. xhr.addEventListener("load", function () {
  14418. if (xhr.status === 200) {
  14419. // Blob as response (XHR2)
  14420. blob = xhr.response;
  14421. var transaction = _this.db.transaction(["textures"], "readwrite");
  14422. // the transaction could abort because of a QuotaExceededError error
  14423. transaction.onabort = function (event) {
  14424. try {
  14425. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14426. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14427. this.hasReachedQuota = true;
  14428. }
  14429. }
  14430. catch (ex) {
  14431. }
  14432. generateBlobUrl();
  14433. };
  14434. transaction.oncomplete = function (event) {
  14435. generateBlobUrl();
  14436. };
  14437. var newTexture = { textureUrl: url, data: blob };
  14438. try {
  14439. // Put the blob into the dabase
  14440. var addRequest = transaction.objectStore("textures").put(newTexture);
  14441. addRequest.onsuccess = function (event) {
  14442. };
  14443. addRequest.onerror = function (event) {
  14444. generateBlobUrl();
  14445. };
  14446. }
  14447. catch (ex) {
  14448. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14449. if (ex.code === 25) {
  14450. Database.isUASupportingBlobStorage = false;
  14451. }
  14452. image.src = url;
  14453. }
  14454. }
  14455. else {
  14456. image.src = url;
  14457. }
  14458. }, false);
  14459. xhr.addEventListener("error", function (event) {
  14460. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14461. image.src = url;
  14462. }, false);
  14463. xhr.send();
  14464. }
  14465. else {
  14466. image.src = url;
  14467. }
  14468. }
  14469. else {
  14470. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14471. image.src = url;
  14472. }
  14473. };
  14474. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14475. var _this = this;
  14476. var updateVersion = function (event) {
  14477. // the version is not yet in the DB or we need to update it
  14478. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14479. };
  14480. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14481. };
  14482. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14483. var _this = this;
  14484. if (this.isSupported) {
  14485. var version;
  14486. try {
  14487. var transaction = this.db.transaction(["versions"]);
  14488. transaction.oncomplete = function (event) {
  14489. if (version) {
  14490. // If the version in the JSON file is > than the version in DB
  14491. if (_this.manifestVersionFound > version.data) {
  14492. _this.mustUpdateRessources = true;
  14493. updateInDBCallback();
  14494. }
  14495. else {
  14496. callback(version.data);
  14497. }
  14498. }
  14499. else {
  14500. _this.mustUpdateRessources = true;
  14501. updateInDBCallback();
  14502. }
  14503. };
  14504. transaction.onabort = function (event) {
  14505. callback(-1);
  14506. };
  14507. var getRequest = transaction.objectStore("versions").get(url);
  14508. getRequest.onsuccess = function (event) {
  14509. version = (event.target).result;
  14510. };
  14511. getRequest.onerror = function (event) {
  14512. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14513. callback(-1);
  14514. };
  14515. }
  14516. catch (ex) {
  14517. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14518. callback(-1);
  14519. }
  14520. }
  14521. else {
  14522. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14523. callback(-1);
  14524. }
  14525. };
  14526. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14527. var _this = this;
  14528. if (this.isSupported && !this.hasReachedQuota) {
  14529. try {
  14530. // Open a transaction to the database
  14531. var transaction = this.db.transaction(["versions"], "readwrite");
  14532. // the transaction could abort because of a QuotaExceededError error
  14533. transaction.onabort = function (event) {
  14534. try {
  14535. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14536. _this.hasReachedQuota = true;
  14537. }
  14538. }
  14539. catch (ex) {
  14540. }
  14541. callback(-1);
  14542. };
  14543. transaction.oncomplete = function (event) {
  14544. callback(_this.manifestVersionFound);
  14545. };
  14546. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14547. // Put the scene into the database
  14548. var addRequest = transaction.objectStore("versions").put(newVersion);
  14549. addRequest.onsuccess = function (event) {
  14550. };
  14551. addRequest.onerror = function (event) {
  14552. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14553. };
  14554. }
  14555. catch (ex) {
  14556. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14557. callback(-1);
  14558. }
  14559. }
  14560. else {
  14561. callback(-1);
  14562. }
  14563. };
  14564. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14565. var _this = this;
  14566. var completeUrl = Database.ReturnFullUrlLocation(url);
  14567. var saveAndLoadFile = function (event) {
  14568. // the scene is not yet in the DB, let's try to save it
  14569. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14570. };
  14571. this._checkVersionFromDB(completeUrl, function (version) {
  14572. if (version !== -1) {
  14573. if (!_this.mustUpdateRessources) {
  14574. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14575. }
  14576. else {
  14577. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14578. }
  14579. }
  14580. else {
  14581. errorCallback();
  14582. }
  14583. });
  14584. };
  14585. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14586. if (this.isSupported) {
  14587. var targetStore;
  14588. if (url.indexOf(".babylon") !== -1) {
  14589. targetStore = "scenes";
  14590. }
  14591. else {
  14592. targetStore = "textures";
  14593. }
  14594. var file;
  14595. var transaction = this.db.transaction([targetStore]);
  14596. transaction.oncomplete = function (event) {
  14597. if (file) {
  14598. callback(file.data);
  14599. }
  14600. else {
  14601. notInDBCallback();
  14602. }
  14603. };
  14604. transaction.onabort = function (event) {
  14605. notInDBCallback();
  14606. };
  14607. var getRequest = transaction.objectStore(targetStore).get(url);
  14608. getRequest.onsuccess = function (event) {
  14609. file = (event.target).result;
  14610. };
  14611. getRequest.onerror = function (event) {
  14612. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14613. notInDBCallback();
  14614. };
  14615. }
  14616. else {
  14617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14618. callback();
  14619. }
  14620. };
  14621. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14622. var _this = this;
  14623. if (this.isSupported) {
  14624. var targetStore;
  14625. if (url.indexOf(".babylon") !== -1) {
  14626. targetStore = "scenes";
  14627. }
  14628. else {
  14629. targetStore = "textures";
  14630. }
  14631. // Create XHR
  14632. var xhr = new XMLHttpRequest(), fileData;
  14633. xhr.open("GET", url, true);
  14634. if (useArrayBuffer) {
  14635. xhr.responseType = "arraybuffer";
  14636. }
  14637. xhr.onprogress = progressCallback;
  14638. xhr.addEventListener("load", function () {
  14639. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14640. // Blob as response (XHR2)
  14641. //fileData = xhr.responseText;
  14642. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14643. if (!_this.hasReachedQuota) {
  14644. // Open a transaction to the database
  14645. var transaction = _this.db.transaction([targetStore], "readwrite");
  14646. // the transaction could abort because of a QuotaExceededError error
  14647. transaction.onabort = function (event) {
  14648. try {
  14649. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14650. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14651. this.hasReachedQuota = true;
  14652. }
  14653. }
  14654. catch (ex) {
  14655. }
  14656. callback(fileData);
  14657. };
  14658. transaction.oncomplete = function (event) {
  14659. callback(fileData);
  14660. };
  14661. var newFile;
  14662. if (targetStore === "scenes") {
  14663. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14664. }
  14665. else {
  14666. newFile = { textureUrl: url, data: fileData };
  14667. }
  14668. try {
  14669. // Put the scene into the database
  14670. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14671. addRequest.onsuccess = function (event) {
  14672. };
  14673. addRequest.onerror = function (event) {
  14674. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14675. };
  14676. }
  14677. catch (ex) {
  14678. callback(fileData);
  14679. }
  14680. }
  14681. else {
  14682. callback(fileData);
  14683. }
  14684. }
  14685. else {
  14686. callback();
  14687. }
  14688. }, false);
  14689. xhr.addEventListener("error", function (event) {
  14690. BABYLON.Tools.Error("error on XHR request.");
  14691. callback();
  14692. }, false);
  14693. xhr.send();
  14694. }
  14695. else {
  14696. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14697. callback();
  14698. }
  14699. };
  14700. Database.isUASupportingBlobStorage = true;
  14701. Database.parseURL = function (url) {
  14702. var a = document.createElement('a');
  14703. a.href = url;
  14704. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14705. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14706. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14707. return absLocation;
  14708. };
  14709. Database.ReturnFullUrlLocation = function (url) {
  14710. if (url.indexOf("http:/") === -1) {
  14711. return (BABYLON.Database.parseURL(window.location.href) + url);
  14712. }
  14713. else {
  14714. return url;
  14715. }
  14716. };
  14717. return Database;
  14718. })();
  14719. BABYLON.Database = Database;
  14720. })(BABYLON || (BABYLON = {}));
  14721. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14722. (function (BABYLON) {
  14723. var SpriteManager = (function () {
  14724. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14725. this.name = name;
  14726. this.cellSize = cellSize;
  14727. this.sprites = new Array();
  14728. this.renderingGroupId = 0;
  14729. this.fogEnabled = true;
  14730. this._vertexDeclaration = [3, 4, 4, 4];
  14731. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14732. this._capacity = capacity;
  14733. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14734. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14735. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14736. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14737. this._scene = scene;
  14738. this._scene.spriteManagers.push(this);
  14739. // VBO
  14740. this._vertexDeclaration = [3, 4, 4, 4];
  14741. this._vertexStrideSize = 15 * 4;
  14742. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14743. var indices = [];
  14744. var index = 0;
  14745. for (var count = 0; count < capacity; count++) {
  14746. indices.push(index);
  14747. indices.push(index + 1);
  14748. indices.push(index + 2);
  14749. indices.push(index);
  14750. indices.push(index + 2);
  14751. indices.push(index + 3);
  14752. index += 4;
  14753. }
  14754. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14755. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14756. // Effects
  14757. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14758. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14759. }
  14760. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14761. var arrayOffset = index * 15;
  14762. if (offsetX == 0)
  14763. offsetX = this._epsilon;
  14764. else if (offsetX == 1)
  14765. offsetX = 1 - this._epsilon;
  14766. if (offsetY == 0)
  14767. offsetY = this._epsilon;
  14768. else if (offsetY == 1)
  14769. offsetY = 1 - this._epsilon;
  14770. this._vertices[arrayOffset] = sprite.position.x;
  14771. this._vertices[arrayOffset + 1] = sprite.position.y;
  14772. this._vertices[arrayOffset + 2] = sprite.position.z;
  14773. this._vertices[arrayOffset + 3] = sprite.angle;
  14774. this._vertices[arrayOffset + 4] = sprite.size;
  14775. this._vertices[arrayOffset + 5] = offsetX;
  14776. this._vertices[arrayOffset + 6] = offsetY;
  14777. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14778. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14779. var offset = (sprite.cellIndex / rowSize) >> 0;
  14780. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14781. this._vertices[arrayOffset + 10] = offset;
  14782. // Color
  14783. this._vertices[arrayOffset + 11] = sprite.color.r;
  14784. this._vertices[arrayOffset + 12] = sprite.color.g;
  14785. this._vertices[arrayOffset + 13] = sprite.color.b;
  14786. this._vertices[arrayOffset + 14] = sprite.color.a;
  14787. };
  14788. SpriteManager.prototype.render = function () {
  14789. // Check
  14790. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14791. return;
  14792. var engine = this._scene.getEngine();
  14793. var baseSize = this._spriteTexture.getBaseSize();
  14794. // Sprites
  14795. var deltaTime = engine.getDeltaTime();
  14796. var max = Math.min(this._capacity, this.sprites.length);
  14797. var rowSize = baseSize.width / this.cellSize;
  14798. var offset = 0;
  14799. for (var index = 0; index < max; index++) {
  14800. var sprite = this.sprites[index];
  14801. if (!sprite) {
  14802. continue;
  14803. }
  14804. sprite._animate(deltaTime);
  14805. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14806. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14807. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14808. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14809. }
  14810. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14811. // Render
  14812. var effect = this._effectBase;
  14813. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14814. effect = this._effectFog;
  14815. }
  14816. engine.enableEffect(effect);
  14817. var viewMatrix = this._scene.getViewMatrix();
  14818. effect.setTexture("diffuseSampler", this._spriteTexture);
  14819. effect.setMatrix("view", viewMatrix);
  14820. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14821. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14822. // Fog
  14823. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14824. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14825. effect.setColor3("vFogColor", this._scene.fogColor);
  14826. }
  14827. // VBOs
  14828. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14829. // Draw order
  14830. effect.setBool("alphaTest", true);
  14831. engine.setColorWrite(false);
  14832. engine.draw(true, 0, max * 6);
  14833. engine.setColorWrite(true);
  14834. effect.setBool("alphaTest", false);
  14835. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14836. engine.draw(true, 0, max * 6);
  14837. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14838. };
  14839. SpriteManager.prototype.dispose = function () {
  14840. if (this._vertexBuffer) {
  14841. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14842. this._vertexBuffer = null;
  14843. }
  14844. if (this._indexBuffer) {
  14845. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14846. this._indexBuffer = null;
  14847. }
  14848. if (this._spriteTexture) {
  14849. this._spriteTexture.dispose();
  14850. this._spriteTexture = null;
  14851. }
  14852. // Remove from scene
  14853. var index = this._scene.spriteManagers.indexOf(this);
  14854. this._scene.spriteManagers.splice(index, 1);
  14855. // Callback
  14856. if (this.onDispose) {
  14857. this.onDispose();
  14858. }
  14859. };
  14860. return SpriteManager;
  14861. })();
  14862. BABYLON.SpriteManager = SpriteManager;
  14863. })(BABYLON || (BABYLON = {}));
  14864. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14865. (function (BABYLON) {
  14866. var Sprite = (function () {
  14867. function Sprite(name, manager) {
  14868. this.name = name;
  14869. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14870. this.size = 1.0;
  14871. this.angle = 0;
  14872. this.cellIndex = 0;
  14873. this.invertU = 0;
  14874. this.invertV = 0;
  14875. this.animations = new Array();
  14876. this._animationStarted = false;
  14877. this._loopAnimation = false;
  14878. this._fromIndex = 0;
  14879. this._toIndex = 0;
  14880. this._delay = 0;
  14881. this._direction = 1;
  14882. this._frameCount = 0;
  14883. this._time = 0;
  14884. this._manager = manager;
  14885. this._manager.sprites.push(this);
  14886. this.position = BABYLON.Vector3.Zero();
  14887. }
  14888. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14889. this._fromIndex = from;
  14890. this._toIndex = to;
  14891. this._loopAnimation = loop;
  14892. this._delay = delay;
  14893. this._animationStarted = true;
  14894. this._direction = from < to ? 1 : -1;
  14895. this.cellIndex = from;
  14896. this._time = 0;
  14897. };
  14898. Sprite.prototype.stopAnimation = function () {
  14899. this._animationStarted = false;
  14900. };
  14901. Sprite.prototype._animate = function (deltaTime) {
  14902. if (!this._animationStarted)
  14903. return;
  14904. this._time += deltaTime;
  14905. if (this._time > this._delay) {
  14906. this._time = this._time % this._delay;
  14907. this.cellIndex += this._direction;
  14908. if (this.cellIndex == this._toIndex) {
  14909. if (this._loopAnimation) {
  14910. this.cellIndex = this._fromIndex;
  14911. }
  14912. else {
  14913. this._animationStarted = false;
  14914. if (this.disposeWhenFinishedAnimating) {
  14915. this.dispose();
  14916. }
  14917. }
  14918. }
  14919. }
  14920. };
  14921. Sprite.prototype.dispose = function () {
  14922. for (var i = 0; i < this._manager.sprites.length; i++) {
  14923. if (this._manager.sprites[i] == this) {
  14924. this._manager.sprites.splice(i, 1);
  14925. }
  14926. }
  14927. };
  14928. return Sprite;
  14929. })();
  14930. BABYLON.Sprite = Sprite;
  14931. })(BABYLON || (BABYLON = {}));
  14932. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14933. (function (BABYLON) {
  14934. var Layer = (function () {
  14935. function Layer(name, imgUrl, scene, isBackground, color) {
  14936. this.name = name;
  14937. this._vertexDeclaration = [2];
  14938. this._vertexStrideSize = 2 * 4;
  14939. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14940. this.isBackground = isBackground === undefined ? true : isBackground;
  14941. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14942. this._scene = scene;
  14943. this._scene.layers.push(this);
  14944. // VBO
  14945. var vertices = [];
  14946. vertices.push(1, 1);
  14947. vertices.push(-1, 1);
  14948. vertices.push(-1, -1);
  14949. vertices.push(1, -1);
  14950. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14951. // Indices
  14952. var indices = [];
  14953. indices.push(0);
  14954. indices.push(1);
  14955. indices.push(2);
  14956. indices.push(0);
  14957. indices.push(2);
  14958. indices.push(3);
  14959. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14960. // Effects
  14961. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14962. }
  14963. Layer.prototype.render = function () {
  14964. // Check
  14965. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14966. return;
  14967. var engine = this._scene.getEngine();
  14968. // Render
  14969. engine.enableEffect(this._effect);
  14970. engine.setState(false);
  14971. // Texture
  14972. this._effect.setTexture("textureSampler", this.texture);
  14973. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14974. // Color
  14975. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14976. // VBOs
  14977. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14978. // Draw order
  14979. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14980. engine.draw(true, 0, 6);
  14981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14982. };
  14983. Layer.prototype.dispose = function () {
  14984. if (this._vertexBuffer) {
  14985. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14986. this._vertexBuffer = null;
  14987. }
  14988. if (this._indexBuffer) {
  14989. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14990. this._indexBuffer = null;
  14991. }
  14992. if (this.texture) {
  14993. this.texture.dispose();
  14994. this.texture = null;
  14995. }
  14996. // Remove from scene
  14997. var index = this._scene.layers.indexOf(this);
  14998. this._scene.layers.splice(index, 1);
  14999. // Callback
  15000. if (this.onDispose) {
  15001. this.onDispose();
  15002. }
  15003. };
  15004. return Layer;
  15005. })();
  15006. BABYLON.Layer = Layer;
  15007. })(BABYLON || (BABYLON = {}));
  15008. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15009. (function (BABYLON) {
  15010. var Particle = (function () {
  15011. function Particle() {
  15012. this.position = BABYLON.Vector3.Zero();
  15013. this.direction = BABYLON.Vector3.Zero();
  15014. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15015. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15016. this.lifeTime = 1.0;
  15017. this.age = 0;
  15018. this.size = 0;
  15019. this.angle = 0;
  15020. this.angularSpeed = 0;
  15021. }
  15022. Particle.prototype.copyTo = function (other) {
  15023. other.position.copyFrom(this.position);
  15024. other.direction.copyFrom(this.direction);
  15025. other.color.copyFrom(this.color);
  15026. other.colorStep.copyFrom(this.colorStep);
  15027. other.lifeTime = this.lifeTime;
  15028. other.age = this.age;
  15029. other.size = this.size;
  15030. other.angle = this.angle;
  15031. other.angularSpeed = this.angularSpeed;
  15032. };
  15033. return Particle;
  15034. })();
  15035. BABYLON.Particle = Particle;
  15036. })(BABYLON || (BABYLON = {}));
  15037. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15038. (function (BABYLON) {
  15039. var randomNumber = function (min, max) {
  15040. if (min === max) {
  15041. return (min);
  15042. }
  15043. var random = Math.random();
  15044. return ((random * (max - min)) + min);
  15045. };
  15046. var ParticleSystem = (function () {
  15047. function ParticleSystem(name, capacity, scene, customEffect) {
  15048. var _this = this;
  15049. this.name = name;
  15050. this.renderingGroupId = 0;
  15051. this.emitter = null;
  15052. this.emitRate = 10;
  15053. this.manualEmitCount = -1;
  15054. this.updateSpeed = 0.01;
  15055. this.targetStopDuration = 0;
  15056. this.disposeOnStop = false;
  15057. this.minEmitPower = 1;
  15058. this.maxEmitPower = 1;
  15059. this.minLifeTime = 1;
  15060. this.maxLifeTime = 1;
  15061. this.minSize = 1;
  15062. this.maxSize = 1;
  15063. this.minAngularSpeed = 0;
  15064. this.maxAngularSpeed = 0;
  15065. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15066. this.forceDepthWrite = false;
  15067. this.gravity = BABYLON.Vector3.Zero();
  15068. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15069. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15070. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15071. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15072. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15073. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15074. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15075. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15076. this.particles = new Array();
  15077. this._vertexDeclaration = [3, 4, 4];
  15078. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15079. this._stockParticles = new Array();
  15080. this._newPartsExcess = 0;
  15081. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15082. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15083. this._scaledDirection = BABYLON.Vector3.Zero();
  15084. this._scaledGravity = BABYLON.Vector3.Zero();
  15085. this._currentRenderId = -1;
  15086. this._started = false;
  15087. this._stopped = false;
  15088. this._actualFrame = 0;
  15089. this.id = name;
  15090. this._capacity = capacity;
  15091. this._scene = scene;
  15092. this._customEffect = customEffect;
  15093. scene.particleSystems.push(this);
  15094. // VBO
  15095. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15096. var indices = [];
  15097. var index = 0;
  15098. for (var count = 0; count < capacity; count++) {
  15099. indices.push(index);
  15100. indices.push(index + 1);
  15101. indices.push(index + 2);
  15102. indices.push(index);
  15103. indices.push(index + 2);
  15104. indices.push(index + 3);
  15105. index += 4;
  15106. }
  15107. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15108. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15109. // Default behaviors
  15110. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15111. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15112. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15113. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15114. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15115. };
  15116. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15117. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15118. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15119. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15120. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15121. };
  15122. this.updateFunction = function (particles) {
  15123. for (var index = 0; index < particles.length; index++) {
  15124. var particle = particles[index];
  15125. particle.age += _this._scaledUpdateSpeed;
  15126. if (particle.age >= particle.lifeTime) {
  15127. _this.recycleParticle(particle);
  15128. index--;
  15129. continue;
  15130. }
  15131. else {
  15132. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15133. particle.color.addInPlace(_this._scaledColorStep);
  15134. if (particle.color.a < 0)
  15135. particle.color.a = 0;
  15136. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15137. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15138. particle.position.addInPlace(_this._scaledDirection);
  15139. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15140. particle.direction.addInPlace(_this._scaledGravity);
  15141. }
  15142. }
  15143. };
  15144. }
  15145. ParticleSystem.prototype.recycleParticle = function (particle) {
  15146. var lastParticle = this.particles.pop();
  15147. if (lastParticle !== particle) {
  15148. lastParticle.copyTo(particle);
  15149. this._stockParticles.push(lastParticle);
  15150. }
  15151. };
  15152. ParticleSystem.prototype.getCapacity = function () {
  15153. return this._capacity;
  15154. };
  15155. ParticleSystem.prototype.isAlive = function () {
  15156. return this._alive;
  15157. };
  15158. ParticleSystem.prototype.isStarted = function () {
  15159. return this._started;
  15160. };
  15161. ParticleSystem.prototype.start = function () {
  15162. this._started = true;
  15163. this._stopped = false;
  15164. this._actualFrame = 0;
  15165. };
  15166. ParticleSystem.prototype.stop = function () {
  15167. this._stopped = true;
  15168. };
  15169. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15170. var offset = index * 11;
  15171. this._vertices[offset] = particle.position.x;
  15172. this._vertices[offset + 1] = particle.position.y;
  15173. this._vertices[offset + 2] = particle.position.z;
  15174. this._vertices[offset + 3] = particle.color.r;
  15175. this._vertices[offset + 4] = particle.color.g;
  15176. this._vertices[offset + 5] = particle.color.b;
  15177. this._vertices[offset + 6] = particle.color.a;
  15178. this._vertices[offset + 7] = particle.angle;
  15179. this._vertices[offset + 8] = particle.size;
  15180. this._vertices[offset + 9] = offsetX;
  15181. this._vertices[offset + 10] = offsetY;
  15182. };
  15183. ParticleSystem.prototype._update = function (newParticles) {
  15184. // Update current
  15185. this._alive = this.particles.length > 0;
  15186. this.updateFunction(this.particles);
  15187. // Add new ones
  15188. var worldMatrix;
  15189. if (this.emitter.position) {
  15190. worldMatrix = this.emitter.getWorldMatrix();
  15191. }
  15192. else {
  15193. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15194. }
  15195. for (var index = 0; index < newParticles; index++) {
  15196. if (this.particles.length === this._capacity) {
  15197. break;
  15198. }
  15199. if (this._stockParticles.length !== 0) {
  15200. var particle = this._stockParticles.pop();
  15201. particle.age = 0;
  15202. }
  15203. else {
  15204. particle = new BABYLON.Particle();
  15205. }
  15206. this.particles.push(particle);
  15207. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15208. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15209. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15210. particle.size = randomNumber(this.minSize, this.maxSize);
  15211. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15212. this.startPositionFunction(worldMatrix, particle.position);
  15213. var step = randomNumber(0, 1.0);
  15214. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15215. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15216. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15217. }
  15218. };
  15219. ParticleSystem.prototype._getEffect = function () {
  15220. if (this._customEffect) {
  15221. return this._customEffect;
  15222. }
  15223. ;
  15224. var defines = [];
  15225. if (this._scene.clipPlane) {
  15226. defines.push("#define CLIPPLANE");
  15227. }
  15228. // Effect
  15229. var join = defines.join("\n");
  15230. if (this._cachedDefines !== join) {
  15231. this._cachedDefines = join;
  15232. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15233. }
  15234. return this._effect;
  15235. };
  15236. ParticleSystem.prototype.animate = function () {
  15237. if (!this._started)
  15238. return;
  15239. var effect = this._getEffect();
  15240. // Check
  15241. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15242. return;
  15243. if (this._currentRenderId === this._scene.getRenderId()) {
  15244. return;
  15245. }
  15246. this._currentRenderId = this._scene.getRenderId();
  15247. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15248. // determine the number of particles we need to create
  15249. var emitCout;
  15250. if (this.manualEmitCount > -1) {
  15251. emitCout = this.manualEmitCount;
  15252. this.manualEmitCount = 0;
  15253. }
  15254. else {
  15255. emitCout = this.emitRate;
  15256. }
  15257. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15258. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15259. if (this._newPartsExcess > 1.0) {
  15260. newParticles += this._newPartsExcess >> 0;
  15261. this._newPartsExcess -= this._newPartsExcess >> 0;
  15262. }
  15263. this._alive = false;
  15264. if (!this._stopped) {
  15265. this._actualFrame += this._scaledUpdateSpeed;
  15266. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15267. this.stop();
  15268. }
  15269. else {
  15270. newParticles = 0;
  15271. }
  15272. this._update(newParticles);
  15273. // Stopped?
  15274. if (this._stopped) {
  15275. if (!this._alive) {
  15276. this._started = false;
  15277. if (this.disposeOnStop) {
  15278. this._scene._toBeDisposed.push(this);
  15279. }
  15280. }
  15281. }
  15282. // Update VBO
  15283. var offset = 0;
  15284. for (var index = 0; index < this.particles.length; index++) {
  15285. var particle = this.particles[index];
  15286. this._appendParticleVertex(offset++, particle, 0, 0);
  15287. this._appendParticleVertex(offset++, particle, 1, 0);
  15288. this._appendParticleVertex(offset++, particle, 1, 1);
  15289. this._appendParticleVertex(offset++, particle, 0, 1);
  15290. }
  15291. var engine = this._scene.getEngine();
  15292. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15293. };
  15294. ParticleSystem.prototype.render = function () {
  15295. var effect = this._getEffect();
  15296. // Check
  15297. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15298. return 0;
  15299. var engine = this._scene.getEngine();
  15300. // Render
  15301. engine.enableEffect(effect);
  15302. engine.setState(false);
  15303. var viewMatrix = this._scene.getViewMatrix();
  15304. effect.setTexture("diffuseSampler", this.particleTexture);
  15305. effect.setMatrix("view", viewMatrix);
  15306. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15307. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15308. if (this._scene.clipPlane) {
  15309. var clipPlane = this._scene.clipPlane;
  15310. var invView = viewMatrix.clone();
  15311. invView.invert();
  15312. effect.setMatrix("invView", invView);
  15313. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15314. }
  15315. // VBOs
  15316. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15317. // Draw order
  15318. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15319. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15320. }
  15321. else {
  15322. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15323. }
  15324. if (this.forceDepthWrite) {
  15325. engine.setDepthWrite(true);
  15326. }
  15327. engine.draw(true, 0, this.particles.length * 6);
  15328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15329. return this.particles.length;
  15330. };
  15331. ParticleSystem.prototype.dispose = function () {
  15332. if (this._vertexBuffer) {
  15333. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15334. this._vertexBuffer = null;
  15335. }
  15336. if (this._indexBuffer) {
  15337. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15338. this._indexBuffer = null;
  15339. }
  15340. if (this.particleTexture) {
  15341. this.particleTexture.dispose();
  15342. this.particleTexture = null;
  15343. }
  15344. // Remove from scene
  15345. var index = this._scene.particleSystems.indexOf(this);
  15346. this._scene.particleSystems.splice(index, 1);
  15347. // Callback
  15348. if (this.onDispose) {
  15349. this.onDispose();
  15350. }
  15351. };
  15352. // Clone
  15353. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15354. var result = new ParticleSystem(name, this._capacity, this._scene);
  15355. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15356. if (newEmitter === undefined) {
  15357. newEmitter = this.emitter;
  15358. }
  15359. result.emitter = newEmitter;
  15360. if (this.particleTexture) {
  15361. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15362. }
  15363. result.start();
  15364. return result;
  15365. };
  15366. // Statics
  15367. ParticleSystem.BLENDMODE_ONEONE = 0;
  15368. ParticleSystem.BLENDMODE_STANDARD = 1;
  15369. return ParticleSystem;
  15370. })();
  15371. BABYLON.ParticleSystem = ParticleSystem;
  15372. })(BABYLON || (BABYLON = {}));
  15373. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15374. (function (BABYLON) {
  15375. var Animation = (function () {
  15376. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15377. this.name = name;
  15378. this.targetProperty = targetProperty;
  15379. this.framePerSecond = framePerSecond;
  15380. this.dataType = dataType;
  15381. this.loopMode = loopMode;
  15382. this._offsetsCache = {};
  15383. this._highLimitsCache = {};
  15384. this._stopped = false;
  15385. this.targetPropertyPath = targetProperty.split(".");
  15386. this.dataType = dataType;
  15387. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15388. }
  15389. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15390. var dataType = undefined;
  15391. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15392. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15393. }
  15394. else if (from instanceof BABYLON.Quaternion) {
  15395. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15396. }
  15397. else if (from instanceof BABYLON.Vector3) {
  15398. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15399. }
  15400. else if (from instanceof BABYLON.Vector2) {
  15401. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15402. }
  15403. else if (from instanceof BABYLON.Color3) {
  15404. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15405. }
  15406. if (dataType == undefined) {
  15407. return null;
  15408. }
  15409. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15410. var keys = [];
  15411. keys.push({ frame: 0, value: from });
  15412. keys.push({ frame: totalFrame, value: to });
  15413. animation.setKeys(keys);
  15414. mesh.animations.push(animation);
  15415. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15416. };
  15417. // Methods
  15418. Animation.prototype.isStopped = function () {
  15419. return this._stopped;
  15420. };
  15421. Animation.prototype.getKeys = function () {
  15422. return this._keys;
  15423. };
  15424. Animation.prototype.getEasingFunction = function () {
  15425. return this._easingFunction;
  15426. };
  15427. Animation.prototype.setEasingFunction = function (easingFunction) {
  15428. this._easingFunction = easingFunction;
  15429. };
  15430. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15431. return startValue + (endValue - startValue) * gradient;
  15432. };
  15433. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15434. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15435. };
  15436. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15437. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15438. };
  15439. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15440. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15441. };
  15442. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15443. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15444. };
  15445. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15446. var startScale = new BABYLON.Vector3(0, 0, 0);
  15447. var startRotation = new BABYLON.Quaternion();
  15448. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15449. startValue.decompose(startScale, startRotation, startTranslation);
  15450. var endScale = new BABYLON.Vector3(0, 0, 0);
  15451. var endRotation = new BABYLON.Quaternion();
  15452. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15453. endValue.decompose(endScale, endRotation, endTranslation);
  15454. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15455. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15456. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15457. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15458. return result;
  15459. };
  15460. Animation.prototype.clone = function () {
  15461. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15462. clone.setKeys(this._keys);
  15463. return clone;
  15464. };
  15465. Animation.prototype.setKeys = function (values) {
  15466. this._keys = values.slice(0);
  15467. this._offsetsCache = {};
  15468. this._highLimitsCache = {};
  15469. };
  15470. Animation.prototype._getKeyValue = function (value) {
  15471. if (typeof value === "function") {
  15472. return value();
  15473. }
  15474. return value;
  15475. };
  15476. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15477. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15478. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15479. }
  15480. this.currentFrame = currentFrame;
  15481. for (var key = 0; key < this._keys.length; key++) {
  15482. // for each frame, we need the key just before the frame superior
  15483. if (this._keys[key + 1].frame >= currentFrame) {
  15484. var startValue = this._getKeyValue(this._keys[key].value);
  15485. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15486. // gradient : percent of currentFrame between the frame inf and the frame sup
  15487. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15488. // check for easingFunction and correction of gradient
  15489. if (this._easingFunction != null) {
  15490. gradient = this._easingFunction.ease(gradient);
  15491. }
  15492. switch (this.dataType) {
  15493. case Animation.ANIMATIONTYPE_FLOAT:
  15494. switch (loopMode) {
  15495. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15496. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15497. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15498. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15499. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15500. }
  15501. break;
  15502. case Animation.ANIMATIONTYPE_QUATERNION:
  15503. var quaternion = null;
  15504. switch (loopMode) {
  15505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15507. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15508. break;
  15509. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15510. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15511. break;
  15512. }
  15513. return quaternion;
  15514. case Animation.ANIMATIONTYPE_VECTOR3:
  15515. switch (loopMode) {
  15516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15518. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15519. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15520. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15521. }
  15522. case Animation.ANIMATIONTYPE_VECTOR2:
  15523. switch (loopMode) {
  15524. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15525. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15526. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15527. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15528. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15529. }
  15530. case Animation.ANIMATIONTYPE_COLOR3:
  15531. switch (loopMode) {
  15532. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15533. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15534. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15535. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15536. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15537. }
  15538. case Animation.ANIMATIONTYPE_MATRIX:
  15539. switch (loopMode) {
  15540. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15541. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15542. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15543. return startValue;
  15544. }
  15545. default:
  15546. break;
  15547. }
  15548. break;
  15549. }
  15550. }
  15551. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15552. };
  15553. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15554. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15555. this._stopped = true;
  15556. return false;
  15557. }
  15558. var returnValue = true;
  15559. // Adding a start key at frame 0 if missing
  15560. if (this._keys[0].frame !== 0) {
  15561. var newKey = { frame: 0, value: this._keys[0].value };
  15562. this._keys.splice(0, 0, newKey);
  15563. }
  15564. // Check limits
  15565. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15566. from = this._keys[0].frame;
  15567. }
  15568. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15569. to = this._keys[this._keys.length - 1].frame;
  15570. }
  15571. // Compute ratio
  15572. var range = to - from;
  15573. var offsetValue;
  15574. // ratio represents the frame delta between from and to
  15575. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15576. var highLimitValue = 0;
  15577. if (ratio > range && !loop) {
  15578. returnValue = false;
  15579. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15580. }
  15581. else {
  15582. // Get max value if required
  15583. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15584. var keyOffset = to.toString() + from.toString();
  15585. if (!this._offsetsCache[keyOffset]) {
  15586. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15587. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15588. switch (this.dataType) {
  15589. case Animation.ANIMATIONTYPE_FLOAT:
  15590. this._offsetsCache[keyOffset] = toValue - fromValue;
  15591. break;
  15592. case Animation.ANIMATIONTYPE_QUATERNION:
  15593. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15594. break;
  15595. case Animation.ANIMATIONTYPE_VECTOR3:
  15596. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15597. case Animation.ANIMATIONTYPE_VECTOR2:
  15598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15599. case Animation.ANIMATIONTYPE_COLOR3:
  15600. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15601. default:
  15602. break;
  15603. }
  15604. this._highLimitsCache[keyOffset] = toValue;
  15605. }
  15606. highLimitValue = this._highLimitsCache[keyOffset];
  15607. offsetValue = this._offsetsCache[keyOffset];
  15608. }
  15609. }
  15610. if (offsetValue === undefined) {
  15611. switch (this.dataType) {
  15612. case Animation.ANIMATIONTYPE_FLOAT:
  15613. offsetValue = 0;
  15614. break;
  15615. case Animation.ANIMATIONTYPE_QUATERNION:
  15616. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15617. break;
  15618. case Animation.ANIMATIONTYPE_VECTOR3:
  15619. offsetValue = BABYLON.Vector3.Zero();
  15620. break;
  15621. case Animation.ANIMATIONTYPE_VECTOR2:
  15622. offsetValue = BABYLON.Vector2.Zero();
  15623. break;
  15624. case Animation.ANIMATIONTYPE_COLOR3:
  15625. offsetValue = BABYLON.Color3.Black();
  15626. }
  15627. }
  15628. // Compute value
  15629. var repeatCount = (ratio / range) >> 0;
  15630. var currentFrame = returnValue ? from + ratio % range : to;
  15631. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15632. // Set value
  15633. if (this.targetPropertyPath.length > 1) {
  15634. var property = this._target[this.targetPropertyPath[0]];
  15635. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15636. property = property[this.targetPropertyPath[index]];
  15637. }
  15638. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15639. }
  15640. else {
  15641. this._target[this.targetPropertyPath[0]] = currentValue;
  15642. }
  15643. if (this._target.markAsDirty) {
  15644. this._target.markAsDirty(this.targetProperty);
  15645. }
  15646. if (!returnValue) {
  15647. this._stopped = true;
  15648. }
  15649. return returnValue;
  15650. };
  15651. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15652. get: function () {
  15653. return Animation._ANIMATIONTYPE_FLOAT;
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15659. get: function () {
  15660. return Animation._ANIMATIONTYPE_VECTOR3;
  15661. },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15666. get: function () {
  15667. return Animation._ANIMATIONTYPE_VECTOR2;
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15673. get: function () {
  15674. return Animation._ANIMATIONTYPE_QUATERNION;
  15675. },
  15676. enumerable: true,
  15677. configurable: true
  15678. });
  15679. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15680. get: function () {
  15681. return Animation._ANIMATIONTYPE_MATRIX;
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15687. get: function () {
  15688. return Animation._ANIMATIONTYPE_COLOR3;
  15689. },
  15690. enumerable: true,
  15691. configurable: true
  15692. });
  15693. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15694. get: function () {
  15695. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15696. },
  15697. enumerable: true,
  15698. configurable: true
  15699. });
  15700. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15701. get: function () {
  15702. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15703. },
  15704. enumerable: true,
  15705. configurable: true
  15706. });
  15707. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15708. get: function () {
  15709. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. // Statics
  15715. Animation._ANIMATIONTYPE_FLOAT = 0;
  15716. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15717. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15718. Animation._ANIMATIONTYPE_MATRIX = 3;
  15719. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15720. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15721. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15722. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15723. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15724. return Animation;
  15725. })();
  15726. BABYLON.Animation = Animation;
  15727. })(BABYLON || (BABYLON = {}));
  15728. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15729. (function (BABYLON) {
  15730. var Animatable = (function () {
  15731. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15732. if (fromFrame === void 0) { fromFrame = 0; }
  15733. if (toFrame === void 0) { toFrame = 100; }
  15734. if (loopAnimation === void 0) { loopAnimation = false; }
  15735. if (speedRatio === void 0) { speedRatio = 1.0; }
  15736. this.target = target;
  15737. this.fromFrame = fromFrame;
  15738. this.toFrame = toFrame;
  15739. this.loopAnimation = loopAnimation;
  15740. this.speedRatio = speedRatio;
  15741. this.onAnimationEnd = onAnimationEnd;
  15742. this._animations = new Array();
  15743. this._paused = false;
  15744. this.animationStarted = false;
  15745. if (animations) {
  15746. this.appendAnimations(target, animations);
  15747. }
  15748. this._scene = scene;
  15749. scene._activeAnimatables.push(this);
  15750. }
  15751. // Methods
  15752. Animatable.prototype.appendAnimations = function (target, animations) {
  15753. for (var index = 0; index < animations.length; index++) {
  15754. var animation = animations[index];
  15755. animation._target = target;
  15756. this._animations.push(animation);
  15757. }
  15758. };
  15759. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15760. var animations = this._animations;
  15761. for (var index = 0; index < animations.length; index++) {
  15762. if (animations[index].targetProperty === property) {
  15763. return animations[index];
  15764. }
  15765. }
  15766. return null;
  15767. };
  15768. Animatable.prototype.pause = function () {
  15769. if (this._paused) {
  15770. return;
  15771. }
  15772. this._paused = true;
  15773. };
  15774. Animatable.prototype.restart = function () {
  15775. this._paused = false;
  15776. };
  15777. Animatable.prototype.stop = function () {
  15778. var index = this._scene._activeAnimatables.indexOf(this);
  15779. if (index > -1) {
  15780. this._scene._activeAnimatables.splice(index, 1);
  15781. }
  15782. if (this.onAnimationEnd) {
  15783. this.onAnimationEnd();
  15784. }
  15785. };
  15786. Animatable.prototype._animate = function (delay) {
  15787. if (this._paused) {
  15788. if (!this._pausedDelay) {
  15789. this._pausedDelay = delay;
  15790. }
  15791. return true;
  15792. }
  15793. if (!this._localDelayOffset) {
  15794. this._localDelayOffset = delay;
  15795. }
  15796. else if (this._pausedDelay) {
  15797. this._localDelayOffset += delay - this._pausedDelay;
  15798. this._pausedDelay = null;
  15799. }
  15800. // Animating
  15801. var running = false;
  15802. var animations = this._animations;
  15803. for (var index = 0; index < animations.length; index++) {
  15804. var animation = animations[index];
  15805. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15806. running = running || isRunning;
  15807. }
  15808. if (!running && this.onAnimationEnd) {
  15809. this.onAnimationEnd();
  15810. }
  15811. return running;
  15812. };
  15813. return Animatable;
  15814. })();
  15815. BABYLON.Animatable = Animatable;
  15816. })(BABYLON || (BABYLON = {}));
  15817. //# sourceMappingURL=babylon.animatable.js.map
  15818. var BABYLON;
  15819. (function (BABYLON) {
  15820. var EasingFunction = (function () {
  15821. function EasingFunction() {
  15822. // Properties
  15823. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15824. }
  15825. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15826. get: function () {
  15827. return EasingFunction._EASINGMODE_EASEIN;
  15828. },
  15829. enumerable: true,
  15830. configurable: true
  15831. });
  15832. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15833. get: function () {
  15834. return EasingFunction._EASINGMODE_EASEOUT;
  15835. },
  15836. enumerable: true,
  15837. configurable: true
  15838. });
  15839. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15840. get: function () {
  15841. return EasingFunction._EASINGMODE_EASEINOUT;
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15847. var n = Math.min(Math.max(easingMode, 0), 2);
  15848. this._easingMode = n;
  15849. };
  15850. EasingFunction.prototype.getEasingMode = function () {
  15851. return this._easingMode;
  15852. };
  15853. EasingFunction.prototype.easeInCore = function (gradient) {
  15854. throw new Error('You must implement this method');
  15855. };
  15856. EasingFunction.prototype.ease = function (gradient) {
  15857. switch (this._easingMode) {
  15858. case EasingFunction.EASINGMODE_EASEIN:
  15859. return this.easeInCore(gradient);
  15860. case EasingFunction.EASINGMODE_EASEOUT:
  15861. return (1 - this.easeInCore(1 - gradient));
  15862. }
  15863. if (gradient >= 0.5) {
  15864. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15865. }
  15866. return (this.easeInCore(gradient * 2) * 0.5);
  15867. };
  15868. //Statics
  15869. EasingFunction._EASINGMODE_EASEIN = 0;
  15870. EasingFunction._EASINGMODE_EASEOUT = 1;
  15871. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15872. return EasingFunction;
  15873. })();
  15874. BABYLON.EasingFunction = EasingFunction;
  15875. var CircleEase = (function (_super) {
  15876. __extends(CircleEase, _super);
  15877. function CircleEase() {
  15878. _super.apply(this, arguments);
  15879. }
  15880. CircleEase.prototype.easeInCore = function (gradient) {
  15881. gradient = Math.max(0, Math.min(1, gradient));
  15882. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15883. };
  15884. return CircleEase;
  15885. })(EasingFunction);
  15886. BABYLON.CircleEase = CircleEase;
  15887. var BackEase = (function (_super) {
  15888. __extends(BackEase, _super);
  15889. function BackEase(amplitude) {
  15890. if (amplitude === void 0) { amplitude = 1; }
  15891. _super.call(this);
  15892. this.amplitude = amplitude;
  15893. }
  15894. BackEase.prototype.easeInCore = function (gradient) {
  15895. var num = Math.max(0, this.amplitude);
  15896. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15897. };
  15898. return BackEase;
  15899. })(EasingFunction);
  15900. BABYLON.BackEase = BackEase;
  15901. var BounceEase = (function (_super) {
  15902. __extends(BounceEase, _super);
  15903. function BounceEase(bounces, bounciness) {
  15904. if (bounces === void 0) { bounces = 3; }
  15905. if (bounciness === void 0) { bounciness = 2; }
  15906. _super.call(this);
  15907. this.bounces = bounces;
  15908. this.bounciness = bounciness;
  15909. }
  15910. BounceEase.prototype.easeInCore = function (gradient) {
  15911. var y = Math.max(0.0, this.bounces);
  15912. var bounciness = this.bounciness;
  15913. if (bounciness <= 1.0) {
  15914. bounciness = 1.001;
  15915. }
  15916. var num9 = Math.pow(bounciness, y);
  15917. var num5 = 1.0 - bounciness;
  15918. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15919. var num15 = gradient * num4;
  15920. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15921. var num3 = Math.floor(num65);
  15922. var num13 = num3 + 1.0;
  15923. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15924. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15925. var num7 = (num8 + num12) * 0.5;
  15926. var num6 = gradient - num7;
  15927. var num2 = num7 - num8;
  15928. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15929. };
  15930. return BounceEase;
  15931. })(EasingFunction);
  15932. BABYLON.BounceEase = BounceEase;
  15933. var CubicEase = (function (_super) {
  15934. __extends(CubicEase, _super);
  15935. function CubicEase() {
  15936. _super.apply(this, arguments);
  15937. }
  15938. CubicEase.prototype.easeInCore = function (gradient) {
  15939. return (gradient * gradient * gradient);
  15940. };
  15941. return CubicEase;
  15942. })(EasingFunction);
  15943. BABYLON.CubicEase = CubicEase;
  15944. var ElasticEase = (function (_super) {
  15945. __extends(ElasticEase, _super);
  15946. function ElasticEase(oscillations, springiness) {
  15947. if (oscillations === void 0) { oscillations = 3; }
  15948. if (springiness === void 0) { springiness = 3; }
  15949. _super.call(this);
  15950. this.oscillations = oscillations;
  15951. this.springiness = springiness;
  15952. }
  15953. ElasticEase.prototype.easeInCore = function (gradient) {
  15954. var num2;
  15955. var num3 = Math.max(0.0, this.oscillations);
  15956. var num = Math.max(0.0, this.springiness);
  15957. if (num == 0) {
  15958. num2 = gradient;
  15959. }
  15960. else {
  15961. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15962. }
  15963. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15964. };
  15965. return ElasticEase;
  15966. })(EasingFunction);
  15967. BABYLON.ElasticEase = ElasticEase;
  15968. var ExponentialEase = (function (_super) {
  15969. __extends(ExponentialEase, _super);
  15970. function ExponentialEase(exponent) {
  15971. if (exponent === void 0) { exponent = 2; }
  15972. _super.call(this);
  15973. this.exponent = exponent;
  15974. }
  15975. ExponentialEase.prototype.easeInCore = function (gradient) {
  15976. if (this.exponent <= 0) {
  15977. return gradient;
  15978. }
  15979. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15980. };
  15981. return ExponentialEase;
  15982. })(EasingFunction);
  15983. BABYLON.ExponentialEase = ExponentialEase;
  15984. var PowerEase = (function (_super) {
  15985. __extends(PowerEase, _super);
  15986. function PowerEase(power) {
  15987. if (power === void 0) { power = 2; }
  15988. _super.call(this);
  15989. this.power = power;
  15990. }
  15991. PowerEase.prototype.easeInCore = function (gradient) {
  15992. var y = Math.max(0.0, this.power);
  15993. return Math.pow(gradient, y);
  15994. };
  15995. return PowerEase;
  15996. })(EasingFunction);
  15997. BABYLON.PowerEase = PowerEase;
  15998. var QuadraticEase = (function (_super) {
  15999. __extends(QuadraticEase, _super);
  16000. function QuadraticEase() {
  16001. _super.apply(this, arguments);
  16002. }
  16003. QuadraticEase.prototype.easeInCore = function (gradient) {
  16004. return (gradient * gradient);
  16005. };
  16006. return QuadraticEase;
  16007. })(EasingFunction);
  16008. BABYLON.QuadraticEase = QuadraticEase;
  16009. var QuarticEase = (function (_super) {
  16010. __extends(QuarticEase, _super);
  16011. function QuarticEase() {
  16012. _super.apply(this, arguments);
  16013. }
  16014. QuarticEase.prototype.easeInCore = function (gradient) {
  16015. return (gradient * gradient * gradient * gradient);
  16016. };
  16017. return QuarticEase;
  16018. })(EasingFunction);
  16019. BABYLON.QuarticEase = QuarticEase;
  16020. var QuinticEase = (function (_super) {
  16021. __extends(QuinticEase, _super);
  16022. function QuinticEase() {
  16023. _super.apply(this, arguments);
  16024. }
  16025. QuinticEase.prototype.easeInCore = function (gradient) {
  16026. return (gradient * gradient * gradient * gradient * gradient);
  16027. };
  16028. return QuinticEase;
  16029. })(EasingFunction);
  16030. BABYLON.QuinticEase = QuinticEase;
  16031. var SineEase = (function (_super) {
  16032. __extends(SineEase, _super);
  16033. function SineEase() {
  16034. _super.apply(this, arguments);
  16035. }
  16036. SineEase.prototype.easeInCore = function (gradient) {
  16037. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16038. };
  16039. return SineEase;
  16040. })(EasingFunction);
  16041. BABYLON.SineEase = SineEase;
  16042. var BezierCurveEase = (function (_super) {
  16043. __extends(BezierCurveEase, _super);
  16044. function BezierCurveEase(x1, y1, x2, y2) {
  16045. if (x1 === void 0) { x1 = 0; }
  16046. if (y1 === void 0) { y1 = 0; }
  16047. if (x2 === void 0) { x2 = 1; }
  16048. if (y2 === void 0) { y2 = 1; }
  16049. _super.call(this);
  16050. this.x1 = x1;
  16051. this.y1 = y1;
  16052. this.x2 = x2;
  16053. this.y2 = y2;
  16054. }
  16055. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16056. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16057. };
  16058. return BezierCurveEase;
  16059. })(EasingFunction);
  16060. BABYLON.BezierCurveEase = BezierCurveEase;
  16061. })(BABYLON || (BABYLON = {}));
  16062. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16063. (function (BABYLON) {
  16064. var Octree = (function () {
  16065. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16066. if (maxDepth === void 0) { maxDepth = 2; }
  16067. this.maxDepth = maxDepth;
  16068. this.dynamicContent = new Array();
  16069. this._maxBlockCapacity = maxBlockCapacity || 64;
  16070. this._selectionContent = new BABYLON.SmartArray(1024);
  16071. this._creationFunc = creationFunc;
  16072. }
  16073. // Methods
  16074. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16075. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16076. };
  16077. Octree.prototype.addMesh = function (entry) {
  16078. for (var index = 0; index < this.blocks.length; index++) {
  16079. var block = this.blocks[index];
  16080. block.addEntry(entry);
  16081. }
  16082. };
  16083. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16084. this._selectionContent.reset();
  16085. for (var index = 0; index < this.blocks.length; index++) {
  16086. var block = this.blocks[index];
  16087. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16088. }
  16089. if (allowDuplicate) {
  16090. this._selectionContent.concat(this.dynamicContent);
  16091. }
  16092. else {
  16093. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16094. }
  16095. return this._selectionContent;
  16096. };
  16097. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16098. this._selectionContent.reset();
  16099. for (var index = 0; index < this.blocks.length; index++) {
  16100. var block = this.blocks[index];
  16101. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16102. }
  16103. if (allowDuplicate) {
  16104. this._selectionContent.concat(this.dynamicContent);
  16105. }
  16106. else {
  16107. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16108. }
  16109. return this._selectionContent;
  16110. };
  16111. Octree.prototype.intersectsRay = function (ray) {
  16112. this._selectionContent.reset();
  16113. for (var index = 0; index < this.blocks.length; index++) {
  16114. var block = this.blocks[index];
  16115. block.intersectsRay(ray, this._selectionContent);
  16116. }
  16117. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16118. return this._selectionContent;
  16119. };
  16120. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16121. target.blocks = new Array();
  16122. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16123. for (var x = 0; x < 2; x++) {
  16124. for (var y = 0; y < 2; y++) {
  16125. for (var z = 0; z < 2; z++) {
  16126. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16127. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16128. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16129. block.addEntries(entries);
  16130. target.blocks.push(block);
  16131. }
  16132. }
  16133. }
  16134. };
  16135. Octree.CreationFuncForMeshes = function (entry, block) {
  16136. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16137. block.entries.push(entry);
  16138. }
  16139. };
  16140. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16141. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16142. block.entries.push(entry);
  16143. }
  16144. };
  16145. return Octree;
  16146. })();
  16147. BABYLON.Octree = Octree;
  16148. })(BABYLON || (BABYLON = {}));
  16149. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16150. (function (BABYLON) {
  16151. var OctreeBlock = (function () {
  16152. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16153. this.entries = new Array();
  16154. this._boundingVectors = new Array();
  16155. this._capacity = capacity;
  16156. this._depth = depth;
  16157. this._maxDepth = maxDepth;
  16158. this._creationFunc = creationFunc;
  16159. this._minPoint = minPoint;
  16160. this._maxPoint = maxPoint;
  16161. this._boundingVectors.push(minPoint.clone());
  16162. this._boundingVectors.push(maxPoint.clone());
  16163. this._boundingVectors.push(minPoint.clone());
  16164. this._boundingVectors[2].x = maxPoint.x;
  16165. this._boundingVectors.push(minPoint.clone());
  16166. this._boundingVectors[3].y = maxPoint.y;
  16167. this._boundingVectors.push(minPoint.clone());
  16168. this._boundingVectors[4].z = maxPoint.z;
  16169. this._boundingVectors.push(maxPoint.clone());
  16170. this._boundingVectors[5].z = minPoint.z;
  16171. this._boundingVectors.push(maxPoint.clone());
  16172. this._boundingVectors[6].x = minPoint.x;
  16173. this._boundingVectors.push(maxPoint.clone());
  16174. this._boundingVectors[7].y = minPoint.y;
  16175. }
  16176. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16177. // Property
  16178. get: function () {
  16179. return this._capacity;
  16180. },
  16181. enumerable: true,
  16182. configurable: true
  16183. });
  16184. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16185. get: function () {
  16186. return this._minPoint;
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16192. get: function () {
  16193. return this._maxPoint;
  16194. },
  16195. enumerable: true,
  16196. configurable: true
  16197. });
  16198. // Methods
  16199. OctreeBlock.prototype.addEntry = function (entry) {
  16200. if (this.blocks) {
  16201. for (var index = 0; index < this.blocks.length; index++) {
  16202. var block = this.blocks[index];
  16203. block.addEntry(entry);
  16204. }
  16205. return;
  16206. }
  16207. this._creationFunc(entry, this);
  16208. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16209. this.createInnerBlocks();
  16210. }
  16211. };
  16212. OctreeBlock.prototype.addEntries = function (entries) {
  16213. for (var index = 0; index < entries.length; index++) {
  16214. var mesh = entries[index];
  16215. this.addEntry(mesh);
  16216. }
  16217. };
  16218. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16219. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16220. if (this.blocks) {
  16221. for (var index = 0; index < this.blocks.length; index++) {
  16222. var block = this.blocks[index];
  16223. block.select(frustumPlanes, selection, allowDuplicate);
  16224. }
  16225. return;
  16226. }
  16227. if (allowDuplicate) {
  16228. selection.concat(this.entries);
  16229. }
  16230. else {
  16231. selection.concatWithNoDuplicate(this.entries);
  16232. }
  16233. }
  16234. };
  16235. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16236. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16237. if (this.blocks) {
  16238. for (var index = 0; index < this.blocks.length; index++) {
  16239. var block = this.blocks[index];
  16240. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16241. }
  16242. return;
  16243. }
  16244. if (allowDuplicate) {
  16245. selection.concat(this.entries);
  16246. }
  16247. else {
  16248. selection.concatWithNoDuplicate(this.entries);
  16249. }
  16250. }
  16251. };
  16252. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16253. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16254. if (this.blocks) {
  16255. for (var index = 0; index < this.blocks.length; index++) {
  16256. var block = this.blocks[index];
  16257. block.intersectsRay(ray, selection);
  16258. }
  16259. return;
  16260. }
  16261. selection.concatWithNoDuplicate(this.entries);
  16262. }
  16263. };
  16264. OctreeBlock.prototype.createInnerBlocks = function () {
  16265. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16266. };
  16267. return OctreeBlock;
  16268. })();
  16269. BABYLON.OctreeBlock = OctreeBlock;
  16270. })(BABYLON || (BABYLON = {}));
  16271. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16272. (function (BABYLON) {
  16273. var Bone = (function () {
  16274. function Bone(name, skeleton, parentBone, matrix) {
  16275. this.name = name;
  16276. this.children = new Array();
  16277. this.animations = new Array();
  16278. this._worldTransform = new BABYLON.Matrix();
  16279. this._absoluteTransform = new BABYLON.Matrix();
  16280. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16281. this._skeleton = skeleton;
  16282. this._matrix = matrix;
  16283. this._baseMatrix = matrix;
  16284. skeleton.bones.push(this);
  16285. if (parentBone) {
  16286. this._parent = parentBone;
  16287. parentBone.children.push(this);
  16288. }
  16289. else {
  16290. this._parent = null;
  16291. }
  16292. this._updateDifferenceMatrix();
  16293. }
  16294. // Members
  16295. Bone.prototype.getParent = function () {
  16296. return this._parent;
  16297. };
  16298. Bone.prototype.getLocalMatrix = function () {
  16299. return this._matrix;
  16300. };
  16301. Bone.prototype.getBaseMatrix = function () {
  16302. return this._baseMatrix;
  16303. };
  16304. Bone.prototype.getWorldMatrix = function () {
  16305. return this._worldTransform;
  16306. };
  16307. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16308. return this._invertedAbsoluteTransform;
  16309. };
  16310. Bone.prototype.getAbsoluteMatrix = function () {
  16311. var matrix = this._matrix.clone();
  16312. var parent = this._parent;
  16313. while (parent) {
  16314. matrix = matrix.multiply(parent.getLocalMatrix());
  16315. parent = parent.getParent();
  16316. }
  16317. return matrix;
  16318. };
  16319. // Methods
  16320. Bone.prototype.updateMatrix = function (matrix) {
  16321. this._matrix = matrix;
  16322. this._skeleton._markAsDirty();
  16323. this._updateDifferenceMatrix();
  16324. };
  16325. Bone.prototype._updateDifferenceMatrix = function () {
  16326. if (this._parent) {
  16327. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16328. }
  16329. else {
  16330. this._absoluteTransform.copyFrom(this._matrix);
  16331. }
  16332. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16333. for (var index = 0; index < this.children.length; index++) {
  16334. this.children[index]._updateDifferenceMatrix();
  16335. }
  16336. };
  16337. Bone.prototype.markAsDirty = function () {
  16338. this._skeleton._markAsDirty();
  16339. };
  16340. return Bone;
  16341. })();
  16342. BABYLON.Bone = Bone;
  16343. })(BABYLON || (BABYLON = {}));
  16344. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16345. (function (BABYLON) {
  16346. var Skeleton = (function () {
  16347. function Skeleton(name, id, scene) {
  16348. this.name = name;
  16349. this.id = id;
  16350. this.bones = new Array();
  16351. this._isDirty = true;
  16352. this._identity = BABYLON.Matrix.Identity();
  16353. this.bones = [];
  16354. this._scene = scene;
  16355. scene.skeletons.push(this);
  16356. }
  16357. // Members
  16358. Skeleton.prototype.getTransformMatrices = function () {
  16359. return this._transformMatrices;
  16360. };
  16361. // Methods
  16362. Skeleton.prototype._markAsDirty = function () {
  16363. this._isDirty = true;
  16364. };
  16365. Skeleton.prototype.prepare = function () {
  16366. if (!this._isDirty) {
  16367. return;
  16368. }
  16369. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16370. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16371. }
  16372. for (var index = 0; index < this.bones.length; index++) {
  16373. var bone = this.bones[index];
  16374. var parentBone = bone.getParent();
  16375. if (parentBone) {
  16376. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16377. }
  16378. else {
  16379. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16380. }
  16381. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16382. }
  16383. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16384. this._isDirty = false;
  16385. this._scene._activeBones += this.bones.length;
  16386. };
  16387. Skeleton.prototype.getAnimatables = function () {
  16388. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16389. this._animatables = [];
  16390. for (var index = 0; index < this.bones.length; index++) {
  16391. this._animatables.push(this.bones[index]);
  16392. }
  16393. }
  16394. return this._animatables;
  16395. };
  16396. Skeleton.prototype.clone = function (name, id) {
  16397. var result = new Skeleton(name, id || name, this._scene);
  16398. for (var index = 0; index < this.bones.length; index++) {
  16399. var source = this.bones[index];
  16400. var parentBone = null;
  16401. if (source.getParent()) {
  16402. var parentIndex = this.bones.indexOf(source.getParent());
  16403. parentBone = result.bones[parentIndex];
  16404. }
  16405. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16406. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16407. }
  16408. return result;
  16409. };
  16410. return Skeleton;
  16411. })();
  16412. BABYLON.Skeleton = Skeleton;
  16413. })(BABYLON || (BABYLON = {}));
  16414. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16415. (function (BABYLON) {
  16416. var PostProcess = (function () {
  16417. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16418. this.name = name;
  16419. this.width = -1;
  16420. this.height = -1;
  16421. this._reusable = false;
  16422. this._textures = new BABYLON.SmartArray(2);
  16423. this._currentRenderTextureInd = 0;
  16424. if (camera != null) {
  16425. this._camera = camera;
  16426. this._scene = camera.getScene();
  16427. camera.attachPostProcess(this);
  16428. this._engine = this._scene.getEngine();
  16429. }
  16430. else {
  16431. this._engine = engine;
  16432. }
  16433. this._renderRatio = ratio;
  16434. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16435. this._reusable = reusable || false;
  16436. samplers = samplers || [];
  16437. samplers.push("textureSampler");
  16438. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16439. }
  16440. PostProcess.prototype.isReusable = function () {
  16441. return this._reusable;
  16442. };
  16443. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16444. camera = camera || this._camera;
  16445. var scene = camera.getScene();
  16446. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16447. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16448. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16449. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16450. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16451. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16452. if (this._textures.length > 0) {
  16453. for (var i = 0; i < this._textures.length; i++) {
  16454. this._engine._releaseTexture(this._textures.data[i]);
  16455. }
  16456. this._textures.reset();
  16457. }
  16458. this.width = desiredWidth;
  16459. this.height = desiredHeight;
  16460. 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 }));
  16461. if (this._reusable) {
  16462. 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 }));
  16463. }
  16464. if (this.onSizeChanged) {
  16465. this.onSizeChanged();
  16466. }
  16467. }
  16468. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16469. if (this.onActivate) {
  16470. this.onActivate(camera);
  16471. }
  16472. // Clear
  16473. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16474. if (this._reusable) {
  16475. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16476. }
  16477. };
  16478. PostProcess.prototype.apply = function () {
  16479. // Check
  16480. if (!this._effect.isReady())
  16481. return null;
  16482. // States
  16483. this._engine.enableEffect(this._effect);
  16484. this._engine.setState(false);
  16485. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16486. this._engine.setDepthBuffer(false);
  16487. this._engine.setDepthWrite(false);
  16488. // Texture
  16489. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16490. // Parameters
  16491. if (this.onApply) {
  16492. this.onApply(this._effect);
  16493. }
  16494. return this._effect;
  16495. };
  16496. PostProcess.prototype.dispose = function (camera) {
  16497. camera = camera || this._camera;
  16498. if (this._textures.length > 0) {
  16499. for (var i = 0; i < this._textures.length; i++) {
  16500. this._engine._releaseTexture(this._textures.data[i]);
  16501. }
  16502. this._textures.reset();
  16503. }
  16504. camera.detachPostProcess(this);
  16505. var index = camera._postProcesses.indexOf(this);
  16506. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16507. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16508. }
  16509. };
  16510. return PostProcess;
  16511. })();
  16512. BABYLON.PostProcess = PostProcess;
  16513. })(BABYLON || (BABYLON = {}));
  16514. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16515. (function (BABYLON) {
  16516. var PostProcessManager = (function () {
  16517. function PostProcessManager(scene) {
  16518. this._vertexDeclaration = [2];
  16519. this._vertexStrideSize = 2 * 4;
  16520. this._scene = scene;
  16521. // VBO
  16522. var vertices = [];
  16523. vertices.push(1, 1);
  16524. vertices.push(-1, 1);
  16525. vertices.push(-1, -1);
  16526. vertices.push(1, -1);
  16527. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16528. // Indices
  16529. var indices = [];
  16530. indices.push(0);
  16531. indices.push(1);
  16532. indices.push(2);
  16533. indices.push(0);
  16534. indices.push(2);
  16535. indices.push(3);
  16536. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16537. }
  16538. // Methods
  16539. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16540. var postProcesses = this._scene.activeCamera._postProcesses;
  16541. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16542. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16543. return false;
  16544. }
  16545. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16546. return true;
  16547. };
  16548. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16549. var postProcesses = this._scene.activeCamera._postProcesses;
  16550. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16551. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16552. return;
  16553. }
  16554. var engine = this._scene.getEngine();
  16555. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16556. if (index < postProcessesTakenIndices.length - 1) {
  16557. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16558. }
  16559. else {
  16560. if (targetTexture) {
  16561. engine.bindFramebuffer(targetTexture);
  16562. }
  16563. else {
  16564. engine.restoreDefaultFramebuffer();
  16565. }
  16566. }
  16567. if (doNotPresent) {
  16568. break;
  16569. }
  16570. var pp = postProcesses[postProcessesTakenIndices[index]];
  16571. var effect = pp.apply();
  16572. if (effect) {
  16573. if (pp.onBeforeRender) {
  16574. pp.onBeforeRender(effect);
  16575. }
  16576. // VBOs
  16577. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16578. // Draw order
  16579. engine.draw(true, 0, 6);
  16580. }
  16581. }
  16582. // Restore depth buffer
  16583. engine.setDepthBuffer(true);
  16584. engine.setDepthWrite(true);
  16585. };
  16586. PostProcessManager.prototype.dispose = function () {
  16587. if (this._vertexBuffer) {
  16588. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16589. this._vertexBuffer = null;
  16590. }
  16591. if (this._indexBuffer) {
  16592. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16593. this._indexBuffer = null;
  16594. }
  16595. };
  16596. return PostProcessManager;
  16597. })();
  16598. BABYLON.PostProcessManager = PostProcessManager;
  16599. })(BABYLON || (BABYLON = {}));
  16600. //# sourceMappingURL=babylon.postProcessManager.js.map
  16601. var BABYLON;
  16602. (function (BABYLON) {
  16603. var PassPostProcess = (function (_super) {
  16604. __extends(PassPostProcess, _super);
  16605. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16606. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16607. }
  16608. return PassPostProcess;
  16609. })(BABYLON.PostProcess);
  16610. BABYLON.PassPostProcess = PassPostProcess;
  16611. })(BABYLON || (BABYLON = {}));
  16612. //# sourceMappingURL=babylon.passPostProcess.js.map
  16613. var BABYLON;
  16614. (function (BABYLON) {
  16615. var BlurPostProcess = (function (_super) {
  16616. __extends(BlurPostProcess, _super);
  16617. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16618. var _this = this;
  16619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16620. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16621. this.direction = direction;
  16622. this.blurWidth = blurWidth;
  16623. this.onApply = function (effect) {
  16624. effect.setFloat2("screenSize", _this.width, _this.height);
  16625. effect.setVector2("direction", _this.direction);
  16626. effect.setFloat("blurWidth", _this.blurWidth);
  16627. };
  16628. }
  16629. return BlurPostProcess;
  16630. })(BABYLON.PostProcess);
  16631. BABYLON.BlurPostProcess = BlurPostProcess;
  16632. })(BABYLON || (BABYLON = {}));
  16633. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16634. var BABYLON;
  16635. (function (BABYLON) {
  16636. var FilterPostProcess = (function (_super) {
  16637. __extends(FilterPostProcess, _super);
  16638. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16639. var _this = this;
  16640. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16641. this.kernelMatrix = kernelMatrix;
  16642. this.onApply = function (effect) {
  16643. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16644. };
  16645. }
  16646. return FilterPostProcess;
  16647. })(BABYLON.PostProcess);
  16648. BABYLON.FilterPostProcess = FilterPostProcess;
  16649. })(BABYLON || (BABYLON = {}));
  16650. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16651. var BABYLON;
  16652. (function (BABYLON) {
  16653. var RefractionPostProcess = (function (_super) {
  16654. __extends(RefractionPostProcess, _super);
  16655. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16656. var _this = this;
  16657. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16658. this.color = color;
  16659. this.depth = depth;
  16660. this.colorLevel = colorLevel;
  16661. this.onActivate = function (cam) {
  16662. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16663. };
  16664. this.onApply = function (effect) {
  16665. effect.setColor3("baseColor", _this.color);
  16666. effect.setFloat("depth", _this.depth);
  16667. effect.setFloat("colorLevel", _this.colorLevel);
  16668. effect.setTexture("refractionSampler", _this._refRexture);
  16669. };
  16670. }
  16671. // Methods
  16672. RefractionPostProcess.prototype.dispose = function (camera) {
  16673. if (this._refRexture) {
  16674. this._refRexture.dispose();
  16675. }
  16676. _super.prototype.dispose.call(this, camera);
  16677. };
  16678. return RefractionPostProcess;
  16679. })(BABYLON.PostProcess);
  16680. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16681. })(BABYLON || (BABYLON = {}));
  16682. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16683. var BABYLON;
  16684. (function (BABYLON) {
  16685. var BlackAndWhitePostProcess = (function (_super) {
  16686. __extends(BlackAndWhitePostProcess, _super);
  16687. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16688. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16689. }
  16690. return BlackAndWhitePostProcess;
  16691. })(BABYLON.PostProcess);
  16692. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16693. })(BABYLON || (BABYLON = {}));
  16694. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16695. var BABYLON;
  16696. (function (BABYLON) {
  16697. var ConvolutionPostProcess = (function (_super) {
  16698. __extends(ConvolutionPostProcess, _super);
  16699. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16700. var _this = this;
  16701. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16702. this.kernel = kernel;
  16703. this.onApply = function (effect) {
  16704. effect.setFloat2("screenSize", _this.width, _this.height);
  16705. effect.setArray("kernel", _this.kernel);
  16706. };
  16707. }
  16708. // Statics
  16709. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16710. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16711. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16712. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16713. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16714. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16715. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16716. return ConvolutionPostProcess;
  16717. })(BABYLON.PostProcess);
  16718. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16719. })(BABYLON || (BABYLON = {}));
  16720. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16721. var BABYLON;
  16722. (function (BABYLON) {
  16723. var FxaaPostProcess = (function (_super) {
  16724. __extends(FxaaPostProcess, _super);
  16725. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16726. var _this = this;
  16727. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16728. this.onSizeChanged = function () {
  16729. _this.texelWidth = 1.0 / _this.width;
  16730. _this.texelHeight = 1.0 / _this.height;
  16731. };
  16732. this.onApply = function (effect) {
  16733. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16734. };
  16735. }
  16736. return FxaaPostProcess;
  16737. })(BABYLON.PostProcess);
  16738. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16739. })(BABYLON || (BABYLON = {}));
  16740. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16741. (function (BABYLON) {
  16742. var LensFlare = (function () {
  16743. function LensFlare(size, position, color, imgUrl, system) {
  16744. this.size = size;
  16745. this.position = position;
  16746. this.dispose = function () {
  16747. if (this.texture) {
  16748. this.texture.dispose();
  16749. }
  16750. // Remove from scene
  16751. var index = this._system.lensFlares.indexOf(this);
  16752. this._system.lensFlares.splice(index, 1);
  16753. };
  16754. this.color = color || new BABYLON.Color3(1, 1, 1);
  16755. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16756. this._system = system;
  16757. system.lensFlares.push(this);
  16758. }
  16759. return LensFlare;
  16760. })();
  16761. BABYLON.LensFlare = LensFlare;
  16762. })(BABYLON || (BABYLON = {}));
  16763. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16764. (function (BABYLON) {
  16765. var LensFlareSystem = (function () {
  16766. function LensFlareSystem(name, emitter, scene) {
  16767. this.name = name;
  16768. this.lensFlares = new Array();
  16769. this.borderLimit = 300;
  16770. this._vertexDeclaration = [2];
  16771. this._vertexStrideSize = 2 * 4;
  16772. this._isEnabled = true;
  16773. this._scene = scene;
  16774. this._emitter = emitter;
  16775. scene.lensFlareSystems.push(this);
  16776. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16777. // VBO
  16778. var vertices = [];
  16779. vertices.push(1, 1);
  16780. vertices.push(-1, 1);
  16781. vertices.push(-1, -1);
  16782. vertices.push(1, -1);
  16783. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16784. // Indices
  16785. var indices = [];
  16786. indices.push(0);
  16787. indices.push(1);
  16788. indices.push(2);
  16789. indices.push(0);
  16790. indices.push(2);
  16791. indices.push(3);
  16792. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16793. // Effects
  16794. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16795. }
  16796. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16797. get: function () {
  16798. return this._isEnabled;
  16799. },
  16800. set: function (value) {
  16801. this._isEnabled = value;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. LensFlareSystem.prototype.getScene = function () {
  16807. return this._scene;
  16808. };
  16809. LensFlareSystem.prototype.getEmitter = function () {
  16810. return this._emitter;
  16811. };
  16812. LensFlareSystem.prototype.getEmitterPosition = function () {
  16813. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16814. };
  16815. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16816. var position = this.getEmitterPosition();
  16817. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16818. this._positionX = position.x;
  16819. this._positionY = position.y;
  16820. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16821. if (position.z > 0) {
  16822. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16823. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16824. return true;
  16825. }
  16826. }
  16827. return false;
  16828. };
  16829. LensFlareSystem.prototype._isVisible = function () {
  16830. if (!this._isEnabled) {
  16831. return false;
  16832. }
  16833. var emitterPosition = this.getEmitterPosition();
  16834. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16835. var distance = direction.length();
  16836. direction.normalize();
  16837. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16838. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16839. return !pickInfo.hit || pickInfo.distance > distance;
  16840. };
  16841. LensFlareSystem.prototype.render = function () {
  16842. if (!this._effect.isReady())
  16843. return false;
  16844. var engine = this._scene.getEngine();
  16845. var viewport = this._scene.activeCamera.viewport;
  16846. var globalViewport = viewport.toGlobal(engine);
  16847. // Position
  16848. if (!this.computeEffectivePosition(globalViewport)) {
  16849. return false;
  16850. }
  16851. // Visibility
  16852. if (!this._isVisible()) {
  16853. return false;
  16854. }
  16855. // Intensity
  16856. var awayX;
  16857. var awayY;
  16858. if (this._positionX < this.borderLimit + globalViewport.x) {
  16859. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16860. }
  16861. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16862. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16863. }
  16864. else {
  16865. awayX = 0;
  16866. }
  16867. if (this._positionY < this.borderLimit + globalViewport.y) {
  16868. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16869. }
  16870. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16871. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16872. }
  16873. else {
  16874. awayY = 0;
  16875. }
  16876. var away = (awayX > awayY) ? awayX : awayY;
  16877. if (away > this.borderLimit) {
  16878. away = this.borderLimit;
  16879. }
  16880. var intensity = 1.0 - (away / this.borderLimit);
  16881. if (intensity < 0) {
  16882. return false;
  16883. }
  16884. if (intensity > 1.0) {
  16885. intensity = 1.0;
  16886. }
  16887. // Position
  16888. var centerX = globalViewport.x + globalViewport.width / 2;
  16889. var centerY = globalViewport.y + globalViewport.height / 2;
  16890. var distX = centerX - this._positionX;
  16891. var distY = centerY - this._positionY;
  16892. // Effects
  16893. engine.enableEffect(this._effect);
  16894. engine.setState(false);
  16895. engine.setDepthBuffer(false);
  16896. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16897. // VBOs
  16898. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16899. for (var index = 0; index < this.lensFlares.length; index++) {
  16900. var flare = this.lensFlares[index];
  16901. var x = centerX - (distX * flare.position);
  16902. var y = centerY - (distY * flare.position);
  16903. var cw = flare.size;
  16904. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16905. var cx = 2 * (x / globalViewport.width) - 1.0;
  16906. var cy = 1.0 - 2 * (y / globalViewport.height);
  16907. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16908. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16909. // Texture
  16910. this._effect.setTexture("textureSampler", flare.texture);
  16911. // Color
  16912. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16913. // Draw order
  16914. engine.draw(true, 0, 6);
  16915. }
  16916. engine.setDepthBuffer(true);
  16917. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16918. return true;
  16919. };
  16920. LensFlareSystem.prototype.dispose = function () {
  16921. if (this._vertexBuffer) {
  16922. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16923. this._vertexBuffer = null;
  16924. }
  16925. if (this._indexBuffer) {
  16926. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16927. this._indexBuffer = null;
  16928. }
  16929. while (this.lensFlares.length) {
  16930. this.lensFlares[0].dispose();
  16931. }
  16932. // Remove from scene
  16933. var index = this._scene.lensFlareSystems.indexOf(this);
  16934. this._scene.lensFlareSystems.splice(index, 1);
  16935. };
  16936. return LensFlareSystem;
  16937. })();
  16938. BABYLON.LensFlareSystem = LensFlareSystem;
  16939. })(BABYLON || (BABYLON = {}));
  16940. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16941. (function (BABYLON) {
  16942. var IntersectionInfo = (function () {
  16943. function IntersectionInfo(bu, bv, distance) {
  16944. this.bu = bu;
  16945. this.bv = bv;
  16946. this.distance = distance;
  16947. this.faceId = 0;
  16948. this.subMeshId = 0;
  16949. }
  16950. return IntersectionInfo;
  16951. })();
  16952. BABYLON.IntersectionInfo = IntersectionInfo;
  16953. var PickingInfo = (function () {
  16954. function PickingInfo() {
  16955. this.hit = false;
  16956. this.distance = 0;
  16957. this.pickedPoint = null;
  16958. this.pickedMesh = null;
  16959. this.bu = 0;
  16960. this.bv = 0;
  16961. this.faceId = -1;
  16962. this.subMeshId = 0;
  16963. }
  16964. // Methods
  16965. PickingInfo.prototype.getNormal = function () {
  16966. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16967. return null;
  16968. }
  16969. var indices = this.pickedMesh.getIndices();
  16970. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16971. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16972. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16973. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16974. normal0 = normal0.scale(this.bu);
  16975. normal1 = normal1.scale(this.bv);
  16976. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16977. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16978. };
  16979. PickingInfo.prototype.getTextureCoordinates = function () {
  16980. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16981. return null;
  16982. }
  16983. var indices = this.pickedMesh.getIndices();
  16984. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16985. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16986. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16987. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16988. uv0 = uv0.scale(this.bu);
  16989. uv1 = uv1.scale(this.bv);
  16990. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16991. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16992. };
  16993. return PickingInfo;
  16994. })();
  16995. BABYLON.PickingInfo = PickingInfo;
  16996. })(BABYLON || (BABYLON = {}));
  16997. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16998. (function (BABYLON) {
  16999. var FilesInput = (function () {
  17000. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17001. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17002. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17003. this.engine = p_engine;
  17004. this.canvas = p_canvas;
  17005. this.currentScene = p_scene;
  17006. this.sceneLoadedCallback = p_sceneLoadedCallback;
  17007. this.progressCallback = p_progressCallback;
  17008. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17009. this.textureLoadingCallback = p_textureLoadingCallback;
  17010. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17011. }
  17012. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17013. var _this = this;
  17014. if (p_elementToMonitor) {
  17015. this.elementToMonitor = p_elementToMonitor;
  17016. this.elementToMonitor.addEventListener("dragenter", function (e) {
  17017. _this.drag(e);
  17018. }, false);
  17019. this.elementToMonitor.addEventListener("dragover", function (e) {
  17020. _this.drag(e);
  17021. }, false);
  17022. this.elementToMonitor.addEventListener("drop", function (e) {
  17023. _this.drop(e);
  17024. }, false);
  17025. }
  17026. };
  17027. FilesInput.prototype.renderFunction = function () {
  17028. if (this.additionnalRenderLoopLogicCallback) {
  17029. this.additionnalRenderLoopLogicCallback();
  17030. }
  17031. if (this.currentScene) {
  17032. if (this.textureLoadingCallback) {
  17033. var remaining = this.currentScene.getWaitingItemsCount();
  17034. if (remaining > 0) {
  17035. this.textureLoadingCallback(remaining);
  17036. }
  17037. }
  17038. this.currentScene.render();
  17039. }
  17040. };
  17041. FilesInput.prototype.drag = function (e) {
  17042. e.stopPropagation();
  17043. e.preventDefault();
  17044. };
  17045. FilesInput.prototype.drop = function (eventDrop) {
  17046. eventDrop.stopPropagation();
  17047. eventDrop.preventDefault();
  17048. this.loadFiles(eventDrop);
  17049. };
  17050. FilesInput.prototype.loadFiles = function (event) {
  17051. var _this = this;
  17052. var that = this;
  17053. if (this.startingProcessingFilesCallback)
  17054. this.startingProcessingFilesCallback();
  17055. var sceneFileToLoad;
  17056. var filesToLoad;
  17057. // Handling data transfer via drag'n'drop
  17058. if (event && event.dataTransfer && event.dataTransfer.files) {
  17059. filesToLoad = event.dataTransfer.files;
  17060. }
  17061. // Handling files from input files
  17062. if (event && event.target && event.target.files) {
  17063. filesToLoad = event.target.files;
  17064. }
  17065. if (filesToLoad && filesToLoad.length > 0) {
  17066. for (var i = 0; i < filesToLoad.length; i++) {
  17067. switch (filesToLoad[i].type) {
  17068. case "image/jpeg":
  17069. case "image/png":
  17070. case "image/bmp":
  17071. FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  17072. break;
  17073. case "image/targa":
  17074. case "image/vnd.ms-dds":
  17075. case "audio/wav":
  17076. case "audio/x-wav":
  17077. case "audio/mp3":
  17078. case "audio/mpeg":
  17079. case "audio/mpeg3":
  17080. case "audio/x-mpeg-3":
  17081. case "audio/ogg":
  17082. FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  17083. break;
  17084. default:
  17085. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17086. sceneFileToLoad = filesToLoad[i];
  17087. }
  17088. break;
  17089. }
  17090. }
  17091. // If a ".babylon" file has been provided
  17092. if (sceneFileToLoad) {
  17093. if (this.currentScene) {
  17094. this.engine.stopRenderLoop();
  17095. this.currentScene.dispose();
  17096. }
  17097. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  17098. that.currentScene = newScene;
  17099. // Wait for textures and shaders to be ready
  17100. that.currentScene.executeWhenReady(function () {
  17101. // Attach camera to canvas inputs
  17102. if (that.currentScene.activeCamera) {
  17103. that.currentScene.activeCamera.attachControl(that.canvas);
  17104. }
  17105. if (that.sceneLoadedCallback) {
  17106. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  17107. }
  17108. that.engine.runRenderLoop(function () {
  17109. that.renderFunction();
  17110. });
  17111. });
  17112. }, function (progress) {
  17113. if (_this.progressCallback) {
  17114. _this.progressCallback(progress);
  17115. }
  17116. });
  17117. }
  17118. else {
  17119. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17120. }
  17121. }
  17122. };
  17123. FilesInput.FilesTextures = new Array();
  17124. FilesInput.FilesToLoad = new Array();
  17125. return FilesInput;
  17126. })();
  17127. BABYLON.FilesInput = FilesInput;
  17128. })(BABYLON || (BABYLON = {}));
  17129. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17130. (function (BABYLON) {
  17131. var OimoJSPlugin = (function () {
  17132. function OimoJSPlugin() {
  17133. this._registeredMeshes = [];
  17134. /**
  17135. * Update the body position according to the mesh position
  17136. * @param mesh
  17137. */
  17138. this.updateBodyPosition = function (mesh) {
  17139. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17140. var registeredMesh = this._registeredMeshes[index];
  17141. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17142. var body = registeredMesh.body.body;
  17143. mesh.computeWorldMatrix(true);
  17144. var center = mesh.getBoundingInfo().boundingBox.center;
  17145. body.setPosition(center.x, center.y, center.z);
  17146. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17147. return;
  17148. }
  17149. // Case where the parent has been updated
  17150. if (registeredMesh.mesh.parent === mesh) {
  17151. mesh.computeWorldMatrix(true);
  17152. registeredMesh.mesh.computeWorldMatrix(true);
  17153. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17154. var absoluteRotation = mesh.rotation;
  17155. body = registeredMesh.body.body;
  17156. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17157. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17158. return;
  17159. }
  17160. }
  17161. };
  17162. }
  17163. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17164. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17165. };
  17166. OimoJSPlugin.prototype.initialize = function (iterations) {
  17167. this._world = new OIMO.World();
  17168. this._world.clear();
  17169. };
  17170. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17171. this._world.gravity = gravity;
  17172. };
  17173. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17174. var body = null;
  17175. this.unregisterMesh(mesh);
  17176. mesh.computeWorldMatrix(true);
  17177. var initialRotation = null;
  17178. if (mesh.rotationQuaternion) {
  17179. initialRotation = mesh.rotationQuaternion.clone();
  17180. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17181. mesh.computeWorldMatrix(true);
  17182. }
  17183. var bbox = mesh.getBoundingInfo().boundingBox;
  17184. // The delta between the mesh position and the mesh bounding box center
  17185. var deltaPosition = mesh.position.subtract(bbox.center);
  17186. // Transform delta position with the rotation
  17187. if (initialRotation) {
  17188. var m = new BABYLON.Matrix();
  17189. initialRotation.toRotationMatrix(m);
  17190. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17191. }
  17192. switch (impostor) {
  17193. case BABYLON.PhysicsEngine.SphereImpostor:
  17194. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17195. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17196. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17197. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17198. body = new OIMO.Body({
  17199. type: 'sphere',
  17200. size: [size],
  17201. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17202. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17203. move: options.mass != 0,
  17204. config: [options.mass, options.friction, options.restitution],
  17205. world: this._world
  17206. });
  17207. break;
  17208. case BABYLON.PhysicsEngine.PlaneImpostor:
  17209. case BABYLON.PhysicsEngine.CylinderImpostor:
  17210. case BABYLON.PhysicsEngine.BoxImpostor:
  17211. var min = bbox.minimumWorld;
  17212. var max = bbox.maximumWorld;
  17213. var box = max.subtract(min);
  17214. var sizeX = this._checkWithEpsilon(box.x);
  17215. var sizeY = this._checkWithEpsilon(box.y);
  17216. var sizeZ = this._checkWithEpsilon(box.z);
  17217. body = new OIMO.Body({
  17218. type: 'box',
  17219. size: [sizeX, sizeY, sizeZ],
  17220. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17221. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17222. move: options.mass != 0,
  17223. config: [options.mass, options.friction, options.restitution],
  17224. world: this._world
  17225. });
  17226. break;
  17227. }
  17228. //If quaternion was set as the rotation of the object
  17229. if (initialRotation) {
  17230. //We have to access the rigid body's properties to set the quaternion.
  17231. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17232. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17233. //update the internal rotation matrix
  17234. body.body.syncShapes();
  17235. }
  17236. this._registeredMeshes.push({
  17237. mesh: mesh,
  17238. body: body,
  17239. delta: deltaPosition
  17240. });
  17241. return body;
  17242. };
  17243. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17244. var types = [], sizes = [], positions = [], rotations = [];
  17245. var initialMesh = parts[0].mesh;
  17246. for (var index = 0; index < parts.length; index++) {
  17247. var part = parts[index];
  17248. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17249. types.push(bodyParameters.type);
  17250. sizes.push.apply(sizes, bodyParameters.size);
  17251. positions.push.apply(positions, bodyParameters.pos);
  17252. rotations.push.apply(rotations, bodyParameters.rot);
  17253. }
  17254. var body = new OIMO.Body({
  17255. type: types,
  17256. size: sizes,
  17257. pos: positions,
  17258. rot: rotations,
  17259. move: options.mass != 0,
  17260. config: [options.mass, options.friction, options.restitution],
  17261. world: this._world
  17262. });
  17263. this._registeredMeshes.push({
  17264. mesh: initialMesh,
  17265. body: body
  17266. });
  17267. return body;
  17268. };
  17269. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17270. var bodyParameters = null;
  17271. var mesh = part.mesh;
  17272. // We need the bounding box/sphere info to compute the physics body
  17273. mesh.computeWorldMatrix();
  17274. switch (part.impostor) {
  17275. case BABYLON.PhysicsEngine.SphereImpostor:
  17276. var bbox = mesh.getBoundingInfo().boundingBox;
  17277. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17278. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17279. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17280. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17281. bodyParameters = {
  17282. type: 'sphere',
  17283. /* bug with oimo : sphere needs 3 sizes in this case */
  17284. size: [size, -1, -1],
  17285. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17286. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17287. };
  17288. break;
  17289. case BABYLON.PhysicsEngine.PlaneImpostor:
  17290. case BABYLON.PhysicsEngine.BoxImpostor:
  17291. bbox = mesh.getBoundingInfo().boundingBox;
  17292. var min = bbox.minimumWorld;
  17293. var max = bbox.maximumWorld;
  17294. var box = max.subtract(min);
  17295. var sizeX = this._checkWithEpsilon(box.x);
  17296. var sizeY = this._checkWithEpsilon(box.y);
  17297. var sizeZ = this._checkWithEpsilon(box.z);
  17298. var relativePosition = mesh.position;
  17299. bodyParameters = {
  17300. type: 'box',
  17301. size: [sizeX, sizeY, sizeZ],
  17302. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17303. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17304. };
  17305. break;
  17306. }
  17307. return bodyParameters;
  17308. };
  17309. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17310. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17311. var registeredMesh = this._registeredMeshes[index];
  17312. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17313. if (registeredMesh.body) {
  17314. this._world.removeRigidBody(registeredMesh.body.body);
  17315. this._unbindBody(registeredMesh.body);
  17316. }
  17317. this._registeredMeshes.splice(index, 1);
  17318. return;
  17319. }
  17320. }
  17321. };
  17322. OimoJSPlugin.prototype._unbindBody = function (body) {
  17323. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17324. var registeredMesh = this._registeredMeshes[index];
  17325. if (registeredMesh.body === body) {
  17326. registeredMesh.body = null;
  17327. }
  17328. }
  17329. };
  17330. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17331. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17332. var registeredMesh = this._registeredMeshes[index];
  17333. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17334. // Get object mass to have a behaviour similar to cannon.js
  17335. var mass = registeredMesh.body.body.massInfo.mass;
  17336. // The force is scaled with the mass of object
  17337. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17338. return;
  17339. }
  17340. }
  17341. };
  17342. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17343. var body1 = null, body2 = null;
  17344. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17345. var registeredMesh = this._registeredMeshes[index];
  17346. if (registeredMesh.mesh === mesh1) {
  17347. body1 = registeredMesh.body.body;
  17348. }
  17349. else if (registeredMesh.mesh === mesh2) {
  17350. body2 = registeredMesh.body.body;
  17351. }
  17352. }
  17353. if (!body1 || !body2) {
  17354. return false;
  17355. }
  17356. if (!options) {
  17357. options = {};
  17358. }
  17359. new OIMO.Link({
  17360. type: options.type,
  17361. body1: body1,
  17362. body2: body2,
  17363. min: options.min,
  17364. max: options.max,
  17365. axe1: options.axe1,
  17366. axe2: options.axe2,
  17367. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17368. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17369. collision: options.collision,
  17370. spring: options.spring,
  17371. world: this._world
  17372. });
  17373. return true;
  17374. };
  17375. OimoJSPlugin.prototype.dispose = function () {
  17376. this._world.clear();
  17377. while (this._registeredMeshes.length) {
  17378. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17379. }
  17380. };
  17381. OimoJSPlugin.prototype.isSupported = function () {
  17382. return OIMO !== undefined;
  17383. };
  17384. OimoJSPlugin.prototype._getLastShape = function (body) {
  17385. var lastShape = body.shapes;
  17386. while (lastShape.next) {
  17387. lastShape = lastShape.next;
  17388. }
  17389. return lastShape;
  17390. };
  17391. OimoJSPlugin.prototype.runOneStep = function (time) {
  17392. this._world.step();
  17393. // Update the position of all registered meshes
  17394. var i = this._registeredMeshes.length;
  17395. var m;
  17396. while (i--) {
  17397. var body = this._registeredMeshes[i].body.body;
  17398. var mesh = this._registeredMeshes[i].mesh;
  17399. var delta = this._registeredMeshes[i].delta;
  17400. if (!body.sleeping) {
  17401. if (body.shapes.next) {
  17402. var parentShape = this._getLastShape(body);
  17403. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17404. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17405. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17406. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17407. if (!mesh.rotationQuaternion) {
  17408. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17409. }
  17410. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17411. mesh.computeWorldMatrix();
  17412. }
  17413. else {
  17414. m = body.getMatrix();
  17415. mtx = BABYLON.Matrix.FromArray(m);
  17416. // Body position
  17417. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17418. if (!delta) {
  17419. mesh.position.x = bodyX;
  17420. mesh.position.y = bodyY;
  17421. mesh.position.z = bodyZ;
  17422. }
  17423. else {
  17424. mesh.position.x = bodyX + delta.x;
  17425. mesh.position.y = bodyY + delta.y;
  17426. mesh.position.z = bodyZ + delta.z;
  17427. }
  17428. if (!mesh.rotationQuaternion) {
  17429. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17430. }
  17431. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17432. mesh.computeWorldMatrix();
  17433. }
  17434. }
  17435. }
  17436. };
  17437. return OimoJSPlugin;
  17438. })();
  17439. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17440. })(BABYLON || (BABYLON = {}));
  17441. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17442. (function (BABYLON) {
  17443. var PhysicsEngine = (function () {
  17444. function PhysicsEngine(plugin) {
  17445. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17446. }
  17447. PhysicsEngine.prototype._initialize = function (gravity) {
  17448. this._currentPlugin.initialize();
  17449. this._setGravity(gravity);
  17450. };
  17451. PhysicsEngine.prototype._runOneStep = function (delta) {
  17452. if (delta > 0.1) {
  17453. delta = 0.1;
  17454. }
  17455. else if (delta <= 0) {
  17456. delta = 1.0 / 60.0;
  17457. }
  17458. this._currentPlugin.runOneStep(delta);
  17459. };
  17460. PhysicsEngine.prototype._setGravity = function (gravity) {
  17461. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17462. this._currentPlugin.setGravity(this.gravity);
  17463. };
  17464. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17465. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17466. };
  17467. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17468. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17469. };
  17470. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17471. this._currentPlugin.unregisterMesh(mesh);
  17472. };
  17473. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17474. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17475. };
  17476. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17477. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17478. };
  17479. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17480. this._currentPlugin.updateBodyPosition(mesh);
  17481. };
  17482. PhysicsEngine.prototype.dispose = function () {
  17483. this._currentPlugin.dispose();
  17484. };
  17485. PhysicsEngine.prototype.isSupported = function () {
  17486. return this._currentPlugin.isSupported();
  17487. };
  17488. // Statics
  17489. PhysicsEngine.NoImpostor = 0;
  17490. PhysicsEngine.SphereImpostor = 1;
  17491. PhysicsEngine.BoxImpostor = 2;
  17492. PhysicsEngine.PlaneImpostor = 3;
  17493. PhysicsEngine.MeshImpostor = 4;
  17494. PhysicsEngine.CapsuleImpostor = 5;
  17495. PhysicsEngine.ConeImpostor = 6;
  17496. PhysicsEngine.CylinderImpostor = 7;
  17497. PhysicsEngine.ConvexHullImpostor = 8;
  17498. PhysicsEngine.Epsilon = 0.001;
  17499. return PhysicsEngine;
  17500. })();
  17501. BABYLON.PhysicsEngine = PhysicsEngine;
  17502. })(BABYLON || (BABYLON = {}));
  17503. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17504. (function (BABYLON) {
  17505. var serializeLight = function (light) {
  17506. var serializationObject = {};
  17507. serializationObject.name = light.name;
  17508. serializationObject.id = light.id;
  17509. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17510. if (light instanceof BABYLON.PointLight) {
  17511. serializationObject.type = 0;
  17512. serializationObject.position = light.position.asArray();
  17513. }
  17514. else if (light instanceof BABYLON.DirectionalLight) {
  17515. serializationObject.type = 1;
  17516. var directionalLight = light;
  17517. serializationObject.position = directionalLight.position.asArray();
  17518. serializationObject.direction = directionalLight.direction.asArray();
  17519. }
  17520. else if (light instanceof BABYLON.SpotLight) {
  17521. serializationObject.type = 2;
  17522. var spotLight = light;
  17523. serializationObject.position = spotLight.position.asArray();
  17524. serializationObject.direction = spotLight.position.asArray();
  17525. serializationObject.angle = spotLight.angle;
  17526. serializationObject.exponent = spotLight.exponent;
  17527. }
  17528. else if (light instanceof BABYLON.HemisphericLight) {
  17529. serializationObject.type = 3;
  17530. var hemisphericLight = light;
  17531. serializationObject.direction = hemisphericLight.direction.asArray();
  17532. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17533. }
  17534. if (light.intensity) {
  17535. serializationObject.intensity = light.intensity;
  17536. }
  17537. serializationObject.range = light.range;
  17538. serializationObject.diffuse = light.diffuse.asArray();
  17539. serializationObject.specular = light.specular.asArray();
  17540. return serializationObject;
  17541. };
  17542. var serializeFresnelParameter = function (fresnelParameter) {
  17543. var serializationObject = {};
  17544. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17545. serializationObject.leftColor = fresnelParameter.leftColor;
  17546. serializationObject.rightColor = fresnelParameter.rightColor;
  17547. serializationObject.bias = fresnelParameter.bias;
  17548. serializationObject.power = fresnelParameter.power;
  17549. return serializationObject;
  17550. };
  17551. var serializeCamera = function (camera) {
  17552. var serializationObject = {};
  17553. serializationObject.name = camera.name;
  17554. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17555. serializationObject.id = camera.id;
  17556. serializationObject.position = camera.position.asArray();
  17557. // Parent
  17558. if (camera.parent) {
  17559. serializationObject.parentId = camera.parent.id;
  17560. }
  17561. // Target
  17562. serializationObject.rotation = camera.rotation.asArray();
  17563. // Locked target
  17564. if (camera.lockedTarget && camera.lockedTarget.id) {
  17565. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17566. }
  17567. serializationObject.fov = camera.fov;
  17568. serializationObject.minZ = camera.minZ;
  17569. serializationObject.maxZ = camera.maxZ;
  17570. serializationObject.speed = camera.speed;
  17571. serializationObject.inertia = camera.inertia;
  17572. serializationObject.checkCollisions = camera.checkCollisions;
  17573. serializationObject.applyGravity = camera.applyGravity;
  17574. if (camera.ellipsoid) {
  17575. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17576. }
  17577. // Animations
  17578. appendAnimations(camera, serializationObject);
  17579. // Layer mask
  17580. serializationObject.layerMask = camera.layerMask;
  17581. return serializationObject;
  17582. };
  17583. var appendAnimations = function (source, destination) {
  17584. if (source.animations) {
  17585. destination.animations = [];
  17586. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17587. var animation = source.animations[animationIndex];
  17588. destination.animations.push(serializeAnimation(animation));
  17589. }
  17590. }
  17591. };
  17592. var serializeAnimation = function (animation) {
  17593. var serializationObject = {};
  17594. serializationObject.name = animation.name;
  17595. serializationObject.property = animation.targetProperty;
  17596. serializationObject.framePerSecond = animation.framePerSecond;
  17597. serializationObject.dataType = animation.dataType;
  17598. serializationObject.loopBehavior = animation.loopMode;
  17599. var dataType = animation.dataType;
  17600. serializationObject.keys = [];
  17601. var keys = animation.getKeys();
  17602. for (var index = 0; index < keys.length; index++) {
  17603. var animationKey = keys[index];
  17604. var key = {};
  17605. key.frame = animationKey.frame;
  17606. switch (dataType) {
  17607. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17608. key.values = [animationKey.value];
  17609. break;
  17610. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17611. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17612. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17613. key.values = animationKey.value.asArray();
  17614. break;
  17615. }
  17616. serializationObject.keys.push(key);
  17617. }
  17618. return serializationObject;
  17619. };
  17620. var serializeMultiMaterial = function (material) {
  17621. var serializationObject = {};
  17622. serializationObject.name = material.name;
  17623. serializationObject.id = material.id;
  17624. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17625. serializationObject.materials = [];
  17626. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17627. var subMat = material.subMaterials[matIndex];
  17628. if (subMat) {
  17629. serializationObject.materials.push(subMat.id);
  17630. }
  17631. else {
  17632. serializationObject.materials.push(null);
  17633. }
  17634. }
  17635. return serializationObject;
  17636. };
  17637. var serializeMaterial = function (material) {
  17638. var serializationObject = {};
  17639. serializationObject.name = material.name;
  17640. serializationObject.ambient = material.ambientColor.asArray();
  17641. serializationObject.diffuse = material.diffuseColor.asArray();
  17642. serializationObject.specular = material.specularColor.asArray();
  17643. serializationObject.specularPower = material.specularPower;
  17644. serializationObject.emissive = material.emissiveColor.asArray();
  17645. serializationObject.alpha = material.alpha;
  17646. serializationObject.id = material.id;
  17647. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17648. serializationObject.backFaceCulling = material.backFaceCulling;
  17649. if (material.diffuseTexture) {
  17650. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17651. }
  17652. if (material.diffuseFresnelParameters) {
  17653. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17654. }
  17655. if (material.ambientTexture) {
  17656. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17657. }
  17658. if (material.opacityTexture) {
  17659. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17660. }
  17661. if (material.opacityFresnelParameters) {
  17662. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17663. }
  17664. if (material.reflectionTexture) {
  17665. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17666. }
  17667. if (material.reflectionFresnelParameters) {
  17668. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17669. }
  17670. if (material.emissiveTexture) {
  17671. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17672. }
  17673. if (material.emissiveFresnelParameters) {
  17674. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17675. }
  17676. if (material.specularTexture) {
  17677. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17678. }
  17679. if (material.bumpTexture) {
  17680. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17681. }
  17682. return serializationObject;
  17683. };
  17684. var serializeTexture = function (texture) {
  17685. var serializationObject = {};
  17686. if (!texture.name) {
  17687. return null;
  17688. }
  17689. if (texture instanceof BABYLON.CubeTexture) {
  17690. serializationObject.name = texture.name;
  17691. serializationObject.hasAlpha = texture.hasAlpha;
  17692. serializationObject.level = texture.level;
  17693. serializationObject.coordinatesMode = texture.coordinatesMode;
  17694. return serializationObject;
  17695. }
  17696. if (texture instanceof BABYLON.MirrorTexture) {
  17697. var mirrorTexture = texture;
  17698. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17699. serializationObject.renderList = [];
  17700. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17701. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17702. }
  17703. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17704. }
  17705. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17706. var renderTargetTexture = texture;
  17707. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17708. serializationObject.renderList = [];
  17709. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17710. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17711. }
  17712. }
  17713. var regularTexture = texture;
  17714. serializationObject.name = texture.name;
  17715. serializationObject.hasAlpha = texture.hasAlpha;
  17716. serializationObject.level = texture.level;
  17717. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17718. serializationObject.coordinatesMode = texture.coordinatesMode;
  17719. serializationObject.uOffset = regularTexture.uOffset;
  17720. serializationObject.vOffset = regularTexture.vOffset;
  17721. serializationObject.uScale = regularTexture.uScale;
  17722. serializationObject.vScale = regularTexture.vScale;
  17723. serializationObject.uAng = regularTexture.uAng;
  17724. serializationObject.vAng = regularTexture.vAng;
  17725. serializationObject.wAng = regularTexture.wAng;
  17726. serializationObject.wrapU = texture.wrapU;
  17727. serializationObject.wrapV = texture.wrapV;
  17728. // Animations
  17729. appendAnimations(texture, serializationObject);
  17730. return serializationObject;
  17731. };
  17732. var serializeSkeleton = function (skeleton) {
  17733. var serializationObject = {};
  17734. serializationObject.name = skeleton.name;
  17735. serializationObject.id = skeleton.id;
  17736. serializationObject.bones = [];
  17737. for (var index = 0; index < skeleton.bones.length; index++) {
  17738. var bone = skeleton.bones[index];
  17739. var serializedBone = {
  17740. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17741. name: bone.name,
  17742. matrix: bone.getLocalMatrix().toArray()
  17743. };
  17744. serializationObject.bones.push(serializedBone);
  17745. if (bone.animations && bone.animations.length > 0) {
  17746. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17747. }
  17748. }
  17749. return serializationObject;
  17750. };
  17751. var serializeParticleSystem = function (particleSystem) {
  17752. var serializationObject = {};
  17753. serializationObject.emitterId = particleSystem.emitter.id;
  17754. serializationObject.capacity = particleSystem.getCapacity();
  17755. if (particleSystem.particleTexture) {
  17756. serializationObject.textureName = particleSystem.particleTexture.name;
  17757. }
  17758. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17759. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17760. serializationObject.minSize = particleSystem.minSize;
  17761. serializationObject.maxSize = particleSystem.maxSize;
  17762. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17763. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17764. serializationObject.emitRate = particleSystem.emitRate;
  17765. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17766. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17767. serializationObject.gravity = particleSystem.gravity.asArray();
  17768. serializationObject.direction1 = particleSystem.direction1.asArray();
  17769. serializationObject.direction2 = particleSystem.direction2.asArray();
  17770. serializationObject.color1 = particleSystem.color1.asArray();
  17771. serializationObject.color2 = particleSystem.color2.asArray();
  17772. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17773. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17774. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17775. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17776. serializationObject.blendMode = particleSystem.blendMode;
  17777. return serializationObject;
  17778. };
  17779. var serializeLensFlareSystem = function (lensFlareSystem) {
  17780. var serializationObject = {};
  17781. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17782. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17783. serializationObject.flares = [];
  17784. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17785. var flare = lensFlareSystem.lensFlares[index];
  17786. serializationObject.flares.push({
  17787. size: flare.size,
  17788. position: flare.position,
  17789. color: flare.color.asArray(),
  17790. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17791. });
  17792. }
  17793. return serializationObject;
  17794. };
  17795. var serializeShadowGenerator = function (light) {
  17796. var serializationObject = {};
  17797. var shadowGenerator = light.getShadowGenerator();
  17798. serializationObject.lightId = light.id;
  17799. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17800. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17801. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17802. serializationObject.renderList = [];
  17803. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17804. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17805. serializationObject.renderList.push(mesh.id);
  17806. }
  17807. return serializationObject;
  17808. };
  17809. var serializedGeometries = [];
  17810. var serializeGeometry = function (geometry, serializationGeometries) {
  17811. if (serializedGeometries[geometry.id]) {
  17812. return;
  17813. }
  17814. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17815. serializationGeometries.boxes.push(serializeBox(geometry));
  17816. }
  17817. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17818. serializationGeometries.spheres.push(serializeSphere(geometry));
  17819. }
  17820. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17821. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17822. }
  17823. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17824. serializationGeometries.toruses.push(serializeTorus(geometry));
  17825. }
  17826. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17827. serializationGeometries.grounds.push(serializeGround(geometry));
  17828. }
  17829. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17830. serializationGeometries.planes.push(serializePlane(geometry));
  17831. }
  17832. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17833. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17834. }
  17835. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17836. throw new Error("Unknow primitive type");
  17837. }
  17838. else {
  17839. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17840. }
  17841. serializedGeometries[geometry.id] = true;
  17842. };
  17843. var serializeGeometryBase = function (geometry) {
  17844. var serializationObject = {};
  17845. serializationObject.id = geometry.id;
  17846. if (BABYLON.Tags.HasTags(geometry)) {
  17847. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17848. }
  17849. return serializationObject;
  17850. };
  17851. var serializeVertexData = function (vertexData) {
  17852. var serializationObject = serializeGeometryBase(vertexData);
  17853. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17854. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17855. }
  17856. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17857. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17858. }
  17859. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17860. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17861. }
  17862. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17863. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17864. }
  17865. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17866. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17867. }
  17868. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17869. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17870. serializationObject.matricesIndices._isExpanded = true;
  17871. }
  17872. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17873. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17874. }
  17875. serializationObject.indices = vertexData.getIndices();
  17876. return serializationObject;
  17877. };
  17878. var serializePrimitive = function (primitive) {
  17879. var serializationObject = serializeGeometryBase(primitive);
  17880. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17881. return serializationObject;
  17882. };
  17883. var serializeBox = function (box) {
  17884. var serializationObject = serializePrimitive(box);
  17885. serializationObject.size = box.size;
  17886. return serializationObject;
  17887. };
  17888. var serializeSphere = function (sphere) {
  17889. var serializationObject = serializePrimitive(sphere);
  17890. serializationObject.segments = sphere.segments;
  17891. serializationObject.diameter = sphere.diameter;
  17892. return serializationObject;
  17893. };
  17894. var serializeCylinder = function (cylinder) {
  17895. var serializationObject = serializePrimitive(cylinder);
  17896. serializationObject.height = cylinder.height;
  17897. serializationObject.diameterTop = cylinder.diameterTop;
  17898. serializationObject.diameterBottom = cylinder.diameterBottom;
  17899. serializationObject.tessellation = cylinder.tessellation;
  17900. return serializationObject;
  17901. };
  17902. var serializeTorus = function (torus) {
  17903. var serializationObject = serializePrimitive(torus);
  17904. serializationObject.diameter = torus.diameter;
  17905. serializationObject.thickness = torus.thickness;
  17906. serializationObject.tessellation = torus.tessellation;
  17907. return serializationObject;
  17908. };
  17909. var serializeGround = function (ground) {
  17910. var serializationObject = serializePrimitive(ground);
  17911. serializationObject.width = ground.width;
  17912. serializationObject.height = ground.height;
  17913. serializationObject.subdivisions = ground.subdivisions;
  17914. return serializationObject;
  17915. };
  17916. var serializePlane = function (plane) {
  17917. var serializationObject = serializePrimitive(plane);
  17918. serializationObject.size = plane.size;
  17919. return serializationObject;
  17920. };
  17921. var serializeTorusKnot = function (torusKnot) {
  17922. var serializationObject = serializePrimitive(torusKnot);
  17923. serializationObject.radius = torusKnot.radius;
  17924. serializationObject.tube = torusKnot.tube;
  17925. serializationObject.radialSegments = torusKnot.radialSegments;
  17926. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17927. serializationObject.p = torusKnot.p;
  17928. serializationObject.q = torusKnot.q;
  17929. return serializationObject;
  17930. };
  17931. var serializeMesh = function (mesh, serializationScene) {
  17932. var serializationObject = {};
  17933. serializationObject.name = mesh.name;
  17934. serializationObject.id = mesh.id;
  17935. if (BABYLON.Tags.HasTags(mesh)) {
  17936. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17937. }
  17938. serializationObject.position = mesh.position.asArray();
  17939. if (mesh.rotationQuaternion) {
  17940. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17941. }
  17942. else if (mesh.rotation) {
  17943. serializationObject.rotation = mesh.rotation.asArray();
  17944. }
  17945. serializationObject.scaling = mesh.scaling.asArray();
  17946. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17947. serializationObject.isEnabled = mesh.isEnabled();
  17948. serializationObject.isVisible = mesh.isVisible;
  17949. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17950. serializationObject.pickable = mesh.isPickable;
  17951. serializationObject.receiveShadows = mesh.receiveShadows;
  17952. serializationObject.billboardMode = mesh.billboardMode;
  17953. serializationObject.visibility = mesh.visibility;
  17954. serializationObject.checkCollisions = mesh.checkCollisions;
  17955. // Parent
  17956. if (mesh.parent) {
  17957. serializationObject.parentId = mesh.parent.id;
  17958. }
  17959. // Geometry
  17960. var geometry = mesh._geometry;
  17961. if (geometry) {
  17962. var geometryId = geometry.id;
  17963. serializationObject.geometryId = geometryId;
  17964. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17965. // 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
  17966. serializeGeometry(geometry, serializationScene.geometries);
  17967. }
  17968. // SubMeshes
  17969. serializationObject.subMeshes = [];
  17970. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17971. var subMesh = mesh.subMeshes[subIndex];
  17972. serializationObject.subMeshes.push({
  17973. materialIndex: subMesh.materialIndex,
  17974. verticesStart: subMesh.verticesStart,
  17975. verticesCount: subMesh.verticesCount,
  17976. indexStart: subMesh.indexStart,
  17977. indexCount: subMesh.indexCount
  17978. });
  17979. }
  17980. }
  17981. // Material
  17982. if (mesh.material) {
  17983. serializationObject.materialId = mesh.material.id;
  17984. }
  17985. else {
  17986. mesh.material = null;
  17987. }
  17988. // Skeleton
  17989. if (mesh.skeleton) {
  17990. serializationObject.skeletonId = mesh.skeleton.id;
  17991. }
  17992. // Physics
  17993. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17994. serializationObject.physicsMass = mesh.getPhysicsMass();
  17995. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17996. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17997. switch (mesh.getPhysicsImpostor()) {
  17998. case BABYLON.PhysicsEngine.BoxImpostor:
  17999. serializationObject.physicsImpostor = 1;
  18000. break;
  18001. case BABYLON.PhysicsEngine.SphereImpostor:
  18002. serializationObject.physicsImpostor = 2;
  18003. break;
  18004. }
  18005. }
  18006. // Instances
  18007. serializationObject.instances = [];
  18008. for (var index = 0; index < mesh.instances.length; index++) {
  18009. var instance = mesh.instances[index];
  18010. var serializationInstance = {
  18011. name: instance.name,
  18012. position: instance.position,
  18013. rotation: instance.rotation,
  18014. rotationQuaternion: instance.rotationQuaternion,
  18015. scaling: instance.scaling
  18016. };
  18017. serializationObject.instances.push(serializationInstance);
  18018. // Animations
  18019. appendAnimations(instance, serializationInstance);
  18020. }
  18021. // Animations
  18022. appendAnimations(mesh, serializationObject);
  18023. // Layer mask
  18024. serializationObject.layerMask = mesh.layerMask;
  18025. return serializationObject;
  18026. };
  18027. var SceneSerializer = (function () {
  18028. function SceneSerializer() {
  18029. }
  18030. SceneSerializer.Serialize = function (scene) {
  18031. var serializationObject = {};
  18032. // Scene
  18033. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18034. serializationObject.autoClear = scene.autoClear;
  18035. serializationObject.clearColor = scene.clearColor.asArray();
  18036. serializationObject.ambientColor = scene.ambientColor.asArray();
  18037. serializationObject.gravity = scene.gravity.asArray();
  18038. // Fog
  18039. if (scene.fogMode && scene.fogMode !== 0) {
  18040. serializationObject.fogMode = scene.fogMode;
  18041. serializationObject.fogColor = scene.fogColor.asArray();
  18042. serializationObject.fogStart = scene.fogStart;
  18043. serializationObject.fogEnd = scene.fogEnd;
  18044. serializationObject.fogDensity = scene.fogDensity;
  18045. }
  18046. // Lights
  18047. serializationObject.lights = [];
  18048. for (var index = 0; index < scene.lights.length; index++) {
  18049. var light = scene.lights[index];
  18050. serializationObject.lights.push(serializeLight(light));
  18051. }
  18052. // Cameras
  18053. serializationObject.cameras = [];
  18054. for (index = 0; index < scene.cameras.length; index++) {
  18055. var camera = scene.cameras[index];
  18056. if (camera instanceof BABYLON.FreeCamera) {
  18057. serializationObject.cameras.push(serializeCamera(camera));
  18058. }
  18059. }
  18060. if (scene.activeCamera) {
  18061. serializationObject.activeCameraID = scene.activeCamera.id;
  18062. }
  18063. // Materials
  18064. serializationObject.materials = [];
  18065. serializationObject.multiMaterials = [];
  18066. for (index = 0; index < scene.materials.length; index++) {
  18067. var material = scene.materials[index];
  18068. if (material instanceof BABYLON.StandardMaterial) {
  18069. serializationObject.materials.push(serializeMaterial(material));
  18070. }
  18071. else if (material instanceof BABYLON.MultiMaterial) {
  18072. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18073. }
  18074. }
  18075. // Skeletons
  18076. serializationObject.skeletons = [];
  18077. for (index = 0; index < scene.skeletons.length; index++) {
  18078. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18079. }
  18080. // Geometries
  18081. serializationObject.geometries = {};
  18082. serializationObject.geometries.boxes = [];
  18083. serializationObject.geometries.spheres = [];
  18084. serializationObject.geometries.cylinders = [];
  18085. serializationObject.geometries.toruses = [];
  18086. serializationObject.geometries.grounds = [];
  18087. serializationObject.geometries.planes = [];
  18088. serializationObject.geometries.torusKnots = [];
  18089. serializationObject.geometries.vertexData = [];
  18090. serializedGeometries = [];
  18091. var geometries = scene.getGeometries();
  18092. for (var index = 0; index < geometries.length; index++) {
  18093. var geometry = geometries[index];
  18094. if (geometry.isReady()) {
  18095. serializeGeometry(geometry, serializationObject.geometries);
  18096. }
  18097. }
  18098. // Meshes
  18099. serializationObject.meshes = [];
  18100. for (index = 0; index < scene.meshes.length; index++) {
  18101. var abstractMesh = scene.meshes[index];
  18102. if (abstractMesh instanceof BABYLON.Mesh) {
  18103. var mesh = abstractMesh;
  18104. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18105. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18106. }
  18107. }
  18108. }
  18109. // Particles Systems
  18110. serializationObject.particleSystems = [];
  18111. for (index = 0; index < scene.particleSystems.length; index++) {
  18112. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18113. }
  18114. // Lens flares
  18115. serializationObject.lensFlareSystems = [];
  18116. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18117. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18118. }
  18119. // Shadows
  18120. serializationObject.shadowGenerators = [];
  18121. for (index = 0; index < scene.lights.length; index++) {
  18122. light = scene.lights[index];
  18123. if (light.getShadowGenerator()) {
  18124. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18125. }
  18126. }
  18127. return serializationObject;
  18128. };
  18129. return SceneSerializer;
  18130. })();
  18131. BABYLON.SceneSerializer = SceneSerializer;
  18132. })(BABYLON || (BABYLON = {}));
  18133. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18134. (function (BABYLON) {
  18135. var SceneLoader = (function () {
  18136. function SceneLoader() {
  18137. }
  18138. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18139. get: function () {
  18140. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18141. },
  18142. set: function (value) {
  18143. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18144. },
  18145. enumerable: true,
  18146. configurable: true
  18147. });
  18148. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18149. get: function () {
  18150. return SceneLoader._ShowLoadingScreen;
  18151. },
  18152. set: function (value) {
  18153. SceneLoader._ShowLoadingScreen = value;
  18154. },
  18155. enumerable: true,
  18156. configurable: true
  18157. });
  18158. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18159. var dotPosition = sceneFilename.lastIndexOf(".");
  18160. var queryStringPosition = sceneFilename.indexOf("?");
  18161. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18162. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18163. var plugin = this._registeredPlugins[index];
  18164. if (plugin.extensions.indexOf(extension) !== -1) {
  18165. return plugin;
  18166. }
  18167. }
  18168. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18169. };
  18170. // Public functions
  18171. SceneLoader.RegisterPlugin = function (plugin) {
  18172. plugin.extensions = plugin.extensions.toLowerCase();
  18173. SceneLoader._registeredPlugins.push(plugin);
  18174. };
  18175. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18176. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18177. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18178. return;
  18179. }
  18180. var manifestChecked = function (success) {
  18181. scene.database = database;
  18182. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18183. var importMeshFromData = function (data) {
  18184. var meshes = [];
  18185. var particleSystems = [];
  18186. var skeletons = [];
  18187. try {
  18188. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18189. if (onerror) {
  18190. onerror(scene, 'unable to load the scene');
  18191. }
  18192. return;
  18193. }
  18194. }
  18195. catch (e) {
  18196. if (onerror) {
  18197. onerror(scene, e);
  18198. }
  18199. return;
  18200. }
  18201. if (onsuccess) {
  18202. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18203. onsuccess(meshes, particleSystems, skeletons);
  18204. }
  18205. };
  18206. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18207. // Direct load
  18208. importMeshFromData(sceneFilename.substr(5));
  18209. return;
  18210. }
  18211. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18212. importMeshFromData(data);
  18213. }, progressCallBack, database);
  18214. };
  18215. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18216. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18217. };
  18218. /**
  18219. * Load a scene
  18220. * @param rootUrl a string that defines the root url for scene and resources
  18221. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18222. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18223. */
  18224. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18225. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18226. };
  18227. /**
  18228. * Append a scene
  18229. * @param rootUrl a string that defines the root url for scene and resources
  18230. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18231. * @param scene is the instance of BABYLON.Scene to append to
  18232. */
  18233. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18234. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18235. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18236. return;
  18237. }
  18238. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18239. var database;
  18240. if (SceneLoader.ShowLoadingScreen) {
  18241. scene.getEngine().displayLoadingUI();
  18242. }
  18243. var loadSceneFromData = function (data) {
  18244. scene.database = database;
  18245. if (!plugin.load(scene, data, rootUrl)) {
  18246. if (onerror) {
  18247. onerror(scene);
  18248. }
  18249. scene.getEngine().hideLoadingUI();
  18250. return;
  18251. }
  18252. if (onsuccess) {
  18253. onsuccess(scene);
  18254. }
  18255. if (SceneLoader.ShowLoadingScreen) {
  18256. scene.executeWhenReady(function () {
  18257. scene.getEngine().hideLoadingUI();
  18258. });
  18259. }
  18260. };
  18261. var manifestChecked = function (success) {
  18262. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18263. };
  18264. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18265. // Direct load
  18266. loadSceneFromData(sceneFilename.substr(5));
  18267. return;
  18268. }
  18269. if (rootUrl.indexOf("file:") === -1) {
  18270. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18271. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18272. }
  18273. else {
  18274. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18275. }
  18276. };
  18277. // Flags
  18278. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18279. SceneLoader._ShowLoadingScreen = true;
  18280. // Members
  18281. SceneLoader._registeredPlugins = new Array();
  18282. return SceneLoader;
  18283. })();
  18284. BABYLON.SceneLoader = SceneLoader;
  18285. ;
  18286. })(BABYLON || (BABYLON = {}));
  18287. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18288. (function (BABYLON) {
  18289. var Internals;
  18290. (function (Internals) {
  18291. var checkColors4 = function (colors, count) {
  18292. // Check if color3 was used
  18293. if (colors.length === count * 3) {
  18294. var colors4 = [];
  18295. for (var index = 0; index < colors.length; index += 3) {
  18296. var newIndex = (index / 3) * 4;
  18297. colors4[newIndex] = colors[index];
  18298. colors4[newIndex + 1] = colors[index + 1];
  18299. colors4[newIndex + 2] = colors[index + 2];
  18300. colors4[newIndex + 3] = 1.0;
  18301. }
  18302. return colors4;
  18303. }
  18304. return colors;
  18305. };
  18306. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18307. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18308. texture.name = parsedTexture.name;
  18309. texture.hasAlpha = parsedTexture.hasAlpha;
  18310. texture.level = parsedTexture.level;
  18311. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18312. return texture;
  18313. };
  18314. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18315. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18316. return null;
  18317. }
  18318. if (parsedTexture.isCube) {
  18319. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18320. }
  18321. var texture;
  18322. if (parsedTexture.mirrorPlane) {
  18323. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18324. texture._waitingRenderList = parsedTexture.renderList;
  18325. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18326. }
  18327. else if (parsedTexture.isRenderTarget) {
  18328. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18329. texture._waitingRenderList = parsedTexture.renderList;
  18330. }
  18331. else {
  18332. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18333. }
  18334. texture.name = parsedTexture.name;
  18335. texture.hasAlpha = parsedTexture.hasAlpha;
  18336. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18337. texture.level = parsedTexture.level;
  18338. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18339. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18340. texture.uOffset = parsedTexture.uOffset;
  18341. texture.vOffset = parsedTexture.vOffset;
  18342. texture.uScale = parsedTexture.uScale;
  18343. texture.vScale = parsedTexture.vScale;
  18344. texture.uAng = parsedTexture.uAng;
  18345. texture.vAng = parsedTexture.vAng;
  18346. texture.wAng = parsedTexture.wAng;
  18347. texture.wrapU = parsedTexture.wrapU;
  18348. texture.wrapV = parsedTexture.wrapV;
  18349. // Animations
  18350. if (parsedTexture.animations) {
  18351. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18352. var parsedAnimation = parsedTexture.animations[animationIndex];
  18353. texture.animations.push(parseAnimation(parsedAnimation));
  18354. }
  18355. }
  18356. return texture;
  18357. };
  18358. var parseSkeleton = function (parsedSkeleton, scene) {
  18359. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18360. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18361. var parsedBone = parsedSkeleton.bones[index];
  18362. var parentBone = null;
  18363. if (parsedBone.parentBoneIndex > -1) {
  18364. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18365. }
  18366. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18367. if (parsedBone.animation) {
  18368. bone.animations.push(parseAnimation(parsedBone.animation));
  18369. }
  18370. }
  18371. return skeleton;
  18372. };
  18373. var parseFresnelParameters = function (parsedFresnelParameters) {
  18374. var fresnelParameters = new BABYLON.FresnelParameters();
  18375. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18376. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18377. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18378. fresnelParameters.bias = parsedFresnelParameters.bias;
  18379. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18380. return fresnelParameters;
  18381. };
  18382. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18383. var material;
  18384. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18385. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18386. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18387. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18388. material.specularPower = parsedMaterial.specularPower;
  18389. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18390. material.alpha = parsedMaterial.alpha;
  18391. material.id = parsedMaterial.id;
  18392. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18393. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18394. material.wireframe = parsedMaterial.wireframe;
  18395. if (parsedMaterial.diffuseTexture) {
  18396. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18397. }
  18398. if (parsedMaterial.diffuseFresnelParameters) {
  18399. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18400. }
  18401. if (parsedMaterial.ambientTexture) {
  18402. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18403. }
  18404. if (parsedMaterial.opacityTexture) {
  18405. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18406. }
  18407. if (parsedMaterial.opacityFresnelParameters) {
  18408. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18409. }
  18410. if (parsedMaterial.reflectionTexture) {
  18411. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18412. }
  18413. if (parsedMaterial.reflectionFresnelParameters) {
  18414. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18415. }
  18416. if (parsedMaterial.emissiveTexture) {
  18417. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18418. }
  18419. if (parsedMaterial.emissiveFresnelParameters) {
  18420. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18421. }
  18422. if (parsedMaterial.specularTexture) {
  18423. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18424. }
  18425. if (parsedMaterial.bumpTexture) {
  18426. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18427. }
  18428. return material;
  18429. };
  18430. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18431. for (var index = 0; index < parsedData.materials.length; index++) {
  18432. var parsedMaterial = parsedData.materials[index];
  18433. if (parsedMaterial.id === id) {
  18434. return parseMaterial(parsedMaterial, scene, rootUrl);
  18435. }
  18436. }
  18437. return null;
  18438. };
  18439. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18440. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18441. multiMaterial.id = parsedMultiMaterial.id;
  18442. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18443. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18444. var subMatId = parsedMultiMaterial.materials[matIndex];
  18445. if (subMatId) {
  18446. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18447. }
  18448. else {
  18449. multiMaterial.subMaterials.push(null);
  18450. }
  18451. }
  18452. return multiMaterial;
  18453. };
  18454. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18455. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18456. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18457. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18458. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18459. var parsedFlare = parsedLensFlareSystem.flares[index];
  18460. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18461. }
  18462. return lensFlareSystem;
  18463. };
  18464. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18465. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18466. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18467. if (parsedParticleSystem.textureName) {
  18468. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18469. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18470. }
  18471. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18472. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18473. particleSystem.minSize = parsedParticleSystem.minSize;
  18474. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18475. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18476. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18477. particleSystem.emitter = emitter;
  18478. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18479. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18480. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18481. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18482. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18483. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18484. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18485. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18486. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18487. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18488. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18489. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18490. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18491. particleSystem.start();
  18492. return particleSystem;
  18493. };
  18494. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18495. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18496. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18497. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18498. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18499. shadowGenerator.getShadowMap().renderList.push(mesh);
  18500. }
  18501. if (parsedShadowGenerator.usePoissonSampling) {
  18502. shadowGenerator.usePoissonSampling = true;
  18503. }
  18504. else {
  18505. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18506. }
  18507. return shadowGenerator;
  18508. };
  18509. var parseAnimation = function (parsedAnimation) {
  18510. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18511. var dataType = parsedAnimation.dataType;
  18512. var keys = [];
  18513. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18514. var key = parsedAnimation.keys[index];
  18515. var data;
  18516. switch (dataType) {
  18517. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18518. data = key.values[0];
  18519. break;
  18520. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18521. data = BABYLON.Quaternion.FromArray(key.values);
  18522. break;
  18523. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18524. data = BABYLON.Matrix.FromArray(key.values);
  18525. break;
  18526. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18527. default:
  18528. data = BABYLON.Vector3.FromArray(key.values);
  18529. break;
  18530. }
  18531. keys.push({
  18532. frame: key.frame,
  18533. value: data
  18534. });
  18535. }
  18536. animation.setKeys(keys);
  18537. return animation;
  18538. };
  18539. var parseLight = function (parsedLight, scene) {
  18540. var light;
  18541. switch (parsedLight.type) {
  18542. case 0:
  18543. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18544. break;
  18545. case 1:
  18546. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18547. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18548. break;
  18549. case 2:
  18550. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18551. break;
  18552. case 3:
  18553. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18554. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18555. break;
  18556. }
  18557. light.id = parsedLight.id;
  18558. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18559. if (parsedLight.intensity !== undefined) {
  18560. light.intensity = parsedLight.intensity;
  18561. }
  18562. if (parsedLight.range) {
  18563. light.range = parsedLight.range;
  18564. }
  18565. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18566. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18567. if (parsedLight.excludedMeshesIds) {
  18568. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18569. }
  18570. // Parent
  18571. if (parsedLight.parentId) {
  18572. light._waitingParentId = parsedLight.parentId;
  18573. }
  18574. if (parsedLight.includedOnlyMeshesIds) {
  18575. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18576. }
  18577. // Animations
  18578. if (parsedLight.animations) {
  18579. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18580. var parsedAnimation = parsedLight.animations[animationIndex];
  18581. light.animations.push(parseAnimation(parsedAnimation));
  18582. }
  18583. }
  18584. if (parsedLight.autoAnimate) {
  18585. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18586. }
  18587. };
  18588. var parseCamera = function (parsedCamera, scene) {
  18589. var camera;
  18590. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18591. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18592. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18593. var alpha = parsedCamera.alpha;
  18594. var beta = parsedCamera.beta;
  18595. var radius = parsedCamera.radius;
  18596. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18597. var eye_space = parsedCamera.eye_space;
  18598. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18599. }
  18600. else {
  18601. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18602. }
  18603. }
  18604. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18605. eye_space = parsedCamera.eye_space;
  18606. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18607. }
  18608. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18609. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18610. }
  18611. else if (parsedCamera.type === "FollowCamera") {
  18612. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18613. camera.heightOffset = parsedCamera.heightOffset;
  18614. camera.radius = parsedCamera.radius;
  18615. camera.rotationOffset = parsedCamera.rotationOffset;
  18616. if (lockedTargetMesh)
  18617. camera.target = lockedTargetMesh;
  18618. }
  18619. else if (parsedCamera.type === "GamepadCamera") {
  18620. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18621. }
  18622. else if (parsedCamera.type === "OculusCamera") {
  18623. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18624. }
  18625. else if (parsedCamera.type === "OculusGamepadCamera") {
  18626. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18627. }
  18628. else if (parsedCamera.type === "TouchCamera") {
  18629. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18630. }
  18631. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18632. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18633. }
  18634. else if (parsedCamera.type === "WebVRCamera") {
  18635. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18636. }
  18637. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18638. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18639. }
  18640. else {
  18641. // Free Camera is the default value
  18642. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18643. }
  18644. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18645. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18646. camera.lockedTarget = lockedTargetMesh;
  18647. }
  18648. camera.id = parsedCamera.id;
  18649. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18650. // Parent
  18651. if (parsedCamera.parentId) {
  18652. camera._waitingParentId = parsedCamera.parentId;
  18653. }
  18654. // Target
  18655. if (parsedCamera.target) {
  18656. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18657. }
  18658. else {
  18659. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18660. }
  18661. camera.fov = parsedCamera.fov;
  18662. camera.minZ = parsedCamera.minZ;
  18663. camera.maxZ = parsedCamera.maxZ;
  18664. camera.speed = parsedCamera.speed;
  18665. camera.inertia = parsedCamera.inertia;
  18666. camera.checkCollisions = parsedCamera.checkCollisions;
  18667. camera.applyGravity = parsedCamera.applyGravity;
  18668. if (parsedCamera.ellipsoid) {
  18669. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18670. }
  18671. // Animations
  18672. if (parsedCamera.animations) {
  18673. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18674. var parsedAnimation = parsedCamera.animations[animationIndex];
  18675. camera.animations.push(parseAnimation(parsedAnimation));
  18676. }
  18677. }
  18678. if (parsedCamera.autoAnimate) {
  18679. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18680. }
  18681. // Layer Mask
  18682. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18683. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18684. }
  18685. else {
  18686. camera.layerMask = 0xFFFFFFFF;
  18687. }
  18688. return camera;
  18689. };
  18690. var parseGeometry = function (parsedGeometry, scene) {
  18691. var id = parsedGeometry.id;
  18692. return scene.getGeometryByID(id);
  18693. };
  18694. var parseBox = function (parsedBox, scene) {
  18695. if (parseGeometry(parsedBox, scene)) {
  18696. return null; // null since geometry could be something else than a box...
  18697. }
  18698. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18699. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18700. scene.pushGeometry(box, true);
  18701. return box;
  18702. };
  18703. var parseSphere = function (parsedSphere, scene) {
  18704. if (parseGeometry(parsedSphere, scene)) {
  18705. return null; // null since geometry could be something else than a sphere...
  18706. }
  18707. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18708. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18709. scene.pushGeometry(sphere, true);
  18710. return sphere;
  18711. };
  18712. var parseCylinder = function (parsedCylinder, scene) {
  18713. if (parseGeometry(parsedCylinder, scene)) {
  18714. return null; // null since geometry could be something else than a cylinder...
  18715. }
  18716. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18717. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18718. scene.pushGeometry(cylinder, true);
  18719. return cylinder;
  18720. };
  18721. var parseTorus = function (parsedTorus, scene) {
  18722. if (parseGeometry(parsedTorus, scene)) {
  18723. return null; // null since geometry could be something else than a torus...
  18724. }
  18725. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18726. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18727. scene.pushGeometry(torus, true);
  18728. return torus;
  18729. };
  18730. var parseGround = function (parsedGround, scene) {
  18731. if (parseGeometry(parsedGround, scene)) {
  18732. return null; // null since geometry could be something else than a ground...
  18733. }
  18734. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18735. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18736. scene.pushGeometry(ground, true);
  18737. return ground;
  18738. };
  18739. var parsePlane = function (parsedPlane, scene) {
  18740. if (parseGeometry(parsedPlane, scene)) {
  18741. return null; // null since geometry could be something else than a plane...
  18742. }
  18743. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18744. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18745. scene.pushGeometry(plane, true);
  18746. return plane;
  18747. };
  18748. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18749. if (parseGeometry(parsedTorusKnot, scene)) {
  18750. return null; // null since geometry could be something else than a torusKnot...
  18751. }
  18752. 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);
  18753. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18754. scene.pushGeometry(torusKnot, true);
  18755. return torusKnot;
  18756. };
  18757. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18758. if (parseGeometry(parsedVertexData, scene)) {
  18759. return null; // null since geometry could be a primitive
  18760. }
  18761. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18762. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18763. if (parsedVertexData.delayLoadingFile) {
  18764. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18765. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18766. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18767. geometry._delayInfo = [];
  18768. if (parsedVertexData.hasUVs) {
  18769. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18770. }
  18771. if (parsedVertexData.hasUVs2) {
  18772. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18773. }
  18774. if (parsedVertexData.hasColors) {
  18775. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18776. }
  18777. if (parsedVertexData.hasMatricesIndices) {
  18778. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18779. }
  18780. if (parsedVertexData.hasMatricesWeights) {
  18781. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18782. }
  18783. geometry._delayLoadingFunction = importVertexData;
  18784. }
  18785. else {
  18786. importVertexData(parsedVertexData, geometry);
  18787. }
  18788. scene.pushGeometry(geometry, true);
  18789. return geometry;
  18790. };
  18791. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18792. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18793. mesh.id = parsedMesh.id;
  18794. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18795. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18796. if (parsedMesh.rotationQuaternion) {
  18797. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18798. }
  18799. else if (parsedMesh.rotation) {
  18800. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18801. }
  18802. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18803. if (parsedMesh.localMatrix) {
  18804. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18805. }
  18806. else if (parsedMesh.pivotMatrix) {
  18807. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18808. }
  18809. mesh.setEnabled(parsedMesh.isEnabled);
  18810. mesh.isVisible = parsedMesh.isVisible;
  18811. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18812. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18813. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18814. if (parsedMesh.applyFog !== undefined) {
  18815. mesh.applyFog = parsedMesh.applyFog;
  18816. }
  18817. if (parsedMesh.pickable !== undefined) {
  18818. mesh.isPickable = parsedMesh.pickable;
  18819. }
  18820. if (parsedMesh.alphaIndex !== undefined) {
  18821. mesh.alphaIndex = parsedMesh.alphaIndex;
  18822. }
  18823. mesh.receiveShadows = parsedMesh.receiveShadows;
  18824. mesh.billboardMode = parsedMesh.billboardMode;
  18825. if (parsedMesh.visibility !== undefined) {
  18826. mesh.visibility = parsedMesh.visibility;
  18827. }
  18828. mesh.checkCollisions = parsedMesh.checkCollisions;
  18829. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18830. // Parent
  18831. if (parsedMesh.parentId) {
  18832. mesh._waitingParentId = parsedMesh.parentId;
  18833. }
  18834. // Actions
  18835. if (parsedMesh.actions !== undefined) {
  18836. mesh._waitingActions = parsedMesh.actions;
  18837. }
  18838. // Geometry
  18839. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18840. if (parsedMesh.delayLoadingFile) {
  18841. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18842. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18843. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18844. if (parsedMesh._binaryInfo) {
  18845. mesh._binaryInfo = parsedMesh._binaryInfo;
  18846. }
  18847. mesh._delayInfo = [];
  18848. if (parsedMesh.hasUVs) {
  18849. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18850. }
  18851. if (parsedMesh.hasUVs2) {
  18852. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18853. }
  18854. if (parsedMesh.hasColors) {
  18855. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18856. }
  18857. if (parsedMesh.hasMatricesIndices) {
  18858. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18859. }
  18860. if (parsedMesh.hasMatricesWeights) {
  18861. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18862. }
  18863. mesh._delayLoadingFunction = importGeometry;
  18864. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18865. mesh._checkDelayState();
  18866. }
  18867. }
  18868. else {
  18869. importGeometry(parsedMesh, mesh);
  18870. }
  18871. // Material
  18872. if (parsedMesh.materialId) {
  18873. mesh.setMaterialByID(parsedMesh.materialId);
  18874. }
  18875. else {
  18876. mesh.material = null;
  18877. }
  18878. // Skeleton
  18879. if (parsedMesh.skeletonId > -1) {
  18880. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18881. }
  18882. // Physics
  18883. if (parsedMesh.physicsImpostor) {
  18884. if (!scene.isPhysicsEnabled()) {
  18885. scene.enablePhysics();
  18886. }
  18887. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18888. }
  18889. // Animations
  18890. if (parsedMesh.animations) {
  18891. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18892. var parsedAnimation = parsedMesh.animations[animationIndex];
  18893. mesh.animations.push(parseAnimation(parsedAnimation));
  18894. }
  18895. }
  18896. if (parsedMesh.autoAnimate) {
  18897. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18898. }
  18899. // Layer Mask
  18900. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18901. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18902. }
  18903. else {
  18904. mesh.layerMask = 0xFFFFFFFF;
  18905. }
  18906. // Instances
  18907. if (parsedMesh.instances) {
  18908. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18909. var parsedInstance = parsedMesh.instances[index];
  18910. var instance = mesh.createInstance(parsedInstance.name);
  18911. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18912. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18913. if (parsedInstance.rotationQuaternion) {
  18914. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18915. }
  18916. else if (parsedInstance.rotation) {
  18917. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18918. }
  18919. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18920. instance.checkCollisions = mesh.checkCollisions;
  18921. if (parsedMesh.animations) {
  18922. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18923. parsedAnimation = parsedMesh.animations[animationIndex];
  18924. instance.animations.push(parseAnimation(parsedAnimation));
  18925. }
  18926. }
  18927. }
  18928. }
  18929. return mesh;
  18930. };
  18931. var parseActions = function (parsedActions, object, scene) {
  18932. var actionManager = new BABYLON.ActionManager(scene);
  18933. if (object === null)
  18934. scene.actionManager = actionManager;
  18935. else
  18936. object.actionManager = actionManager;
  18937. // instanciate a new object
  18938. var instanciate = function (name, params) {
  18939. var newInstance = Object.create(BABYLON[name].prototype);
  18940. newInstance.constructor.apply(newInstance, params);
  18941. return newInstance;
  18942. };
  18943. var parseParameter = function (name, value, target, propertyPath) {
  18944. if (propertyPath === null) {
  18945. // String, boolean or float
  18946. var floatValue = parseFloat(value);
  18947. if (value === "true" || value === "false")
  18948. return value === "true";
  18949. else
  18950. return isNaN(floatValue) ? value : floatValue;
  18951. }
  18952. var effectiveTarget = propertyPath.split(".");
  18953. var values = value.split(",");
  18954. for (var i = 0; i < effectiveTarget.length; i++) {
  18955. target = target[effectiveTarget[i]];
  18956. }
  18957. // Return appropriate value with its type
  18958. if (target instanceof Boolean)
  18959. return values[0] === "true";
  18960. if (target instanceof String)
  18961. return values[0];
  18962. // Parameters with multiple values such as Vector3 etc.
  18963. var split = new Array();
  18964. for (var i = 0; i < values.length; i++)
  18965. split.push(parseFloat(values[i]));
  18966. if (target instanceof BABYLON.Vector3)
  18967. return BABYLON.Vector3.FromArray(split);
  18968. if (target instanceof BABYLON.Vector4)
  18969. return BABYLON.Vector4.FromArray(split);
  18970. if (target instanceof BABYLON.Color3)
  18971. return BABYLON.Color3.FromArray(split);
  18972. if (target instanceof BABYLON.Color4)
  18973. return BABYLON.Color4.FromArray(split);
  18974. return parseFloat(values[0]);
  18975. };
  18976. // traverse graph per trigger
  18977. var traverse = function (parsedAction, trigger, condition, action) {
  18978. var parameters = new Array();
  18979. var target = null;
  18980. var propertyPath = null;
  18981. // Parameters
  18982. if (parsedAction.type === 2)
  18983. parameters.push(actionManager);
  18984. else
  18985. parameters.push(trigger);
  18986. for (var i = 0; i < parsedAction.properties.length; i++) {
  18987. var value = parsedAction.properties[i].value;
  18988. var name = parsedAction.properties[i].name;
  18989. if (name === "target")
  18990. value = target = scene.getNodeByName(value);
  18991. else if (name === "parent")
  18992. value = scene.getNodeByName(value);
  18993. else if (name === "sound")
  18994. value = scene.getSoundByName(value);
  18995. else if (name !== "propertyPath") {
  18996. if (parsedAction.type === 2 && name === "operator")
  18997. value = BABYLON.ValueCondition[value];
  18998. else
  18999. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19000. }
  19001. else {
  19002. propertyPath = value;
  19003. }
  19004. parameters.push(value);
  19005. }
  19006. parameters.push(condition);
  19007. // If interpolate value action
  19008. if (parsedAction.name === "InterpolateValueAction") {
  19009. var param = parameters[parameters.length - 2];
  19010. parameters[parameters.length - 1] = param;
  19011. parameters[parameters.length - 2] = condition;
  19012. }
  19013. // Action or condition(s)
  19014. var newAction = instanciate(parsedAction.name, parameters);
  19015. if (newAction instanceof BABYLON.Condition) {
  19016. condition = newAction;
  19017. newAction = action;
  19018. }
  19019. else {
  19020. condition = null;
  19021. if (action)
  19022. action.then(newAction);
  19023. else
  19024. actionManager.registerAction(newAction);
  19025. }
  19026. for (var i = 0; i < parsedAction.children.length; i++)
  19027. traverse(parsedAction.children[i], trigger, condition, newAction);
  19028. };
  19029. for (var i = 0; i < parsedActions.children.length; i++) {
  19030. var triggerParams;
  19031. var trigger = parsedActions.children[i];
  19032. if (trigger.properties.length > 0) {
  19033. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19034. }
  19035. else
  19036. triggerParams = BABYLON.ActionManager[trigger.name];
  19037. for (var j = 0; j < trigger.children.length; j++)
  19038. traverse(trigger.children[j], triggerParams, null, null);
  19039. }
  19040. };
  19041. var parseSound = function (parsedSound, scene, rootUrl) {
  19042. var soundName = parsedSound.name;
  19043. var soundUrl = rootUrl + soundName;
  19044. var options = {
  19045. autoplay: parsedSound.autoplay,
  19046. loop: parsedSound.loop,
  19047. volume: parsedSound.volume,
  19048. spatialSound: parsedSound.spatialSound,
  19049. maxDistance: parsedSound.maxDistance,
  19050. rolloffFactor: parsedSound.rolloffFactor,
  19051. refDistance: parsedSound.refDistance,
  19052. distanceModel: parsedSound.distanceModel,
  19053. panningModel: parsedSound.panningModel,
  19054. playbackRate: parsedSound.playbackRate
  19055. };
  19056. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19057. scene._removePendingData(newSound);
  19058. }, options);
  19059. scene._addPendingData(newSound);
  19060. if (parsedSound.position) {
  19061. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19062. newSound.setPosition(soundPosition);
  19063. }
  19064. if (parsedSound.isDirectional) {
  19065. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19066. if (parsedSound.localDirectionToMesh) {
  19067. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19068. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19069. }
  19070. }
  19071. if (parsedSound.connectedMeshId) {
  19072. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19073. if (connectedMesh) {
  19074. newSound.attachToMesh(connectedMesh);
  19075. }
  19076. }
  19077. };
  19078. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19079. names = (names instanceof Array) ? names : [names];
  19080. for (var i in names) {
  19081. if (mesh.name === names[i]) {
  19082. hierarchyIds.push(mesh.id);
  19083. return true;
  19084. }
  19085. }
  19086. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19087. hierarchyIds.push(mesh.id);
  19088. return true;
  19089. }
  19090. return false;
  19091. };
  19092. var importVertexData = function (parsedVertexData, geometry) {
  19093. var vertexData = new BABYLON.VertexData();
  19094. // positions
  19095. var positions = parsedVertexData.positions;
  19096. if (positions) {
  19097. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19098. }
  19099. // normals
  19100. var normals = parsedVertexData.normals;
  19101. if (normals) {
  19102. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19103. }
  19104. // uvs
  19105. var uvs = parsedVertexData.uvs;
  19106. if (uvs) {
  19107. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19108. }
  19109. // uv2s
  19110. var uv2s = parsedVertexData.uv2s;
  19111. if (uv2s) {
  19112. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19113. }
  19114. // colors
  19115. var colors = parsedVertexData.colors;
  19116. if (colors) {
  19117. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19118. }
  19119. // matricesIndices
  19120. var matricesIndices = parsedVertexData.matricesIndices;
  19121. if (matricesIndices) {
  19122. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19123. }
  19124. // matricesWeights
  19125. var matricesWeights = parsedVertexData.matricesWeights;
  19126. if (matricesWeights) {
  19127. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19128. }
  19129. // indices
  19130. var indices = parsedVertexData.indices;
  19131. if (indices) {
  19132. vertexData.indices = indices;
  19133. }
  19134. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19135. };
  19136. var importGeometry = function (parsedGeometry, mesh) {
  19137. var scene = mesh.getScene();
  19138. // Geometry
  19139. var geometryId = parsedGeometry.geometryId;
  19140. if (geometryId) {
  19141. var geometry = scene.getGeometryByID(geometryId);
  19142. if (geometry) {
  19143. geometry.applyToMesh(mesh);
  19144. }
  19145. }
  19146. else if (parsedGeometry instanceof ArrayBuffer) {
  19147. var binaryInfo = mesh._binaryInfo;
  19148. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19149. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19150. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19151. }
  19152. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19153. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19154. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19155. }
  19156. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19157. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19158. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19159. }
  19160. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19161. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19162. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19163. }
  19164. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19165. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19166. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19167. }
  19168. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19169. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19171. }
  19172. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19173. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19174. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19175. }
  19176. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19177. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19178. mesh.setIndices(indicesData);
  19179. }
  19180. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19181. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19182. mesh.subMeshes = [];
  19183. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19184. var materialIndex = subMeshesData[(i * 5) + 0];
  19185. var verticesStart = subMeshesData[(i * 5) + 1];
  19186. var verticesCount = subMeshesData[(i * 5) + 2];
  19187. var indexStart = subMeshesData[(i * 5) + 3];
  19188. var indexCount = subMeshesData[(i * 5) + 4];
  19189. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19190. }
  19191. }
  19192. }
  19193. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19194. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19195. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19196. if (parsedGeometry.uvs) {
  19197. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19198. }
  19199. if (parsedGeometry.uvs2) {
  19200. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19201. }
  19202. if (parsedGeometry.colors) {
  19203. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19204. }
  19205. if (parsedGeometry.matricesIndices) {
  19206. if (!parsedGeometry.matricesIndices._isExpanded) {
  19207. var floatIndices = [];
  19208. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19209. var matricesIndex = parsedGeometry.matricesIndices[i];
  19210. floatIndices.push(matricesIndex & 0x000000FF);
  19211. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19212. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19213. floatIndices.push(matricesIndex >> 24);
  19214. }
  19215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19216. }
  19217. else {
  19218. delete parsedGeometry.matricesIndices._isExpanded;
  19219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19220. }
  19221. }
  19222. if (parsedGeometry.matricesWeights) {
  19223. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19224. }
  19225. mesh.setIndices(parsedGeometry.indices);
  19226. // SubMeshes
  19227. if (parsedGeometry.subMeshes) {
  19228. mesh.subMeshes = [];
  19229. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19230. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19231. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19232. }
  19233. }
  19234. }
  19235. // Flat shading
  19236. if (mesh._shouldGenerateFlatShading) {
  19237. mesh.convertToFlatShadedMesh();
  19238. delete mesh._shouldGenerateFlatShading;
  19239. }
  19240. // Update
  19241. mesh.computeWorldMatrix(true);
  19242. // Octree
  19243. if (scene._selectionOctree) {
  19244. scene._selectionOctree.addMesh(mesh);
  19245. }
  19246. };
  19247. BABYLON.SceneLoader.RegisterPlugin({
  19248. extensions: ".babylon",
  19249. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19250. var parsedData = JSON.parse(data);
  19251. var loadedSkeletonsIds = [];
  19252. var loadedMaterialsIds = [];
  19253. var hierarchyIds = [];
  19254. for (var index = 0; index < parsedData.meshes.length; index++) {
  19255. var parsedMesh = parsedData.meshes[index];
  19256. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19257. if (meshesNames instanceof Array) {
  19258. // Remove found mesh name from list.
  19259. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19260. }
  19261. // Material ?
  19262. if (parsedMesh.materialId) {
  19263. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19264. if (!materialFound) {
  19265. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19266. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19267. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19268. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19269. var subMatId = parsedMultiMaterial.materials[matIndex];
  19270. loadedMaterialsIds.push(subMatId);
  19271. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19272. }
  19273. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19274. parseMultiMaterial(parsedMultiMaterial, scene);
  19275. materialFound = true;
  19276. break;
  19277. }
  19278. }
  19279. }
  19280. if (!materialFound) {
  19281. loadedMaterialsIds.push(parsedMesh.materialId);
  19282. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19283. }
  19284. }
  19285. // Skeleton ?
  19286. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19287. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19288. if (!skeletonAlreadyLoaded) {
  19289. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19290. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19291. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19292. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19293. loadedSkeletonsIds.push(parsedSkeleton.id);
  19294. }
  19295. }
  19296. }
  19297. }
  19298. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19299. meshes.push(mesh);
  19300. }
  19301. }
  19302. for (index = 0; index < scene.meshes.length; index++) {
  19303. var currentMesh = scene.meshes[index];
  19304. if (currentMesh._waitingParentId) {
  19305. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19306. currentMesh._waitingParentId = undefined;
  19307. }
  19308. }
  19309. // Particles
  19310. if (parsedData.particleSystems) {
  19311. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19312. var parsedParticleSystem = parsedData.particleSystems[index];
  19313. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19314. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19315. }
  19316. }
  19317. }
  19318. return true;
  19319. },
  19320. load: function (scene, data, rootUrl) {
  19321. var parsedData = JSON.parse(data);
  19322. // Scene
  19323. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19324. scene.autoClear = parsedData.autoClear;
  19325. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19326. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19327. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19328. // Fog
  19329. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19330. scene.fogMode = parsedData.fogMode;
  19331. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19332. scene.fogStart = parsedData.fogStart;
  19333. scene.fogEnd = parsedData.fogEnd;
  19334. scene.fogDensity = parsedData.fogDensity;
  19335. }
  19336. for (var index = 0; index < parsedData.lights.length; index++) {
  19337. var parsedLight = parsedData.lights[index];
  19338. parseLight(parsedLight, scene);
  19339. }
  19340. // Materials
  19341. if (parsedData.materials) {
  19342. for (index = 0; index < parsedData.materials.length; index++) {
  19343. var parsedMaterial = parsedData.materials[index];
  19344. parseMaterial(parsedMaterial, scene, rootUrl);
  19345. }
  19346. }
  19347. if (parsedData.multiMaterials) {
  19348. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19349. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19350. parseMultiMaterial(parsedMultiMaterial, scene);
  19351. }
  19352. }
  19353. // Skeletons
  19354. if (parsedData.skeletons) {
  19355. for (index = 0; index < parsedData.skeletons.length; index++) {
  19356. var parsedSkeleton = parsedData.skeletons[index];
  19357. parseSkeleton(parsedSkeleton, scene);
  19358. }
  19359. }
  19360. // Geometries
  19361. var geometries = parsedData.geometries;
  19362. if (geometries) {
  19363. // Boxes
  19364. var boxes = geometries.boxes;
  19365. if (boxes) {
  19366. for (index = 0; index < boxes.length; index++) {
  19367. var parsedBox = boxes[index];
  19368. parseBox(parsedBox, scene);
  19369. }
  19370. }
  19371. // Spheres
  19372. var spheres = geometries.spheres;
  19373. if (spheres) {
  19374. for (index = 0; index < spheres.length; index++) {
  19375. var parsedSphere = spheres[index];
  19376. parseSphere(parsedSphere, scene);
  19377. }
  19378. }
  19379. // Cylinders
  19380. var cylinders = geometries.cylinders;
  19381. if (cylinders) {
  19382. for (index = 0; index < cylinders.length; index++) {
  19383. var parsedCylinder = cylinders[index];
  19384. parseCylinder(parsedCylinder, scene);
  19385. }
  19386. }
  19387. // Toruses
  19388. var toruses = geometries.toruses;
  19389. if (toruses) {
  19390. for (index = 0; index < toruses.length; index++) {
  19391. var parsedTorus = toruses[index];
  19392. parseTorus(parsedTorus, scene);
  19393. }
  19394. }
  19395. // Grounds
  19396. var grounds = geometries.grounds;
  19397. if (grounds) {
  19398. for (index = 0; index < grounds.length; index++) {
  19399. var parsedGround = grounds[index];
  19400. parseGround(parsedGround, scene);
  19401. }
  19402. }
  19403. // Planes
  19404. var planes = geometries.planes;
  19405. if (planes) {
  19406. for (index = 0; index < planes.length; index++) {
  19407. var parsedPlane = planes[index];
  19408. parsePlane(parsedPlane, scene);
  19409. }
  19410. }
  19411. // TorusKnots
  19412. var torusKnots = geometries.torusKnots;
  19413. if (torusKnots) {
  19414. for (index = 0; index < torusKnots.length; index++) {
  19415. var parsedTorusKnot = torusKnots[index];
  19416. parseTorusKnot(parsedTorusKnot, scene);
  19417. }
  19418. }
  19419. // VertexData
  19420. var vertexData = geometries.vertexData;
  19421. if (vertexData) {
  19422. for (index = 0; index < vertexData.length; index++) {
  19423. var parsedVertexData = vertexData[index];
  19424. parseVertexData(parsedVertexData, scene, rootUrl);
  19425. }
  19426. }
  19427. }
  19428. for (index = 0; index < parsedData.meshes.length; index++) {
  19429. var parsedMesh = parsedData.meshes[index];
  19430. parseMesh(parsedMesh, scene, rootUrl);
  19431. }
  19432. for (index = 0; index < parsedData.cameras.length; index++) {
  19433. var parsedCamera = parsedData.cameras[index];
  19434. parseCamera(parsedCamera, scene);
  19435. }
  19436. if (parsedData.activeCameraID) {
  19437. scene.setActiveCameraByID(parsedData.activeCameraID);
  19438. }
  19439. for (index = 0; index < scene.cameras.length; index++) {
  19440. var camera = scene.cameras[index];
  19441. if (camera._waitingParentId) {
  19442. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19443. camera._waitingParentId = undefined;
  19444. }
  19445. }
  19446. for (index = 0; index < scene.lights.length; index++) {
  19447. var light = scene.lights[index];
  19448. if (light._waitingParentId) {
  19449. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19450. light._waitingParentId = undefined;
  19451. }
  19452. }
  19453. // Sounds
  19454. if (parsedData.sounds) {
  19455. for (index = 0; index < parsedData.sounds.length; index++) {
  19456. var parsedSound = parsedData.sounds[index];
  19457. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19458. parseSound(parsedSound, scene, rootUrl);
  19459. }
  19460. else {
  19461. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19462. }
  19463. }
  19464. }
  19465. for (index = 0; index < scene.meshes.length; index++) {
  19466. var mesh = scene.meshes[index];
  19467. if (mesh._waitingParentId) {
  19468. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19469. mesh._waitingParentId = undefined;
  19470. }
  19471. if (mesh._waitingActions) {
  19472. parseActions(mesh._waitingActions, mesh, scene);
  19473. mesh._waitingActions = undefined;
  19474. }
  19475. }
  19476. // Particles Systems
  19477. if (parsedData.particleSystems) {
  19478. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19479. var parsedParticleSystem = parsedData.particleSystems[index];
  19480. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19481. }
  19482. }
  19483. // Lens flares
  19484. if (parsedData.lensFlareSystems) {
  19485. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19486. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19487. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19488. }
  19489. }
  19490. // Shadows
  19491. if (parsedData.shadowGenerators) {
  19492. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19493. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19494. parseShadowGenerator(parsedShadowGenerator, scene);
  19495. }
  19496. }
  19497. // Actions (scene)
  19498. if (parsedData.actions) {
  19499. parseActions(parsedData.actions, null, scene);
  19500. }
  19501. // Finish
  19502. return true;
  19503. }
  19504. });
  19505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19506. })(BABYLON || (BABYLON = {}));
  19507. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19508. (function (BABYLON) {
  19509. // Unique ID when we import meshes from Babylon to CSG
  19510. var currentCSGMeshId = 0;
  19511. // # class Vertex
  19512. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19513. // one to provide additional features like texture coordinates and vertex
  19514. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19515. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19516. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19517. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19518. // is not used anywhere else.
  19519. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19520. var Vertex = (function () {
  19521. function Vertex(pos, normal, uv) {
  19522. this.pos = pos;
  19523. this.normal = normal;
  19524. this.uv = uv;
  19525. }
  19526. Vertex.prototype.clone = function () {
  19527. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19528. };
  19529. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19530. // orientation of a polygon is flipped.
  19531. Vertex.prototype.flip = function () {
  19532. this.normal = this.normal.scale(-1);
  19533. };
  19534. // Create a new vertex between this vertex and `other` by linearly
  19535. // interpolating all properties using a parameter of `t`. Subclasses should
  19536. // override this to interpolate additional properties.
  19537. Vertex.prototype.interpolate = function (other, t) {
  19538. 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));
  19539. };
  19540. return Vertex;
  19541. })();
  19542. // # class Plane
  19543. // Represents a plane in 3D space.
  19544. var Plane = (function () {
  19545. function Plane(normal, w) {
  19546. this.normal = normal;
  19547. this.w = w;
  19548. }
  19549. Plane.FromPoints = function (a, b, c) {
  19550. var v0 = c.subtract(a);
  19551. var v1 = b.subtract(a);
  19552. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19553. return null;
  19554. }
  19555. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19556. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19557. };
  19558. Plane.prototype.clone = function () {
  19559. return new Plane(this.normal.clone(), this.w);
  19560. };
  19561. Plane.prototype.flip = function () {
  19562. this.normal.scaleInPlace(-1);
  19563. this.w = -this.w;
  19564. };
  19565. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19566. // fragments in the appropriate lists. Coplanar polygons go into either
  19567. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19568. // respect to this plane. Polygons in front or in back of this plane go into
  19569. // either `front` or `back`.
  19570. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19571. var COPLANAR = 0;
  19572. var FRONT = 1;
  19573. var BACK = 2;
  19574. var SPANNING = 3;
  19575. // Classify each point as well as the entire polygon into one of the above
  19576. // four classes.
  19577. var polygonType = 0;
  19578. var types = [];
  19579. for (var i = 0; i < polygon.vertices.length; i++) {
  19580. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19581. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19582. polygonType |= type;
  19583. types.push(type);
  19584. }
  19585. switch (polygonType) {
  19586. case COPLANAR:
  19587. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19588. break;
  19589. case FRONT:
  19590. front.push(polygon);
  19591. break;
  19592. case BACK:
  19593. back.push(polygon);
  19594. break;
  19595. case SPANNING:
  19596. var f = [], b = [];
  19597. for (i = 0; i < polygon.vertices.length; i++) {
  19598. var j = (i + 1) % polygon.vertices.length;
  19599. var ti = types[i], tj = types[j];
  19600. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19601. if (ti != BACK)
  19602. f.push(vi);
  19603. if (ti != FRONT)
  19604. b.push(ti != BACK ? vi.clone() : vi);
  19605. if ((ti | tj) == SPANNING) {
  19606. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19607. var v = vi.interpolate(vj, t);
  19608. f.push(v);
  19609. b.push(v.clone());
  19610. }
  19611. }
  19612. if (f.length >= 3) {
  19613. var poly = new Polygon(f, polygon.shared);
  19614. if (poly.plane)
  19615. front.push(poly);
  19616. }
  19617. if (b.length >= 3) {
  19618. poly = new Polygon(b, polygon.shared);
  19619. if (poly.plane)
  19620. back.push(poly);
  19621. }
  19622. break;
  19623. }
  19624. };
  19625. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19626. // point is on the plane.
  19627. Plane.EPSILON = 1e-5;
  19628. return Plane;
  19629. })();
  19630. // # class Polygon
  19631. // Represents a convex polygon. The vertices used to initialize a polygon must
  19632. // be coplanar and form a convex loop.
  19633. //
  19634. // Each convex polygon has a `shared` property, which is shared between all
  19635. // polygons that are clones of each other or were split from the same polygon.
  19636. // This can be used to define per-polygon properties (such as surface color).
  19637. var Polygon = (function () {
  19638. function Polygon(vertices, shared) {
  19639. this.vertices = vertices;
  19640. this.shared = shared;
  19641. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19642. }
  19643. Polygon.prototype.clone = function () {
  19644. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19645. return new Polygon(vertices, this.shared);
  19646. };
  19647. Polygon.prototype.flip = function () {
  19648. this.vertices.reverse().map(function (v) {
  19649. v.flip();
  19650. });
  19651. this.plane.flip();
  19652. };
  19653. return Polygon;
  19654. })();
  19655. // # class Node
  19656. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19657. // by picking a polygon to split along. That polygon (and all other coplanar
  19658. // polygons) are added directly to that node and the other polygons are added to
  19659. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19660. // no distinction between internal and leaf nodes.
  19661. var Node = (function () {
  19662. function Node(polygons) {
  19663. this.plane = null;
  19664. this.front = null;
  19665. this.back = null;
  19666. this.polygons = [];
  19667. if (polygons) {
  19668. this.build(polygons);
  19669. }
  19670. }
  19671. Node.prototype.clone = function () {
  19672. var node = new Node();
  19673. node.plane = this.plane && this.plane.clone();
  19674. node.front = this.front && this.front.clone();
  19675. node.back = this.back && this.back.clone();
  19676. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19677. return node;
  19678. };
  19679. // Convert solid space to empty space and empty space to solid space.
  19680. Node.prototype.invert = function () {
  19681. for (var i = 0; i < this.polygons.length; i++) {
  19682. this.polygons[i].flip();
  19683. }
  19684. if (this.plane) {
  19685. this.plane.flip();
  19686. }
  19687. if (this.front) {
  19688. this.front.invert();
  19689. }
  19690. if (this.back) {
  19691. this.back.invert();
  19692. }
  19693. var temp = this.front;
  19694. this.front = this.back;
  19695. this.back = temp;
  19696. };
  19697. // Recursively remove all polygons in `polygons` that are inside this BSP
  19698. // tree.
  19699. Node.prototype.clipPolygons = function (polygons) {
  19700. if (!this.plane)
  19701. return polygons.slice();
  19702. var front = [], back = [];
  19703. for (var i = 0; i < polygons.length; i++) {
  19704. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19705. }
  19706. if (this.front) {
  19707. front = this.front.clipPolygons(front);
  19708. }
  19709. if (this.back) {
  19710. back = this.back.clipPolygons(back);
  19711. }
  19712. else {
  19713. back = [];
  19714. }
  19715. return front.concat(back);
  19716. };
  19717. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19718. // `bsp`.
  19719. Node.prototype.clipTo = function (bsp) {
  19720. this.polygons = bsp.clipPolygons(this.polygons);
  19721. if (this.front)
  19722. this.front.clipTo(bsp);
  19723. if (this.back)
  19724. this.back.clipTo(bsp);
  19725. };
  19726. // Return a list of all polygons in this BSP tree.
  19727. Node.prototype.allPolygons = function () {
  19728. var polygons = this.polygons.slice();
  19729. if (this.front)
  19730. polygons = polygons.concat(this.front.allPolygons());
  19731. if (this.back)
  19732. polygons = polygons.concat(this.back.allPolygons());
  19733. return polygons;
  19734. };
  19735. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19736. // new polygons are filtered down to the bottom of the tree and become new
  19737. // nodes there. Each set of polygons is partitioned using the first polygon
  19738. // (no heuristic is used to pick a good split).
  19739. Node.prototype.build = function (polygons) {
  19740. if (!polygons.length)
  19741. return;
  19742. if (!this.plane)
  19743. this.plane = polygons[0].plane.clone();
  19744. var front = [], back = [];
  19745. for (var i = 0; i < polygons.length; i++) {
  19746. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19747. }
  19748. if (front.length) {
  19749. if (!this.front)
  19750. this.front = new Node();
  19751. this.front.build(front);
  19752. }
  19753. if (back.length) {
  19754. if (!this.back)
  19755. this.back = new Node();
  19756. this.back.build(back);
  19757. }
  19758. };
  19759. return Node;
  19760. })();
  19761. var CSG = (function () {
  19762. function CSG() {
  19763. this.polygons = new Array();
  19764. }
  19765. // Convert BABYLON.Mesh to BABYLON.CSG
  19766. CSG.FromMesh = function (mesh) {
  19767. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19768. if (mesh instanceof BABYLON.Mesh) {
  19769. mesh.computeWorldMatrix(true);
  19770. var matrix = mesh.getWorldMatrix();
  19771. var meshPosition = mesh.position.clone();
  19772. var meshRotation = mesh.rotation.clone();
  19773. var meshScaling = mesh.scaling.clone();
  19774. }
  19775. else {
  19776. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19777. }
  19778. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19779. var subMeshes = mesh.subMeshes;
  19780. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19781. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19782. vertices = [];
  19783. for (var j = 0; j < 3; j++) {
  19784. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19785. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19786. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19787. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19788. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19789. vertex = new Vertex(position, normal, uv);
  19790. vertices.push(vertex);
  19791. }
  19792. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19793. // To handle the case of degenerated triangle
  19794. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19795. if (polygon.plane)
  19796. polygons.push(polygon);
  19797. }
  19798. }
  19799. var csg = CSG.FromPolygons(polygons);
  19800. csg.matrix = matrix;
  19801. csg.position = meshPosition;
  19802. csg.rotation = meshRotation;
  19803. csg.scaling = meshScaling;
  19804. currentCSGMeshId++;
  19805. return csg;
  19806. };
  19807. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19808. CSG.FromPolygons = function (polygons) {
  19809. var csg = new BABYLON.CSG();
  19810. csg.polygons = polygons;
  19811. return csg;
  19812. };
  19813. CSG.prototype.clone = function () {
  19814. var csg = new BABYLON.CSG();
  19815. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19816. csg.copyTransformAttributes(this);
  19817. return csg;
  19818. };
  19819. CSG.prototype.toPolygons = function () {
  19820. return this.polygons;
  19821. };
  19822. CSG.prototype.union = function (csg) {
  19823. var a = new Node(this.clone().polygons);
  19824. var b = new Node(csg.clone().polygons);
  19825. a.clipTo(b);
  19826. b.clipTo(a);
  19827. b.invert();
  19828. b.clipTo(a);
  19829. b.invert();
  19830. a.build(b.allPolygons());
  19831. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19832. };
  19833. CSG.prototype.unionInPlace = function (csg) {
  19834. var a = new Node(this.polygons);
  19835. var b = new Node(csg.polygons);
  19836. a.clipTo(b);
  19837. b.clipTo(a);
  19838. b.invert();
  19839. b.clipTo(a);
  19840. b.invert();
  19841. a.build(b.allPolygons());
  19842. this.polygons = a.allPolygons();
  19843. };
  19844. CSG.prototype.subtract = function (csg) {
  19845. var a = new Node(this.clone().polygons);
  19846. var b = new Node(csg.clone().polygons);
  19847. a.invert();
  19848. a.clipTo(b);
  19849. b.clipTo(a);
  19850. b.invert();
  19851. b.clipTo(a);
  19852. b.invert();
  19853. a.build(b.allPolygons());
  19854. a.invert();
  19855. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19856. };
  19857. CSG.prototype.subtractInPlace = function (csg) {
  19858. var a = new Node(this.polygons);
  19859. var b = new Node(csg.polygons);
  19860. a.invert();
  19861. a.clipTo(b);
  19862. b.clipTo(a);
  19863. b.invert();
  19864. b.clipTo(a);
  19865. b.invert();
  19866. a.build(b.allPolygons());
  19867. a.invert();
  19868. this.polygons = a.allPolygons();
  19869. };
  19870. CSG.prototype.intersect = function (csg) {
  19871. var a = new Node(this.clone().polygons);
  19872. var b = new Node(csg.clone().polygons);
  19873. a.invert();
  19874. b.clipTo(a);
  19875. b.invert();
  19876. a.clipTo(b);
  19877. b.clipTo(a);
  19878. a.build(b.allPolygons());
  19879. a.invert();
  19880. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19881. };
  19882. CSG.prototype.intersectInPlace = function (csg) {
  19883. var a = new Node(this.polygons);
  19884. var b = new Node(csg.polygons);
  19885. a.invert();
  19886. b.clipTo(a);
  19887. b.invert();
  19888. a.clipTo(b);
  19889. b.clipTo(a);
  19890. a.build(b.allPolygons());
  19891. a.invert();
  19892. this.polygons = a.allPolygons();
  19893. };
  19894. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19895. // not modified.
  19896. CSG.prototype.inverse = function () {
  19897. var csg = this.clone();
  19898. csg.inverseInPlace();
  19899. return csg;
  19900. };
  19901. CSG.prototype.inverseInPlace = function () {
  19902. this.polygons.map(function (p) {
  19903. p.flip();
  19904. });
  19905. };
  19906. // This is used to keep meshes transformations so they can be restored
  19907. // when we build back a Babylon Mesh
  19908. // NB : All CSG operations are performed in world coordinates
  19909. CSG.prototype.copyTransformAttributes = function (csg) {
  19910. this.matrix = csg.matrix;
  19911. this.position = csg.position;
  19912. this.rotation = csg.rotation;
  19913. this.scaling = csg.scaling;
  19914. return this;
  19915. };
  19916. // Build Raw mesh from CSG
  19917. // Coordinates here are in world space
  19918. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19919. var matrix = this.matrix.clone();
  19920. matrix.invert();
  19921. 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;
  19922. if (keepSubMeshes) {
  19923. // Sort Polygons, since subMeshes are indices range
  19924. polygons.sort(function (a, b) {
  19925. if (a.shared.meshId === b.shared.meshId) {
  19926. return a.shared.subMeshId - b.shared.subMeshId;
  19927. }
  19928. else {
  19929. return a.shared.meshId - b.shared.meshId;
  19930. }
  19931. });
  19932. }
  19933. for (var i = 0, il = polygons.length; i < il; i++) {
  19934. polygon = polygons[i];
  19935. // Building SubMeshes
  19936. if (!subMesh_dict[polygon.shared.meshId]) {
  19937. subMesh_dict[polygon.shared.meshId] = {};
  19938. }
  19939. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19940. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19941. indexStart: +Infinity,
  19942. indexEnd: -Infinity,
  19943. materialIndex: polygon.shared.materialIndex
  19944. };
  19945. }
  19946. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19947. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19948. polygonIndices[0] = 0;
  19949. polygonIndices[1] = j - 1;
  19950. polygonIndices[2] = j;
  19951. for (var k = 0; k < 3; k++) {
  19952. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19953. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19954. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19955. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19956. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19957. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19958. // Check if 2 points can be merged
  19959. 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)) {
  19960. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19961. uvs.push(uv.x, uv.y);
  19962. normals.push(normal.x, normal.y, normal.z);
  19963. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19964. }
  19965. indices.push(vertex_idx);
  19966. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19967. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19968. currentIndex++;
  19969. }
  19970. }
  19971. }
  19972. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19973. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19974. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19975. mesh.setIndices(indices);
  19976. if (keepSubMeshes) {
  19977. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19978. var materialIndexOffset = 0, materialMaxIndex;
  19979. mesh.subMeshes.length = 0;
  19980. for (var m in subMesh_dict) {
  19981. materialMaxIndex = -1;
  19982. for (var sm in subMesh_dict[m]) {
  19983. subMesh_obj = subMesh_dict[m][sm];
  19984. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19985. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19986. }
  19987. materialIndexOffset += ++materialMaxIndex;
  19988. }
  19989. }
  19990. return mesh;
  19991. };
  19992. // Build Mesh from CSG taking material and transforms into account
  19993. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19994. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19995. mesh.material = material;
  19996. mesh.position.copyFrom(this.position);
  19997. mesh.rotation.copyFrom(this.rotation);
  19998. mesh.scaling.copyFrom(this.scaling);
  19999. mesh.computeWorldMatrix(true);
  20000. return mesh;
  20001. };
  20002. return CSG;
  20003. })();
  20004. BABYLON.CSG = CSG;
  20005. })(BABYLON || (BABYLON = {}));
  20006. //# sourceMappingURL=babylon.csg.js.map
  20007. var BABYLON;
  20008. (function (BABYLON) {
  20009. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20010. __extends(OculusDistortionCorrectionPostProcess, _super);
  20011. //ANY
  20012. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20013. var _this = this;
  20014. _super.call(this, name, "oculusDistortionCorrection", [
  20015. 'LensCenter',
  20016. 'Scale',
  20017. 'ScaleIn',
  20018. 'HmdWarpParam'
  20019. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20020. this._isRightEye = isRightEye;
  20021. this._distortionFactors = cameraSettings.DistortionK;
  20022. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20023. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20024. this.onSizeChanged = function () {
  20025. _this.aspectRatio = _this.width * .5 / _this.height;
  20026. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20027. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20028. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20029. };
  20030. this.onApply = function (effect) {
  20031. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20032. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20033. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20034. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20035. };
  20036. }
  20037. return OculusDistortionCorrectionPostProcess;
  20038. })(BABYLON.PostProcess);
  20039. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20040. })(BABYLON || (BABYLON = {}));
  20041. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20042. // 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
  20043. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20044. var BABYLON;
  20045. (function (BABYLON) {
  20046. (function (JoystickAxis) {
  20047. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20048. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20049. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20050. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20051. var JoystickAxis = BABYLON.JoystickAxis;
  20052. var VirtualJoystick = (function () {
  20053. function VirtualJoystick(leftJoystick) {
  20054. var _this = this;
  20055. if (leftJoystick) {
  20056. this._leftJoystick = true;
  20057. }
  20058. else {
  20059. this._leftJoystick = false;
  20060. }
  20061. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20062. VirtualJoystick._globalJoystickIndex++;
  20063. // By default left & right arrow keys are moving the X
  20064. // and up & down keys are moving the Y
  20065. this._axisTargetedByLeftAndRight = 0 /* X */;
  20066. this._axisTargetedByUpAndDown = 1 /* Y */;
  20067. this.reverseLeftRight = false;
  20068. this.reverseUpDown = false;
  20069. // collections of pointers
  20070. this._touches = new BABYLON.VirtualJoystick.Collection();
  20071. this.deltaPosition = BABYLON.Vector3.Zero();
  20072. this._joystickSensibility = 25;
  20073. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20074. this._rotationSpeed = 25;
  20075. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20076. this._rotateOnAxisRelativeToMesh = false;
  20077. // injecting a canvas element on top of the canvas 3D game
  20078. if (!VirtualJoystick.vjCanvas) {
  20079. window.addEventListener("resize", function () {
  20080. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20081. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20082. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20083. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20084. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20085. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20086. }, false);
  20087. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20088. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20089. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20090. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20091. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20092. VirtualJoystick.vjCanvas.style.width = "100%";
  20093. VirtualJoystick.vjCanvas.style.height = "100%";
  20094. VirtualJoystick.vjCanvas.style.position = "absolute";
  20095. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20096. VirtualJoystick.vjCanvas.style.top = "0px";
  20097. VirtualJoystick.vjCanvas.style.left = "0px";
  20098. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20099. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20100. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20101. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20102. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20103. document.body.appendChild(VirtualJoystick.vjCanvas);
  20104. }
  20105. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20106. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20107. this.pressed = false;
  20108. // default joystick color
  20109. this._joystickColor = "cyan";
  20110. this._joystickPointerID = -1;
  20111. // current joystick position
  20112. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20113. // origin joystick position
  20114. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20115. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20116. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20117. _this._onPointerDown(evt);
  20118. }, false);
  20119. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20120. _this._onPointerMove(evt);
  20121. }, false);
  20122. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20123. _this._onPointerUp(evt);
  20124. }, false);
  20125. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20126. _this._onPointerUp(evt);
  20127. }, false);
  20128. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20129. evt.preventDefault(); // Disables system menu
  20130. }, false);
  20131. requestAnimationFrame(function () {
  20132. _this._drawVirtualJoystick();
  20133. });
  20134. }
  20135. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20136. this._joystickSensibility = newJoystickSensibility;
  20137. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20138. };
  20139. VirtualJoystick.prototype._onPointerDown = function (e) {
  20140. var positionOnScreenCondition;
  20141. e.preventDefault();
  20142. if (this._leftJoystick === true) {
  20143. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20144. }
  20145. else {
  20146. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20147. }
  20148. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20149. // First contact will be dedicated to the virtual joystick
  20150. this._joystickPointerID = e.pointerId;
  20151. this._joystickPointerStartPos.x = e.clientX;
  20152. this._joystickPointerStartPos.y = e.clientY;
  20153. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20154. this._deltaJoystickVector.x = 0;
  20155. this._deltaJoystickVector.y = 0;
  20156. this.pressed = true;
  20157. this._touches.add(e.pointerId.toString(), e);
  20158. }
  20159. else {
  20160. // You can only trigger the action buttons with a joystick declared
  20161. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20162. this._action();
  20163. this._touches.add(e.pointerId.toString(), e);
  20164. }
  20165. }
  20166. };
  20167. VirtualJoystick.prototype._onPointerMove = function (e) {
  20168. // If the current pointer is the one associated to the joystick (first touch contact)
  20169. if (this._joystickPointerID == e.pointerId) {
  20170. this._joystickPointerPos.x = e.clientX;
  20171. this._joystickPointerPos.y = e.clientY;
  20172. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20173. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20174. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20175. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20176. switch (this._axisTargetedByLeftAndRight) {
  20177. case 0 /* X */:
  20178. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20179. break;
  20180. case 1 /* Y */:
  20181. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20182. break;
  20183. case 2 /* Z */:
  20184. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20185. break;
  20186. }
  20187. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20188. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20189. switch (this._axisTargetedByUpAndDown) {
  20190. case 0 /* X */:
  20191. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20192. break;
  20193. case 1 /* Y */:
  20194. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20195. break;
  20196. case 2 /* Z */:
  20197. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20198. break;
  20199. }
  20200. }
  20201. else {
  20202. if (this._touches.item(e.pointerId.toString())) {
  20203. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20204. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20205. }
  20206. }
  20207. };
  20208. VirtualJoystick.prototype._onPointerUp = function (e) {
  20209. this._clearCanvas();
  20210. if (this._joystickPointerID == e.pointerId) {
  20211. this._joystickPointerID = -1;
  20212. this.pressed = false;
  20213. }
  20214. this._deltaJoystickVector.x = 0;
  20215. this._deltaJoystickVector.y = 0;
  20216. this._touches.remove(e.pointerId.toString());
  20217. };
  20218. /**
  20219. * Change the color of the virtual joystick
  20220. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20221. */
  20222. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20223. this._joystickColor = newColor;
  20224. };
  20225. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20226. this._action = action;
  20227. };
  20228. // Define which axis you'd like to control for left & right
  20229. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20230. switch (axis) {
  20231. case 0 /* X */:
  20232. case 1 /* Y */:
  20233. case 2 /* Z */:
  20234. this._axisTargetedByLeftAndRight = axis;
  20235. break;
  20236. default:
  20237. this._axisTargetedByLeftAndRight = 0 /* X */;
  20238. break;
  20239. }
  20240. };
  20241. // Define which axis you'd like to control for up & down
  20242. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20243. switch (axis) {
  20244. case 0 /* X */:
  20245. case 1 /* Y */:
  20246. case 2 /* Z */:
  20247. this._axisTargetedByUpAndDown = axis;
  20248. break;
  20249. default:
  20250. this._axisTargetedByUpAndDown = 1 /* Y */;
  20251. break;
  20252. }
  20253. };
  20254. VirtualJoystick.prototype._clearCanvas = function () {
  20255. if (this._leftJoystick) {
  20256. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20257. }
  20258. else {
  20259. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20260. }
  20261. };
  20262. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20263. var _this = this;
  20264. if (this.pressed) {
  20265. this._clearCanvas();
  20266. this._touches.forEach(function (touch) {
  20267. if (touch.pointerId === _this._joystickPointerID) {
  20268. VirtualJoystick.vjCanvasContext.beginPath();
  20269. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20270. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20271. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20272. VirtualJoystick.vjCanvasContext.stroke();
  20273. VirtualJoystick.vjCanvasContext.beginPath();
  20274. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20275. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20276. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20277. VirtualJoystick.vjCanvasContext.stroke();
  20278. VirtualJoystick.vjCanvasContext.beginPath();
  20279. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20280. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20281. VirtualJoystick.vjCanvasContext.stroke();
  20282. }
  20283. else {
  20284. VirtualJoystick.vjCanvasContext.beginPath();
  20285. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20286. VirtualJoystick.vjCanvasContext.beginPath();
  20287. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20288. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20289. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20290. VirtualJoystick.vjCanvasContext.stroke();
  20291. }
  20292. ;
  20293. });
  20294. }
  20295. requestAnimationFrame(function () {
  20296. _this._drawVirtualJoystick();
  20297. });
  20298. };
  20299. VirtualJoystick.prototype.releaseCanvas = function () {
  20300. if (VirtualJoystick.vjCanvas) {
  20301. document.body.removeChild(VirtualJoystick.vjCanvas);
  20302. VirtualJoystick.vjCanvas = null;
  20303. }
  20304. };
  20305. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20306. VirtualJoystick._globalJoystickIndex = 0;
  20307. return VirtualJoystick;
  20308. })();
  20309. BABYLON.VirtualJoystick = VirtualJoystick;
  20310. })(BABYLON || (BABYLON = {}));
  20311. var BABYLON;
  20312. (function (BABYLON) {
  20313. var VirtualJoystick;
  20314. (function (VirtualJoystick) {
  20315. var Collection = (function () {
  20316. function Collection() {
  20317. this._count = 0;
  20318. this._collection = new Array();
  20319. }
  20320. Collection.prototype.Count = function () {
  20321. return this._count;
  20322. };
  20323. Collection.prototype.add = function (key, item) {
  20324. if (this._collection[key] != undefined) {
  20325. return undefined;
  20326. }
  20327. this._collection[key] = item;
  20328. return ++this._count;
  20329. };
  20330. Collection.prototype.remove = function (key) {
  20331. if (this._collection[key] == undefined) {
  20332. return undefined;
  20333. }
  20334. delete this._collection[key];
  20335. return --this._count;
  20336. };
  20337. Collection.prototype.item = function (key) {
  20338. return this._collection[key];
  20339. };
  20340. Collection.prototype.forEach = function (block) {
  20341. var key;
  20342. for (key in this._collection) {
  20343. if (this._collection.hasOwnProperty(key)) {
  20344. block(this._collection[key]);
  20345. }
  20346. }
  20347. };
  20348. return Collection;
  20349. })();
  20350. VirtualJoystick.Collection = Collection;
  20351. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20352. })(BABYLON || (BABYLON = {}));
  20353. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20354. var BABYLON;
  20355. (function (BABYLON) {
  20356. var OculusRiftDevKit2013_Metric = {
  20357. HResolution: 1280,
  20358. VResolution: 800,
  20359. HScreenSize: 0.149759993,
  20360. VScreenSize: 0.0935999975,
  20361. VScreenCenter: 0.0467999987,
  20362. EyeToScreenDistance: 0.0410000011,
  20363. LensSeparationDistance: 0.0635000020,
  20364. InterpupillaryDistance: 0.0640000030,
  20365. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20366. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20367. PostProcessScaleFactor: 1.714605507808412,
  20368. LensCenterOffset: 0.151976421
  20369. };
  20370. var _OculusInnerCamera = (function (_super) {
  20371. __extends(_OculusInnerCamera, _super);
  20372. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20373. _super.call(this, name, position, scene);
  20374. this._workMatrix = new BABYLON.Matrix();
  20375. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20376. // Constants
  20377. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20378. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20379. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20380. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20381. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20382. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20383. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20384. // Postprocess
  20385. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20386. }
  20387. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20388. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20389. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20390. return this._projectionMatrix;
  20391. };
  20392. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20393. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20394. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20395. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20396. // Computing target and final matrix
  20397. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20398. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20399. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20400. return this._viewMatrix;
  20401. };
  20402. return _OculusInnerCamera;
  20403. })(BABYLON.FreeCamera);
  20404. var OculusCamera = (function (_super) {
  20405. __extends(OculusCamera, _super);
  20406. function OculusCamera(name, position, scene) {
  20407. _super.call(this, name, position, scene);
  20408. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20409. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20410. this.subCameras.push(this._leftCamera);
  20411. this.subCameras.push(this._rightCamera);
  20412. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20413. }
  20414. OculusCamera.prototype._update = function () {
  20415. this._leftCamera.position.copyFrom(this.position);
  20416. this._rightCamera.position.copyFrom(this.position);
  20417. this._updateCamera(this._leftCamera);
  20418. this._updateCamera(this._rightCamera);
  20419. _super.prototype._update.call(this);
  20420. };
  20421. OculusCamera.prototype._updateCamera = function (camera) {
  20422. camera.minZ = this.minZ;
  20423. camera.maxZ = this.maxZ;
  20424. camera.rotation.x = this.rotation.x;
  20425. camera.rotation.y = this.rotation.y;
  20426. camera.rotation.z = this.rotation.z;
  20427. };
  20428. // Oculus events
  20429. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20430. var yaw = evt.alpha / 180 * Math.PI;
  20431. var pitch = evt.beta / 180 * Math.PI;
  20432. var roll = evt.gamma / 180 * Math.PI;
  20433. if (!this._offsetOrientation) {
  20434. this._offsetOrientation = {
  20435. yaw: yaw,
  20436. pitch: pitch,
  20437. roll: roll
  20438. };
  20439. return;
  20440. }
  20441. else {
  20442. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20443. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20444. this.rotation.z += this._offsetOrientation.roll - roll;
  20445. this._offsetOrientation.yaw = yaw;
  20446. this._offsetOrientation.pitch = pitch;
  20447. this._offsetOrientation.roll = roll;
  20448. }
  20449. };
  20450. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20451. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20452. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20453. };
  20454. OculusCamera.prototype.detachControl = function (element) {
  20455. _super.prototype.detachControl.call(this, element);
  20456. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20457. };
  20458. return OculusCamera;
  20459. })(BABYLON.FreeCamera);
  20460. BABYLON.OculusCamera = OculusCamera;
  20461. })(BABYLON || (BABYLON = {}));
  20462. //# sourceMappingURL=babylon.oculusCamera.js.map
  20463. var BABYLON;
  20464. (function (BABYLON) {
  20465. var OculusRiftDevKit2013_Metric = {
  20466. HResolution: 1280,
  20467. VResolution: 800,
  20468. HScreenSize: 0.149759993,
  20469. VScreenSize: 0.0935999975,
  20470. VScreenCenter: 0.0467999987,
  20471. EyeToScreenDistance: 0.0410000011,
  20472. LensSeparationDistance: 0.0635000020,
  20473. InterpupillaryDistance: 0.0640000030,
  20474. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20475. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20476. PostProcessScaleFactor: 1.714605507808412,
  20477. LensCenterOffset: 0.151976421
  20478. };
  20479. var _OculusInnerGamepadCamera = (function (_super) {
  20480. __extends(_OculusInnerGamepadCamera, _super);
  20481. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20482. _super.call(this, name, position, scene);
  20483. this._workMatrix = new BABYLON.Matrix();
  20484. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20485. // Constants
  20486. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20487. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20488. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20489. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20490. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20491. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20492. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20493. // Postprocess
  20494. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20495. }
  20496. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20497. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20498. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20499. return this._projectionMatrix;
  20500. };
  20501. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20502. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20503. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20504. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20505. // Computing target and final matrix
  20506. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20507. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20508. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20509. return this._viewMatrix;
  20510. };
  20511. return _OculusInnerGamepadCamera;
  20512. })(BABYLON.FreeCamera);
  20513. var OculusGamepadCamera = (function (_super) {
  20514. __extends(OculusGamepadCamera, _super);
  20515. function OculusGamepadCamera(name, position, scene) {
  20516. var _this = this;
  20517. _super.call(this, name, position, scene);
  20518. this.angularSensibility = 200;
  20519. this.moveSensibility = 75;
  20520. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20521. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20522. this.subCameras.push(this._leftCamera);
  20523. this.subCameras.push(this._rightCamera);
  20524. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20525. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20526. _this._onNewGameConnected(gamepad);
  20527. });
  20528. }
  20529. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20530. // Only the first gamepad can control the camera
  20531. if (gamepad.index === 0) {
  20532. this._gamepad = gamepad;
  20533. }
  20534. };
  20535. OculusGamepadCamera.prototype._update = function () {
  20536. this._leftCamera.position.copyFrom(this.position);
  20537. this._rightCamera.position.copyFrom(this.position);
  20538. this._updateCamera(this._leftCamera);
  20539. this._updateCamera(this._rightCamera);
  20540. _super.prototype._update.call(this);
  20541. };
  20542. OculusGamepadCamera.prototype._checkInputs = function () {
  20543. if (!this._gamepad) {
  20544. return;
  20545. }
  20546. var LSValues = this._gamepad.leftStick;
  20547. var normalizedLX = LSValues.x / this.moveSensibility;
  20548. var normalizedLY = LSValues.y / this.moveSensibility;
  20549. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20550. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20551. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20552. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20553. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20554. };
  20555. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20556. camera.minZ = this.minZ;
  20557. camera.maxZ = this.maxZ;
  20558. camera.rotation.x = this.rotation.x;
  20559. camera.rotation.y = this.rotation.y;
  20560. camera.rotation.z = this.rotation.z;
  20561. };
  20562. // Oculus events
  20563. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20564. var yaw = evt.alpha / 180 * Math.PI;
  20565. var pitch = evt.beta / 180 * Math.PI;
  20566. var roll = evt.gamma / 180 * Math.PI;
  20567. if (!this._offsetOrientation) {
  20568. this._offsetOrientation = {
  20569. yaw: yaw,
  20570. pitch: pitch,
  20571. roll: roll
  20572. };
  20573. return;
  20574. }
  20575. else {
  20576. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20577. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20578. this.rotation.z += this._offsetOrientation.roll - roll;
  20579. this._offsetOrientation.yaw = yaw;
  20580. this._offsetOrientation.pitch = pitch;
  20581. this._offsetOrientation.roll = roll;
  20582. }
  20583. };
  20584. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20585. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20586. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20587. };
  20588. OculusGamepadCamera.prototype.detachControl = function (element) {
  20589. _super.prototype.detachControl.call(this, element);
  20590. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20591. };
  20592. OculusGamepadCamera.prototype.dispose = function () {
  20593. this._gamepads.dispose();
  20594. _super.prototype.dispose.call(this);
  20595. };
  20596. return OculusGamepadCamera;
  20597. })(BABYLON.FreeCamera);
  20598. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20599. })(BABYLON || (BABYLON = {}));
  20600. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20601. var BABYLON;
  20602. (function (BABYLON) {
  20603. // We're mainly based on the logic defined into the FreeCamera code
  20604. var VirtualJoysticksCamera = (function (_super) {
  20605. __extends(VirtualJoysticksCamera, _super);
  20606. function VirtualJoysticksCamera(name, position, scene) {
  20607. _super.call(this, name, position, scene);
  20608. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20609. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20610. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20611. this._leftjoystick.setJoystickSensibility(0.15);
  20612. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20613. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20614. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20615. this._rightjoystick.reverseUpDown = true;
  20616. this._rightjoystick.setJoystickSensibility(0.05);
  20617. this._rightjoystick.setJoystickColor("yellow");
  20618. }
  20619. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20620. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20621. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20622. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20623. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20624. if (!this._leftjoystick.pressed) {
  20625. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20626. }
  20627. if (!this._rightjoystick.pressed) {
  20628. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20629. }
  20630. };
  20631. VirtualJoysticksCamera.prototype.dispose = function () {
  20632. this._leftjoystick.releaseCanvas();
  20633. _super.prototype.dispose.call(this);
  20634. };
  20635. return VirtualJoysticksCamera;
  20636. })(BABYLON.FreeCamera);
  20637. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20638. })(BABYLON || (BABYLON = {}));
  20639. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20640. var BABYLON;
  20641. (function (BABYLON) {
  20642. var ShaderMaterial = (function (_super) {
  20643. __extends(ShaderMaterial, _super);
  20644. function ShaderMaterial(name, scene, shaderPath, options) {
  20645. _super.call(this, name, scene);
  20646. this._textures = new Array();
  20647. this._floats = new Array();
  20648. this._floatsArrays = {};
  20649. this._colors3 = new Array();
  20650. this._colors4 = new Array();
  20651. this._vectors2 = new Array();
  20652. this._vectors3 = new Array();
  20653. this._matrices = new Array();
  20654. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20655. this._shaderPath = shaderPath;
  20656. options.needAlphaBlending = options.needAlphaBlending || false;
  20657. options.needAlphaTesting = options.needAlphaTesting || false;
  20658. options.attributes = options.attributes || ["position", "normal", "uv"];
  20659. options.uniforms = options.uniforms || ["worldViewProjection"];
  20660. options.samplers = options.samplers || [];
  20661. this._options = options;
  20662. }
  20663. ShaderMaterial.prototype.needAlphaBlending = function () {
  20664. return this._options.needAlphaBlending;
  20665. };
  20666. ShaderMaterial.prototype.needAlphaTesting = function () {
  20667. return this._options.needAlphaTesting;
  20668. };
  20669. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20670. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20671. this._options.uniforms.push(uniformName);
  20672. }
  20673. };
  20674. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20675. if (this._options.samplers.indexOf(name) === -1) {
  20676. this._options.samplers.push(name);
  20677. }
  20678. this._textures[name] = texture;
  20679. return this;
  20680. };
  20681. ShaderMaterial.prototype.setFloat = function (name, value) {
  20682. this._checkUniform(name);
  20683. this._floats[name] = value;
  20684. return this;
  20685. };
  20686. ShaderMaterial.prototype.setFloats = function (name, value) {
  20687. this._checkUniform(name);
  20688. this._floatsArrays[name] = value;
  20689. return this;
  20690. };
  20691. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20692. this._checkUniform(name);
  20693. this._colors3[name] = value;
  20694. return this;
  20695. };
  20696. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20697. this._checkUniform(name);
  20698. this._colors4[name] = value;
  20699. return this;
  20700. };
  20701. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20702. this._checkUniform(name);
  20703. this._vectors2[name] = value;
  20704. return this;
  20705. };
  20706. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20707. this._checkUniform(name);
  20708. this._vectors3[name] = value;
  20709. return this;
  20710. };
  20711. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20712. this._checkUniform(name);
  20713. this._matrices[name] = value;
  20714. return this;
  20715. };
  20716. ShaderMaterial.prototype.isReady = function () {
  20717. var scene = this.getScene();
  20718. var engine = scene.getEngine();
  20719. if (!this.checkReadyOnEveryCall) {
  20720. if (this._renderId === scene.getRenderId()) {
  20721. return true;
  20722. }
  20723. }
  20724. var previousEffect = this._effect;
  20725. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20726. if (!this._effect.isReady()) {
  20727. return false;
  20728. }
  20729. if (previousEffect !== this._effect) {
  20730. scene.resetCachedMaterial();
  20731. }
  20732. this._renderId = scene.getRenderId();
  20733. return true;
  20734. };
  20735. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20736. var scene = this.getScene();
  20737. if (this._options.uniforms.indexOf("world") !== -1) {
  20738. this._effect.setMatrix("world", world);
  20739. }
  20740. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20741. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20742. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20743. }
  20744. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20745. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20746. }
  20747. };
  20748. ShaderMaterial.prototype.bind = function (world) {
  20749. // Std values
  20750. this.bindOnlyWorldMatrix(world);
  20751. if (this.getScene().getCachedMaterial() !== this) {
  20752. if (this._options.uniforms.indexOf("view") !== -1) {
  20753. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20754. }
  20755. if (this._options.uniforms.indexOf("projection") !== -1) {
  20756. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20757. }
  20758. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20759. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20760. }
  20761. for (var name in this._textures) {
  20762. this._effect.setTexture(name, this._textures[name]);
  20763. }
  20764. for (name in this._floats) {
  20765. this._effect.setFloat(name, this._floats[name]);
  20766. }
  20767. for (name in this._floatsArrays) {
  20768. this._effect.setArray(name, this._floatsArrays[name]);
  20769. }
  20770. for (name in this._colors3) {
  20771. this._effect.setColor3(name, this._colors3[name]);
  20772. }
  20773. for (name in this._colors4) {
  20774. var color = this._colors4[name];
  20775. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20776. }
  20777. for (name in this._vectors2) {
  20778. this._effect.setVector2(name, this._vectors2[name]);
  20779. }
  20780. for (name in this._vectors3) {
  20781. this._effect.setVector3(name, this._vectors3[name]);
  20782. }
  20783. for (name in this._matrices) {
  20784. this._effect.setMatrix(name, this._matrices[name]);
  20785. }
  20786. }
  20787. _super.prototype.bind.call(this, world, null);
  20788. };
  20789. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20790. for (var name in this._textures) {
  20791. this._textures[name].dispose();
  20792. }
  20793. this._textures = [];
  20794. _super.prototype.dispose.call(this, forceDisposeEffect);
  20795. };
  20796. return ShaderMaterial;
  20797. })(BABYLON.Material);
  20798. BABYLON.ShaderMaterial = ShaderMaterial;
  20799. })(BABYLON || (BABYLON = {}));
  20800. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20801. (function (BABYLON) {
  20802. var VertexData = (function () {
  20803. function VertexData() {
  20804. }
  20805. VertexData.prototype.set = function (data, kind) {
  20806. switch (kind) {
  20807. case BABYLON.VertexBuffer.PositionKind:
  20808. this.positions = data;
  20809. break;
  20810. case BABYLON.VertexBuffer.NormalKind:
  20811. this.normals = data;
  20812. break;
  20813. case BABYLON.VertexBuffer.UVKind:
  20814. this.uvs = data;
  20815. break;
  20816. case BABYLON.VertexBuffer.UV2Kind:
  20817. this.uv2s = data;
  20818. break;
  20819. case BABYLON.VertexBuffer.ColorKind:
  20820. this.colors = data;
  20821. break;
  20822. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20823. this.matricesIndices = data;
  20824. break;
  20825. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20826. this.matricesWeights = data;
  20827. break;
  20828. }
  20829. };
  20830. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20831. this._applyTo(mesh, updatable);
  20832. };
  20833. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20834. this._applyTo(geometry, updatable);
  20835. };
  20836. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20837. this._update(mesh);
  20838. };
  20839. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20840. this._update(geometry);
  20841. };
  20842. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20843. if (this.positions) {
  20844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20845. }
  20846. if (this.normals) {
  20847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20848. }
  20849. if (this.uvs) {
  20850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20851. }
  20852. if (this.uv2s) {
  20853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20854. }
  20855. if (this.colors) {
  20856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20857. }
  20858. if (this.matricesIndices) {
  20859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20860. }
  20861. if (this.matricesWeights) {
  20862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20863. }
  20864. if (this.indices) {
  20865. meshOrGeometry.setIndices(this.indices);
  20866. }
  20867. };
  20868. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20869. if (this.positions) {
  20870. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20871. }
  20872. if (this.normals) {
  20873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20874. }
  20875. if (this.uvs) {
  20876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20877. }
  20878. if (this.uv2s) {
  20879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20880. }
  20881. if (this.colors) {
  20882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20883. }
  20884. if (this.matricesIndices) {
  20885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20886. }
  20887. if (this.matricesWeights) {
  20888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20889. }
  20890. if (this.indices) {
  20891. meshOrGeometry.setIndices(this.indices);
  20892. }
  20893. };
  20894. VertexData.prototype.transform = function (matrix) {
  20895. var transformed = BABYLON.Vector3.Zero();
  20896. if (this.positions) {
  20897. var position = BABYLON.Vector3.Zero();
  20898. for (var index = 0; index < this.positions.length; index += 3) {
  20899. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20900. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20901. this.positions[index] = transformed.x;
  20902. this.positions[index + 1] = transformed.y;
  20903. this.positions[index + 2] = transformed.z;
  20904. }
  20905. }
  20906. if (this.normals) {
  20907. var normal = BABYLON.Vector3.Zero();
  20908. for (index = 0; index < this.normals.length; index += 3) {
  20909. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20910. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20911. this.normals[index] = transformed.x;
  20912. this.normals[index + 1] = transformed.y;
  20913. this.normals[index + 2] = transformed.z;
  20914. }
  20915. }
  20916. };
  20917. VertexData.prototype.merge = function (other) {
  20918. if (other.indices) {
  20919. if (!this.indices) {
  20920. this.indices = [];
  20921. }
  20922. var offset = this.positions ? this.positions.length / 3 : 0;
  20923. for (var index = 0; index < other.indices.length; index++) {
  20924. this.indices.push(other.indices[index] + offset);
  20925. }
  20926. }
  20927. if (other.positions) {
  20928. if (!this.positions) {
  20929. this.positions = [];
  20930. }
  20931. for (index = 0; index < other.positions.length; index++) {
  20932. this.positions.push(other.positions[index]);
  20933. }
  20934. }
  20935. if (other.normals) {
  20936. if (!this.normals) {
  20937. this.normals = [];
  20938. }
  20939. for (index = 0; index < other.normals.length; index++) {
  20940. this.normals.push(other.normals[index]);
  20941. }
  20942. }
  20943. if (other.uvs) {
  20944. if (!this.uvs) {
  20945. this.uvs = [];
  20946. }
  20947. for (index = 0; index < other.uvs.length; index++) {
  20948. this.uvs.push(other.uvs[index]);
  20949. }
  20950. }
  20951. if (other.uv2s) {
  20952. if (!this.uv2s) {
  20953. this.uv2s = [];
  20954. }
  20955. for (index = 0; index < other.uv2s.length; index++) {
  20956. this.uv2s.push(other.uv2s[index]);
  20957. }
  20958. }
  20959. if (other.matricesIndices) {
  20960. if (!this.matricesIndices) {
  20961. this.matricesIndices = [];
  20962. }
  20963. for (index = 0; index < other.matricesIndices.length; index++) {
  20964. this.matricesIndices.push(other.matricesIndices[index]);
  20965. }
  20966. }
  20967. if (other.matricesWeights) {
  20968. if (!this.matricesWeights) {
  20969. this.matricesWeights = [];
  20970. }
  20971. for (index = 0; index < other.matricesWeights.length; index++) {
  20972. this.matricesWeights.push(other.matricesWeights[index]);
  20973. }
  20974. }
  20975. if (other.colors) {
  20976. if (!this.colors) {
  20977. this.colors = [];
  20978. }
  20979. for (index = 0; index < other.colors.length; index++) {
  20980. this.colors.push(other.colors[index]);
  20981. }
  20982. }
  20983. };
  20984. // Statics
  20985. VertexData.ExtractFromMesh = function (mesh) {
  20986. return VertexData._ExtractFrom(mesh);
  20987. };
  20988. VertexData.ExtractFromGeometry = function (geometry) {
  20989. return VertexData._ExtractFrom(geometry);
  20990. };
  20991. VertexData._ExtractFrom = function (meshOrGeometry) {
  20992. var result = new VertexData();
  20993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20994. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20995. }
  20996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20997. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20998. }
  20999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21000. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21001. }
  21002. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21003. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21004. }
  21005. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21006. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21007. }
  21008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21009. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21010. }
  21011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21012. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21013. }
  21014. result.indices = meshOrGeometry.getIndices();
  21015. return result;
  21016. };
  21017. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21018. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21019. closeArray = closeArray || false;
  21020. closePath = closePath || false;
  21021. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21022. offset = offset || defaultOffset;
  21023. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21024. var positions = [];
  21025. var indices = [];
  21026. var normals = [];
  21027. var uvs = [];
  21028. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21029. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21030. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21031. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21032. var minlg; // minimal length among all paths from pathArray
  21033. var lg = []; // array of path lengths : nb of vertex per path
  21034. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21035. var p; // path iterator
  21036. var i; // point iterator
  21037. var j; // point iterator
  21038. // if single path in pathArray
  21039. if (pathArray.length < 2) {
  21040. var ar1 = [];
  21041. var ar2 = [];
  21042. for (i = 0; i < pathArray[0].length - offset; i++) {
  21043. ar1.push(pathArray[0][i]);
  21044. ar2.push(pathArray[0][i + offset]);
  21045. }
  21046. pathArray = [ar1, ar2];
  21047. }
  21048. // positions and horizontal distances (u)
  21049. var idc = 0;
  21050. minlg = pathArray[0].length;
  21051. for (p = 0; p < pathArray.length; p++) {
  21052. uTotalDistance[p] = 0;
  21053. us[p] = [0];
  21054. var path = pathArray[p];
  21055. var l = path.length;
  21056. minlg = (minlg < l) ? minlg : l;
  21057. lg[p] = l;
  21058. idx[p] = idc;
  21059. j = 0;
  21060. while (j < l) {
  21061. positions.push(path[j].x, path[j].y, path[j].z);
  21062. if (j > 0) {
  21063. var vectlg = path[j].subtract(path[j - 1]).length();
  21064. var dist = vectlg + uTotalDistance[p];
  21065. us[p].push(dist);
  21066. uTotalDistance[p] = dist;
  21067. }
  21068. j++;
  21069. }
  21070. if (closePath) {
  21071. vectlg = path[0].subtract(path[j - 1]).length();
  21072. dist = vectlg + uTotalDistance[p];
  21073. uTotalDistance[p] = dist;
  21074. }
  21075. idc += l;
  21076. }
  21077. for (i = 0; i < minlg; i++) {
  21078. vTotalDistance[i] = 0;
  21079. vs[i] = [0];
  21080. var path1;
  21081. var path2;
  21082. for (p = 0; p < pathArray.length - 1; p++) {
  21083. path1 = pathArray[p];
  21084. path2 = pathArray[p + 1];
  21085. vectlg = path2[i].subtract(path1[i]).length();
  21086. dist = vectlg + vTotalDistance[i];
  21087. vs[i].push(dist);
  21088. vTotalDistance[i] = dist;
  21089. }
  21090. if (closeArray) {
  21091. path1 = pathArray[p];
  21092. path2 = pathArray[0];
  21093. vectlg = path2[i].subtract(path1[i]).length();
  21094. dist = vectlg + vTotalDistance[i];
  21095. vTotalDistance[i] = dist;
  21096. }
  21097. }
  21098. // uvs
  21099. var u;
  21100. var v;
  21101. for (p = 0; p < pathArray.length; p++) {
  21102. for (i = 0; i < minlg; i++) {
  21103. u = us[p][i] / uTotalDistance[p];
  21104. v = vs[i][p] / vTotalDistance[i];
  21105. uvs.push(u, v);
  21106. }
  21107. }
  21108. // indices
  21109. p = 0; // path index
  21110. var pi = 0; // positions array index
  21111. var l1 = lg[p] - 1; // path1 length
  21112. var l2 = lg[p + 1] - 1; // path2 length
  21113. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21114. var shft = idx[1] - idx[0]; // shift
  21115. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21116. var t1; // two consecutive triangles, so 4 points : point1
  21117. var t2; // point2
  21118. var t3; // point3
  21119. var t4; // point4
  21120. while (pi <= min && p < path1nb) {
  21121. // 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
  21122. t1 = pi;
  21123. t2 = pi + shft;
  21124. t3 = pi + 1;
  21125. t4 = pi + shft + 1;
  21126. indices.push(pi, pi + shft, pi + 1);
  21127. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21128. pi += 1;
  21129. if (pi === min) {
  21130. if (closePath) {
  21131. indices.push(pi, pi + shft, idx[p]);
  21132. indices.push(idx[p] + shft, idx[p], pi + shft);
  21133. t3 = idx[p];
  21134. t4 = idx[p] + shft;
  21135. }
  21136. p++;
  21137. if (p === lg.length - 1) {
  21138. shft = idx[0] - idx[p];
  21139. l1 = lg[p] - 1;
  21140. l2 = lg[0] - 1;
  21141. }
  21142. else {
  21143. shft = idx[p + 1] - idx[p];
  21144. l1 = lg[p] - 1;
  21145. l2 = lg[p + 1] - 1;
  21146. }
  21147. pi = idx[p];
  21148. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21149. }
  21150. }
  21151. // normals
  21152. VertexData.ComputeNormals(positions, indices, normals);
  21153. // sides
  21154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21155. // Result
  21156. var vertexData = new VertexData();
  21157. vertexData.indices = indices;
  21158. vertexData.positions = positions;
  21159. vertexData.normals = normals;
  21160. vertexData.uvs = uvs;
  21161. return vertexData;
  21162. };
  21163. VertexData.CreateBox = function (size, sideOrientation) {
  21164. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21165. var normalsSource = [
  21166. new BABYLON.Vector3(0, 0, 1),
  21167. new BABYLON.Vector3(0, 0, -1),
  21168. new BABYLON.Vector3(1, 0, 0),
  21169. new BABYLON.Vector3(-1, 0, 0),
  21170. new BABYLON.Vector3(0, 1, 0),
  21171. new BABYLON.Vector3(0, -1, 0)
  21172. ];
  21173. var indices = [];
  21174. var positions = [];
  21175. var normals = [];
  21176. var uvs = [];
  21177. size = size || 1;
  21178. for (var index = 0; index < normalsSource.length; index++) {
  21179. var normal = normalsSource[index];
  21180. // Get two vectors perpendicular to the face normal and to each other.
  21181. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21182. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21183. // Six indices (two triangles) per face.
  21184. var verticesLength = positions.length / 3;
  21185. indices.push(verticesLength);
  21186. indices.push(verticesLength + 1);
  21187. indices.push(verticesLength + 2);
  21188. indices.push(verticesLength);
  21189. indices.push(verticesLength + 2);
  21190. indices.push(verticesLength + 3);
  21191. // Four vertices per face.
  21192. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21193. positions.push(vertex.x, vertex.y, vertex.z);
  21194. normals.push(normal.x, normal.y, normal.z);
  21195. uvs.push(1.0, 1.0);
  21196. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21197. positions.push(vertex.x, vertex.y, vertex.z);
  21198. normals.push(normal.x, normal.y, normal.z);
  21199. uvs.push(0.0, 1.0);
  21200. vertex = normal.add(side1).add(side2).scale(size / 2);
  21201. positions.push(vertex.x, vertex.y, vertex.z);
  21202. normals.push(normal.x, normal.y, normal.z);
  21203. uvs.push(0.0, 0.0);
  21204. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21205. positions.push(vertex.x, vertex.y, vertex.z);
  21206. normals.push(normal.x, normal.y, normal.z);
  21207. uvs.push(1.0, 0.0);
  21208. }
  21209. // sides
  21210. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21211. // Result
  21212. var vertexData = new VertexData();
  21213. vertexData.indices = indices;
  21214. vertexData.positions = positions;
  21215. vertexData.normals = normals;
  21216. vertexData.uvs = uvs;
  21217. return vertexData;
  21218. };
  21219. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21220. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21221. segments = segments || 32;
  21222. diameter = diameter || 1;
  21223. var radius = diameter / 2;
  21224. var totalZRotationSteps = 2 + segments;
  21225. var totalYRotationSteps = 2 * totalZRotationSteps;
  21226. var indices = [];
  21227. var positions = [];
  21228. var normals = [];
  21229. var uvs = [];
  21230. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21231. var normalizedZ = zRotationStep / totalZRotationSteps;
  21232. var angleZ = (normalizedZ * Math.PI);
  21233. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21234. var normalizedY = yRotationStep / totalYRotationSteps;
  21235. var angleY = normalizedY * Math.PI * 2;
  21236. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21237. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21238. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21239. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21240. var vertex = complete.scale(radius);
  21241. var normal = BABYLON.Vector3.Normalize(vertex);
  21242. positions.push(vertex.x, vertex.y, vertex.z);
  21243. normals.push(normal.x, normal.y, normal.z);
  21244. uvs.push(normalizedZ, normalizedY);
  21245. }
  21246. if (zRotationStep > 0) {
  21247. var verticesCount = positions.length / 3;
  21248. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21249. indices.push((firstIndex));
  21250. indices.push((firstIndex + 1));
  21251. indices.push(firstIndex + totalYRotationSteps + 1);
  21252. indices.push((firstIndex + totalYRotationSteps + 1));
  21253. indices.push((firstIndex + 1));
  21254. indices.push((firstIndex + totalYRotationSteps + 2));
  21255. }
  21256. }
  21257. }
  21258. // Sides
  21259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21260. // Result
  21261. var vertexData = new VertexData();
  21262. vertexData.indices = indices;
  21263. vertexData.positions = positions;
  21264. vertexData.normals = normals;
  21265. vertexData.uvs = uvs;
  21266. return vertexData;
  21267. };
  21268. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21269. if (subdivisions === void 0) { subdivisions = 1; }
  21270. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21271. var radiusTop = diameterTop / 2;
  21272. var radiusBottom = diameterBottom / 2;
  21273. var indices = [];
  21274. var positions = [];
  21275. var normals = [];
  21276. var uvs = [];
  21277. height = height || 1;
  21278. diameterTop = diameterTop || 0.5;
  21279. diameterBottom = diameterBottom || 1;
  21280. tessellation = tessellation || 16;
  21281. subdivisions = subdivisions || 1;
  21282. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21283. var getCircleVector = function (i) {
  21284. var angle = (i * 2.0 * Math.PI / tessellation);
  21285. var dx = Math.cos(angle);
  21286. var dz = Math.sin(angle);
  21287. return new BABYLON.Vector3(dx, 0, dz);
  21288. };
  21289. var createCylinderCap = function (isTop) {
  21290. var radius = isTop ? radiusTop : radiusBottom;
  21291. if (radius === 0) {
  21292. return;
  21293. }
  21294. var vbase = positions.length / 3;
  21295. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21296. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21297. if (!isTop) {
  21298. offset.scaleInPlace(-1);
  21299. textureScale.x = -textureScale.x;
  21300. }
  21301. for (var i = 0; i < tessellation; i++) {
  21302. var circleVector = getCircleVector(i);
  21303. var position = circleVector.scale(radius).add(offset);
  21304. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21305. positions.push(position.x, position.y, position.z);
  21306. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21307. }
  21308. for (i = 0; i < tessellation - 2; i++) {
  21309. if (!isTop) {
  21310. indices.push(vbase);
  21311. indices.push(vbase + (i + 2) % tessellation);
  21312. indices.push(vbase + (i + 1) % tessellation);
  21313. }
  21314. else {
  21315. indices.push(vbase);
  21316. indices.push(vbase + (i + 1) % tessellation);
  21317. indices.push(vbase + (i + 2) % tessellation);
  21318. }
  21319. }
  21320. };
  21321. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21322. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21323. var stride = tessellation + 1;
  21324. for (var i = 0; i <= tessellation; i++) {
  21325. var circleVector = getCircleVector(i);
  21326. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21327. var position, radius = radiusBottom;
  21328. for (var s = 0; s <= subdivisions; s++) {
  21329. // Update variables
  21330. position = circleVector.scale(radius);
  21331. position.addInPlace(base.add(offset.scale(s)));
  21332. textureCoordinate.y += 1 / subdivisions;
  21333. radius += (radiusTop - radiusBottom) / subdivisions;
  21334. // Push in arrays
  21335. positions.push(position.x, position.y, position.z);
  21336. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21337. }
  21338. }
  21339. subdivisions += 1;
  21340. for (s = 0; s < subdivisions - 1; s++) {
  21341. for (i = 0; i <= tessellation; i++) {
  21342. indices.push(i * subdivisions + s);
  21343. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21344. indices.push(i * subdivisions + (s + 1));
  21345. indices.push(i * subdivisions + (s + 1));
  21346. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21347. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21348. }
  21349. }
  21350. // Create flat triangle fan caps to seal the top and bottom.
  21351. createCylinderCap(true);
  21352. createCylinderCap(false);
  21353. // Normals
  21354. VertexData.ComputeNormals(positions, indices, normals);
  21355. // Sides
  21356. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21357. // Result
  21358. var vertexData = new VertexData();
  21359. vertexData.indices = indices;
  21360. vertexData.positions = positions;
  21361. vertexData.normals = normals;
  21362. vertexData.uvs = uvs;
  21363. return vertexData;
  21364. };
  21365. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21366. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21367. var indices = [];
  21368. var positions = [];
  21369. var normals = [];
  21370. var uvs = [];
  21371. diameter = diameter || 1;
  21372. thickness = thickness || 0.5;
  21373. tessellation = tessellation || 16;
  21374. var stride = tessellation + 1;
  21375. for (var i = 0; i <= tessellation; i++) {
  21376. var u = i / tessellation;
  21377. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21378. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21379. for (var j = 0; j <= tessellation; j++) {
  21380. var v = 1 - j / tessellation;
  21381. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21382. var dx = Math.cos(innerAngle);
  21383. var dy = Math.sin(innerAngle);
  21384. // Create a vertex.
  21385. var normal = new BABYLON.Vector3(dx, dy, 0);
  21386. var position = normal.scale(thickness / 2);
  21387. var textureCoordinate = new BABYLON.Vector2(u, v);
  21388. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21389. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21390. positions.push(position.x, position.y, position.z);
  21391. normals.push(normal.x, normal.y, normal.z);
  21392. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21393. // And create indices for two triangles.
  21394. var nextI = (i + 1) % stride;
  21395. var nextJ = (j + 1) % stride;
  21396. indices.push(i * stride + j);
  21397. indices.push(i * stride + nextJ);
  21398. indices.push(nextI * stride + j);
  21399. indices.push(i * stride + nextJ);
  21400. indices.push(nextI * stride + nextJ);
  21401. indices.push(nextI * stride + j);
  21402. }
  21403. }
  21404. // Sides
  21405. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21406. // Result
  21407. var vertexData = new VertexData();
  21408. vertexData.indices = indices;
  21409. vertexData.positions = positions;
  21410. vertexData.normals = normals;
  21411. vertexData.uvs = uvs;
  21412. return vertexData;
  21413. };
  21414. VertexData.CreateLines = function (points) {
  21415. var indices = [];
  21416. var positions = [];
  21417. for (var index = 0; index < points.length; index++) {
  21418. positions.push(points[index].x, points[index].y, points[index].z);
  21419. if (index > 0) {
  21420. indices.push(index - 1);
  21421. indices.push(index);
  21422. }
  21423. }
  21424. // Result
  21425. var vertexData = new VertexData();
  21426. vertexData.indices = indices;
  21427. vertexData.positions = positions;
  21428. return vertexData;
  21429. };
  21430. VertexData.CreateGround = function (width, height, subdivisions) {
  21431. var indices = [];
  21432. var positions = [];
  21433. var normals = [];
  21434. var uvs = [];
  21435. var row, col;
  21436. width = width || 1;
  21437. height = height || 1;
  21438. subdivisions = subdivisions || 1;
  21439. for (row = 0; row <= subdivisions; row++) {
  21440. for (col = 0; col <= subdivisions; col++) {
  21441. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21442. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21443. positions.push(position.x, position.y, position.z);
  21444. normals.push(normal.x, normal.y, normal.z);
  21445. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21446. }
  21447. }
  21448. for (row = 0; row < subdivisions; row++) {
  21449. for (col = 0; col < subdivisions; col++) {
  21450. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21451. indices.push(col + 1 + row * (subdivisions + 1));
  21452. indices.push(col + row * (subdivisions + 1));
  21453. indices.push(col + (row + 1) * (subdivisions + 1));
  21454. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21455. indices.push(col + row * (subdivisions + 1));
  21456. }
  21457. }
  21458. // Result
  21459. var vertexData = new VertexData();
  21460. vertexData.indices = indices;
  21461. vertexData.positions = positions;
  21462. vertexData.normals = normals;
  21463. vertexData.uvs = uvs;
  21464. return vertexData;
  21465. };
  21466. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21467. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21468. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21469. var indices = [];
  21470. var positions = [];
  21471. var normals = [];
  21472. var uvs = [];
  21473. var row, col, tileRow, tileCol;
  21474. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21475. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21476. precision.w = (precision.w < 1) ? 1 : precision.w;
  21477. precision.h = (precision.h < 1) ? 1 : precision.h;
  21478. var tileSize = {
  21479. 'w': (xmax - xmin) / subdivisions.w,
  21480. 'h': (zmax - zmin) / subdivisions.h
  21481. };
  21482. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21483. // Indices
  21484. var base = positions.length / 3;
  21485. var rowLength = precision.w + 1;
  21486. for (row = 0; row < precision.h; row++) {
  21487. for (col = 0; col < precision.w; col++) {
  21488. var square = [
  21489. base + col + row * rowLength,
  21490. base + (col + 1) + row * rowLength,
  21491. base + (col + 1) + (row + 1) * rowLength,
  21492. base + col + (row + 1) * rowLength
  21493. ];
  21494. indices.push(square[1]);
  21495. indices.push(square[2]);
  21496. indices.push(square[3]);
  21497. indices.push(square[0]);
  21498. indices.push(square[1]);
  21499. indices.push(square[3]);
  21500. }
  21501. }
  21502. // Position, normals and uvs
  21503. var position = BABYLON.Vector3.Zero();
  21504. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21505. for (row = 0; row <= precision.h; row++) {
  21506. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21507. for (col = 0; col <= precision.w; col++) {
  21508. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21509. position.y = 0;
  21510. positions.push(position.x, position.y, position.z);
  21511. normals.push(normal.x, normal.y, normal.z);
  21512. uvs.push(col / precision.w, row / precision.h);
  21513. }
  21514. }
  21515. }
  21516. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21517. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21518. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21519. }
  21520. }
  21521. // Result
  21522. var vertexData = new VertexData();
  21523. vertexData.indices = indices;
  21524. vertexData.positions = positions;
  21525. vertexData.normals = normals;
  21526. vertexData.uvs = uvs;
  21527. return vertexData;
  21528. };
  21529. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21530. var indices = [];
  21531. var positions = [];
  21532. var normals = [];
  21533. var uvs = [];
  21534. var row, col;
  21535. for (row = 0; row <= subdivisions; row++) {
  21536. for (col = 0; col <= subdivisions; col++) {
  21537. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21538. // Compute height
  21539. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21540. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21541. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21542. var r = buffer[pos] / 255.0;
  21543. var g = buffer[pos + 1] / 255.0;
  21544. var b = buffer[pos + 2] / 255.0;
  21545. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21546. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21547. // Add vertex
  21548. positions.push(position.x, position.y, position.z);
  21549. normals.push(0, 0, 0);
  21550. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21551. }
  21552. }
  21553. for (row = 0; row < subdivisions; row++) {
  21554. for (col = 0; col < subdivisions; col++) {
  21555. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21556. indices.push(col + 1 + row * (subdivisions + 1));
  21557. indices.push(col + row * (subdivisions + 1));
  21558. indices.push(col + (row + 1) * (subdivisions + 1));
  21559. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21560. indices.push(col + row * (subdivisions + 1));
  21561. }
  21562. }
  21563. // Normals
  21564. VertexData.ComputeNormals(positions, indices, normals);
  21565. // Result
  21566. var vertexData = new VertexData();
  21567. vertexData.indices = indices;
  21568. vertexData.positions = positions;
  21569. vertexData.normals = normals;
  21570. vertexData.uvs = uvs;
  21571. return vertexData;
  21572. };
  21573. VertexData.CreatePlane = function (size, sideOrientation) {
  21574. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21575. var indices = [];
  21576. var positions = [];
  21577. var normals = [];
  21578. var uvs = [];
  21579. size = size || 1;
  21580. // Vertices
  21581. var halfSize = size / 2.0;
  21582. positions.push(-halfSize, -halfSize, 0);
  21583. normals.push(0, 0, -1.0);
  21584. uvs.push(0.0, 0.0);
  21585. positions.push(halfSize, -halfSize, 0);
  21586. normals.push(0, 0, -1.0);
  21587. uvs.push(1.0, 0.0);
  21588. positions.push(halfSize, halfSize, 0);
  21589. normals.push(0, 0, -1.0);
  21590. uvs.push(1.0, 1.0);
  21591. positions.push(-halfSize, halfSize, 0);
  21592. normals.push(0, 0, -1.0);
  21593. uvs.push(0.0, 1.0);
  21594. // Indices
  21595. indices.push(0);
  21596. indices.push(1);
  21597. indices.push(2);
  21598. indices.push(0);
  21599. indices.push(2);
  21600. indices.push(3);
  21601. // Sides
  21602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21603. // Result
  21604. var vertexData = new VertexData();
  21605. vertexData.indices = indices;
  21606. vertexData.positions = positions;
  21607. vertexData.normals = normals;
  21608. vertexData.uvs = uvs;
  21609. return vertexData;
  21610. };
  21611. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21612. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  21613. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21614. var indices = [];
  21615. var positions = [];
  21616. var normals = [];
  21617. var uvs = [];
  21618. radius = radius || 2;
  21619. tube = tube || 0.5;
  21620. radialSegments = radialSegments || 32;
  21621. tubularSegments = tubularSegments || 32;
  21622. p = p || 2;
  21623. q = q || 3;
  21624. // Helper
  21625. var getPos = function (angle) {
  21626. var cu = Math.cos(angle);
  21627. var su = Math.sin(angle);
  21628. var quOverP = q / p * angle;
  21629. var cs = Math.cos(quOverP);
  21630. var tx = radius * (2 + cs) * 0.5 * cu;
  21631. var ty = radius * (2 + cs) * su * 0.5;
  21632. var tz = radius * Math.sin(quOverP) * 0.5;
  21633. return new BABYLON.Vector3(tx, ty, tz);
  21634. };
  21635. for (var i = 0; i <= radialSegments; i++) {
  21636. var modI = i % radialSegments;
  21637. var u = modI / radialSegments * 2 * p * Math.PI;
  21638. var p1 = getPos(u);
  21639. var p2 = getPos(u + 0.01);
  21640. var tang = p2.subtract(p1);
  21641. var n = p2.add(p1);
  21642. var bitan = BABYLON.Vector3.Cross(tang, n);
  21643. n = BABYLON.Vector3.Cross(bitan, tang);
  21644. bitan.normalize();
  21645. n.normalize();
  21646. for (var j = 0; j < tubularSegments; j++) {
  21647. var modJ = j % tubularSegments;
  21648. var v = modJ / tubularSegments * 2 * Math.PI;
  21649. var cx = -tube * Math.cos(v);
  21650. var cy = tube * Math.sin(v);
  21651. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21652. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21653. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21654. uvs.push(i / radialSegments);
  21655. uvs.push(j / tubularSegments);
  21656. }
  21657. }
  21658. for (i = 0; i < radialSegments; i++) {
  21659. for (j = 0; j < tubularSegments; j++) {
  21660. var jNext = (j + 1) % tubularSegments;
  21661. var a = i * tubularSegments + j;
  21662. var b = (i + 1) * tubularSegments + j;
  21663. var c = (i + 1) * tubularSegments + jNext;
  21664. var d = i * tubularSegments + jNext;
  21665. indices.push(d);
  21666. indices.push(b);
  21667. indices.push(a);
  21668. indices.push(d);
  21669. indices.push(c);
  21670. indices.push(b);
  21671. }
  21672. }
  21673. // Normals
  21674. VertexData.ComputeNormals(positions, indices, normals);
  21675. // Sides
  21676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21677. // Result
  21678. var vertexData = new VertexData();
  21679. vertexData.indices = indices;
  21680. vertexData.positions = positions;
  21681. vertexData.normals = normals;
  21682. vertexData.uvs = uvs;
  21683. return vertexData;
  21684. };
  21685. // Tools
  21686. VertexData.ComputeNormals = function (positions, indices, normals) {
  21687. var positionVectors = [];
  21688. var facesOfVertices = [];
  21689. var index;
  21690. for (index = 0; index < positions.length; index += 3) {
  21691. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21692. positionVectors.push(vector3);
  21693. facesOfVertices.push([]);
  21694. }
  21695. // Compute normals
  21696. var facesNormals = [];
  21697. for (index = 0; index < indices.length / 3; index++) {
  21698. var i1 = indices[index * 3];
  21699. var i2 = indices[index * 3 + 1];
  21700. var i3 = indices[index * 3 + 2];
  21701. var p1 = positionVectors[i1];
  21702. var p2 = positionVectors[i2];
  21703. var p3 = positionVectors[i3];
  21704. var p1p2 = p1.subtract(p2);
  21705. var p3p2 = p3.subtract(p2);
  21706. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21707. facesOfVertices[i1].push(index);
  21708. facesOfVertices[i2].push(index);
  21709. facesOfVertices[i3].push(index);
  21710. }
  21711. for (index = 0; index < positionVectors.length; index++) {
  21712. var faces = facesOfVertices[index];
  21713. var normal = BABYLON.Vector3.Zero();
  21714. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21715. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21716. }
  21717. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21718. normals[index * 3] = normal.x;
  21719. normals[index * 3 + 1] = normal.y;
  21720. normals[index * 3 + 2] = normal.z;
  21721. }
  21722. };
  21723. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  21724. var li = indices.length;
  21725. var ln = normals.length;
  21726. var i;
  21727. var n;
  21728. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21729. switch (sideOrientation) {
  21730. case BABYLON.Mesh.FRONTSIDE:
  21731. break;
  21732. case BABYLON.Mesh.BACKSIDE:
  21733. var tmp;
  21734. for (i = 0; i < li; i += 3) {
  21735. tmp = indices[i];
  21736. indices[i] = indices[i + 2];
  21737. indices[i + 2] = tmp;
  21738. }
  21739. for (n = 0; n < ln; n++) {
  21740. normals[n] = -normals[n];
  21741. }
  21742. break;
  21743. case BABYLON.Mesh.DOUBLESIDE:
  21744. // positions
  21745. var lp = positions.length;
  21746. var l = lp / 3;
  21747. for (var p = 0; p < lp; p++) {
  21748. positions[lp + p] = positions[p];
  21749. }
  21750. for (i = 0; i < li; i += 3) {
  21751. indices[i + li] = indices[i + 2] + l;
  21752. indices[i + 1 + li] = indices[i + 1] + l;
  21753. indices[i + 2 + li] = indices[i] + l;
  21754. }
  21755. for (n = 0; n < ln; n++) {
  21756. normals[ln + n] = -normals[n];
  21757. }
  21758. // uvs
  21759. var lu = uvs.length;
  21760. for (var u = 0; u < lu; u++) {
  21761. uvs[u + lu] = uvs[u];
  21762. }
  21763. break;
  21764. }
  21765. };
  21766. return VertexData;
  21767. })();
  21768. BABYLON.VertexData = VertexData;
  21769. })(BABYLON || (BABYLON = {}));
  21770. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21771. var BABYLON;
  21772. (function (BABYLON) {
  21773. var buildCamera = function (that, name) {
  21774. that._leftCamera.isIntermediate = true;
  21775. that.subCameras.push(that._leftCamera);
  21776. that.subCameras.push(that._rightCamera);
  21777. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21778. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21779. that._anaglyphPostProcess.onApply = function (effect) {
  21780. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21781. };
  21782. that._update();
  21783. };
  21784. var AnaglyphArcRotateCamera = (function (_super) {
  21785. __extends(AnaglyphArcRotateCamera, _super);
  21786. // ANY
  21787. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21788. _super.call(this, name, alpha, beta, radius, target, scene);
  21789. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21790. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21791. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21792. buildCamera(this, name);
  21793. }
  21794. AnaglyphArcRotateCamera.prototype._update = function () {
  21795. this._updateCamera(this._leftCamera);
  21796. this._updateCamera(this._rightCamera);
  21797. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21798. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21799. _super.prototype._update.call(this);
  21800. };
  21801. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21802. camera.beta = this.beta;
  21803. camera.radius = this.radius;
  21804. camera.minZ = this.minZ;
  21805. camera.maxZ = this.maxZ;
  21806. camera.fov = this.fov;
  21807. camera.target = this.target;
  21808. };
  21809. return AnaglyphArcRotateCamera;
  21810. })(BABYLON.ArcRotateCamera);
  21811. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21812. var AnaglyphFreeCamera = (function (_super) {
  21813. __extends(AnaglyphFreeCamera, _super);
  21814. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21815. _super.call(this, name, position, scene);
  21816. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21817. this._transformMatrix = new BABYLON.Matrix();
  21818. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21819. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21820. buildCamera(this, name);
  21821. }
  21822. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21823. var target = this.getTarget();
  21824. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21825. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21826. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21827. };
  21828. AnaglyphFreeCamera.prototype._update = function () {
  21829. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21830. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21831. this._updateCamera(this._leftCamera);
  21832. this._updateCamera(this._rightCamera);
  21833. _super.prototype._update.call(this);
  21834. };
  21835. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21836. camera.minZ = this.minZ;
  21837. camera.maxZ = this.maxZ;
  21838. camera.fov = this.fov;
  21839. camera.viewport = this.viewport;
  21840. camera.setTarget(this.getTarget());
  21841. };
  21842. return AnaglyphFreeCamera;
  21843. })(BABYLON.FreeCamera);
  21844. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21845. })(BABYLON || (BABYLON = {}));
  21846. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21847. var BABYLON;
  21848. (function (BABYLON) {
  21849. var AnaglyphPostProcess = (function (_super) {
  21850. __extends(AnaglyphPostProcess, _super);
  21851. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21852. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21853. }
  21854. return AnaglyphPostProcess;
  21855. })(BABYLON.PostProcess);
  21856. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21857. })(BABYLON || (BABYLON = {}));
  21858. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21859. (function (BABYLON) {
  21860. var Tags = (function () {
  21861. function Tags() {
  21862. }
  21863. Tags.EnableFor = function (obj) {
  21864. obj._tags = obj._tags || {};
  21865. obj.hasTags = function () {
  21866. return Tags.HasTags(obj);
  21867. };
  21868. obj.addTags = function (tagsString) {
  21869. return Tags.AddTagsTo(obj, tagsString);
  21870. };
  21871. obj.removeTags = function (tagsString) {
  21872. return Tags.RemoveTagsFrom(obj, tagsString);
  21873. };
  21874. obj.matchesTagsQuery = function (tagsQuery) {
  21875. return Tags.MatchesQuery(obj, tagsQuery);
  21876. };
  21877. };
  21878. Tags.DisableFor = function (obj) {
  21879. delete obj._tags;
  21880. delete obj.hasTags;
  21881. delete obj.addTags;
  21882. delete obj.removeTags;
  21883. delete obj.matchesTagsQuery;
  21884. };
  21885. Tags.HasTags = function (obj) {
  21886. if (!obj._tags) {
  21887. return false;
  21888. }
  21889. return !BABYLON.Tools.IsEmpty(obj._tags);
  21890. };
  21891. Tags.GetTags = function (obj) {
  21892. if (!obj._tags) {
  21893. return null;
  21894. }
  21895. return obj._tags;
  21896. };
  21897. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21898. // a tag cannot start with '||', '&&', and '!'
  21899. // it cannot contain whitespaces
  21900. Tags.AddTagsTo = function (obj, tagsString) {
  21901. if (!tagsString) {
  21902. return;
  21903. }
  21904. var tags = tagsString.split(" ");
  21905. for (var t in tags) {
  21906. Tags._AddTagTo(obj, tags[t]);
  21907. }
  21908. };
  21909. Tags._AddTagTo = function (obj, tag) {
  21910. tag = tag.trim();
  21911. if (tag === "" || tag === "true" || tag === "false") {
  21912. return;
  21913. }
  21914. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21915. return;
  21916. }
  21917. Tags.EnableFor(obj);
  21918. obj._tags[tag] = true;
  21919. };
  21920. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21921. if (!Tags.HasTags(obj)) {
  21922. return;
  21923. }
  21924. var tags = tagsString.split(" ");
  21925. for (var t in tags) {
  21926. Tags._RemoveTagFrom(obj, tags[t]);
  21927. }
  21928. };
  21929. Tags._RemoveTagFrom = function (obj, tag) {
  21930. delete obj._tags[tag];
  21931. };
  21932. Tags.MatchesQuery = function (obj, tagsQuery) {
  21933. if (tagsQuery === undefined) {
  21934. return true;
  21935. }
  21936. if (tagsQuery === "") {
  21937. return Tags.HasTags(obj);
  21938. }
  21939. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21940. };
  21941. return Tags;
  21942. })();
  21943. BABYLON.Tags = Tags;
  21944. })(BABYLON || (BABYLON = {}));
  21945. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21946. (function (BABYLON) {
  21947. var Internals;
  21948. (function (Internals) {
  21949. var AndOrNotEvaluator = (function () {
  21950. function AndOrNotEvaluator() {
  21951. }
  21952. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21953. if (!query.match(/\([^\(\)]*\)/g)) {
  21954. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21955. }
  21956. else {
  21957. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21958. // remove parenthesis
  21959. r = r.slice(1, r.length - 1);
  21960. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21961. });
  21962. }
  21963. if (query === "true") {
  21964. return true;
  21965. }
  21966. if (query === "false") {
  21967. return false;
  21968. }
  21969. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21970. };
  21971. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21972. evaluateCallback = evaluateCallback || (function (r) {
  21973. return r === "true" ? true : false;
  21974. });
  21975. var result;
  21976. var or = parenthesisContent.split("||");
  21977. for (var i in or) {
  21978. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21979. var and = ori.split("&&");
  21980. if (and.length > 1) {
  21981. for (var j = 0; j < and.length; ++j) {
  21982. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21983. if (andj !== "true" && andj !== "false") {
  21984. if (andj[0] === "!") {
  21985. result = !evaluateCallback(andj.substring(1));
  21986. }
  21987. else {
  21988. result = evaluateCallback(andj);
  21989. }
  21990. }
  21991. else {
  21992. result = andj === "true" ? true : false;
  21993. }
  21994. if (!result) {
  21995. ori = "false";
  21996. break;
  21997. }
  21998. }
  21999. }
  22000. if (result || ori === "true") {
  22001. result = true;
  22002. break;
  22003. }
  22004. // result equals false (or undefined)
  22005. if (ori !== "true" && ori !== "false") {
  22006. if (ori[0] === "!") {
  22007. result = !evaluateCallback(ori.substring(1));
  22008. }
  22009. else {
  22010. result = evaluateCallback(ori);
  22011. }
  22012. }
  22013. else {
  22014. result = ori === "true" ? true : false;
  22015. }
  22016. }
  22017. // the whole parenthesis scope is replaced by 'true' or 'false'
  22018. return result ? "true" : "false";
  22019. };
  22020. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22021. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22022. // remove whitespaces
  22023. r = r.replace(/[\s]/g, function () { return ""; });
  22024. return r.length % 2 ? "!" : "";
  22025. });
  22026. booleanString = booleanString.trim();
  22027. if (booleanString === "!true") {
  22028. booleanString = "false";
  22029. }
  22030. else if (booleanString === "!false") {
  22031. booleanString = "true";
  22032. }
  22033. return booleanString;
  22034. };
  22035. return AndOrNotEvaluator;
  22036. })();
  22037. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22039. })(BABYLON || (BABYLON = {}));
  22040. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22041. (function (BABYLON) {
  22042. var PostProcessRenderPass = (function () {
  22043. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22044. this._enabled = true;
  22045. this._refCount = 0;
  22046. this._name = name;
  22047. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22048. this.setRenderList(renderList);
  22049. this._renderTexture.onBeforeRender = beforeRender;
  22050. this._renderTexture.onAfterRender = afterRender;
  22051. this._scene = scene;
  22052. this._renderList = renderList;
  22053. }
  22054. // private
  22055. PostProcessRenderPass.prototype._incRefCount = function () {
  22056. if (this._refCount === 0) {
  22057. this._scene.customRenderTargets.push(this._renderTexture);
  22058. }
  22059. return ++this._refCount;
  22060. };
  22061. PostProcessRenderPass.prototype._decRefCount = function () {
  22062. this._refCount--;
  22063. if (this._refCount <= 0) {
  22064. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22065. }
  22066. return this._refCount;
  22067. };
  22068. PostProcessRenderPass.prototype._update = function () {
  22069. this.setRenderList(this._renderList);
  22070. };
  22071. // public
  22072. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22073. this._renderTexture.renderList = renderList;
  22074. };
  22075. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22076. return this._renderTexture;
  22077. };
  22078. return PostProcessRenderPass;
  22079. })();
  22080. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22081. })(BABYLON || (BABYLON = {}));
  22082. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22083. (function (BABYLON) {
  22084. var PostProcessRenderEffect = (function () {
  22085. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22086. this._engine = engine;
  22087. this._name = name;
  22088. this._singleInstance = singleInstance || true;
  22089. this._getPostProcess = getPostProcess;
  22090. this._cameras = [];
  22091. this._indicesForCamera = [];
  22092. this._postProcesses = {};
  22093. this._renderPasses = {};
  22094. this._renderEffectAsPasses = {};
  22095. }
  22096. PostProcessRenderEffect.prototype._update = function () {
  22097. for (var renderPassName in this._renderPasses) {
  22098. this._renderPasses[renderPassName]._update();
  22099. }
  22100. };
  22101. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22102. this._renderPasses[renderPass._name] = renderPass;
  22103. this._linkParameters();
  22104. };
  22105. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22106. delete this._renderPasses[renderPass._name];
  22107. this._linkParameters();
  22108. };
  22109. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22110. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22111. this._linkParameters();
  22112. };
  22113. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22114. for (var renderPassName in this._renderPasses) {
  22115. if (renderPassName === passName) {
  22116. return this._renderPasses[passName];
  22117. }
  22118. }
  22119. };
  22120. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22121. this._renderPasses = {};
  22122. this._linkParameters();
  22123. };
  22124. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22125. var cameraKey;
  22126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22127. for (var i = 0; i < _cam.length; i++) {
  22128. var camera = _cam[i];
  22129. var cameraName = camera.name;
  22130. if (this._singleInstance) {
  22131. cameraKey = 0;
  22132. }
  22133. else {
  22134. cameraKey = cameraName;
  22135. }
  22136. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22137. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22138. if (!this._indicesForCamera[cameraName]) {
  22139. this._indicesForCamera[cameraName] = [];
  22140. }
  22141. this._indicesForCamera[cameraName].push(index);
  22142. if (this._cameras.indexOf(camera) === -1) {
  22143. this._cameras[cameraName] = camera;
  22144. }
  22145. for (var passName in this._renderPasses) {
  22146. this._renderPasses[passName]._incRefCount();
  22147. }
  22148. }
  22149. this._linkParameters();
  22150. };
  22151. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22152. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22153. for (var i = 0; i < _cam.length; i++) {
  22154. var camera = _cam[i];
  22155. var cameraName = camera.name;
  22156. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22157. var index = this._cameras.indexOf(cameraName);
  22158. this._indicesForCamera.splice(index, 1);
  22159. this._cameras.splice(index, 1);
  22160. for (var passName in this._renderPasses) {
  22161. this._renderPasses[passName]._decRefCount();
  22162. }
  22163. }
  22164. };
  22165. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22166. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22167. for (var i = 0; i < _cam.length; i++) {
  22168. var camera = _cam[i];
  22169. var cameraName = camera.name;
  22170. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22171. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22172. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22173. }
  22174. }
  22175. for (var passName in this._renderPasses) {
  22176. this._renderPasses[passName]._incRefCount();
  22177. }
  22178. }
  22179. };
  22180. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22181. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22182. for (var i = 0; i < _cam.length; i++) {
  22183. var camera = _cam[i];
  22184. var cameraName = camera.Name;
  22185. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22186. for (var passName in this._renderPasses) {
  22187. this._renderPasses[passName]._decRefCount();
  22188. }
  22189. }
  22190. };
  22191. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22192. if (this._singleInstance) {
  22193. return this._postProcesses[0];
  22194. }
  22195. else {
  22196. return this._postProcesses[camera.name];
  22197. }
  22198. };
  22199. PostProcessRenderEffect.prototype._linkParameters = function () {
  22200. var _this = this;
  22201. for (var index in this._postProcesses) {
  22202. if (this.applyParameters) {
  22203. this.applyParameters(this._postProcesses[index]);
  22204. }
  22205. this._postProcesses[index].onBeforeRender = function (effect) {
  22206. _this._linkTextures(effect);
  22207. };
  22208. }
  22209. };
  22210. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22211. for (var renderPassName in this._renderPasses) {
  22212. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22213. }
  22214. for (var renderEffectName in this._renderEffectAsPasses) {
  22215. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22216. }
  22217. };
  22218. return PostProcessRenderEffect;
  22219. })();
  22220. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22221. })(BABYLON || (BABYLON = {}));
  22222. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22223. (function (BABYLON) {
  22224. var PostProcessRenderPipeline = (function () {
  22225. function PostProcessRenderPipeline(engine, name) {
  22226. this._engine = engine;
  22227. this._name = name;
  22228. this._renderEffects = {};
  22229. this._renderEffectsForIsolatedPass = {};
  22230. this._cameras = [];
  22231. }
  22232. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22233. this._renderEffects[renderEffect._name] = renderEffect;
  22234. };
  22235. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22236. var renderEffects = this._renderEffects[renderEffectName];
  22237. if (!renderEffects) {
  22238. return;
  22239. }
  22240. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22241. };
  22242. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22243. var renderEffects = this._renderEffects[renderEffectName];
  22244. if (!renderEffects) {
  22245. return;
  22246. }
  22247. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22248. };
  22249. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22250. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22251. var indicesToDelete = [];
  22252. for (var i = 0; i < _cam.length; i++) {
  22253. var camera = _cam[i];
  22254. var cameraName = camera.name;
  22255. if (this._cameras.indexOf(camera) === -1) {
  22256. this._cameras[cameraName] = camera;
  22257. }
  22258. else if (unique) {
  22259. indicesToDelete.push(i);
  22260. }
  22261. }
  22262. for (var i = 0; i < indicesToDelete.length; i++) {
  22263. cameras.splice(indicesToDelete[i], 1);
  22264. }
  22265. for (var renderEffectName in this._renderEffects) {
  22266. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22267. }
  22268. };
  22269. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22270. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22271. for (var renderEffectName in this._renderEffects) {
  22272. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22273. }
  22274. for (var i = 0; i < _cam.length; i++) {
  22275. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22276. }
  22277. };
  22278. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22279. var _this = this;
  22280. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22281. var pass = null;
  22282. for (var renderEffectName in this._renderEffects) {
  22283. pass = this._renderEffects[renderEffectName].getPass(passName);
  22284. if (pass != null) {
  22285. break;
  22286. }
  22287. }
  22288. if (pass === null) {
  22289. return;
  22290. }
  22291. for (var renderEffectName in this._renderEffects) {
  22292. this._renderEffects[renderEffectName]._disable(_cam);
  22293. }
  22294. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22295. for (var i = 0; i < _cam.length; i++) {
  22296. var camera = _cam[i];
  22297. var cameraName = camera.name;
  22298. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22299. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22300. });
  22301. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22302. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22303. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22304. }
  22305. };
  22306. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22307. var _this = this;
  22308. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22309. for (var i = 0; i < _cam.length; i++) {
  22310. var camera = _cam[i];
  22311. var cameraName = camera.name;
  22312. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22313. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22314. });
  22315. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22316. }
  22317. for (var renderEffectName in this._renderEffects) {
  22318. this._renderEffects[renderEffectName]._enable(_cam);
  22319. }
  22320. };
  22321. PostProcessRenderPipeline.prototype._update = function () {
  22322. for (var renderEffectName in this._renderEffects) {
  22323. this._renderEffects[renderEffectName]._update();
  22324. }
  22325. for (var i = 0; i < this._cameras.length; i++) {
  22326. var cameraName = this._cameras[i].name;
  22327. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22328. this._renderEffectsForIsolatedPass[cameraName]._update();
  22329. }
  22330. }
  22331. };
  22332. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22333. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22334. return PostProcessRenderPipeline;
  22335. })();
  22336. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22337. })(BABYLON || (BABYLON = {}));
  22338. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22339. (function (BABYLON) {
  22340. var PostProcessRenderPipelineManager = (function () {
  22341. function PostProcessRenderPipelineManager() {
  22342. this._renderPipelines = {};
  22343. }
  22344. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22345. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22346. };
  22347. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22348. var renderPipeline = this._renderPipelines[renderPipelineName];
  22349. if (!renderPipeline) {
  22350. return;
  22351. }
  22352. renderPipeline._attachCameras(cameras, unique);
  22353. };
  22354. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22355. var renderPipeline = this._renderPipelines[renderPipelineName];
  22356. if (!renderPipeline) {
  22357. return;
  22358. }
  22359. renderPipeline._detachCameras(cameras);
  22360. };
  22361. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22362. var renderPipeline = this._renderPipelines[renderPipelineName];
  22363. if (!renderPipeline) {
  22364. return;
  22365. }
  22366. renderPipeline._enableEffect(renderEffectName, cameras);
  22367. };
  22368. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22369. var renderPipeline = this._renderPipelines[renderPipelineName];
  22370. if (!renderPipeline) {
  22371. return;
  22372. }
  22373. renderPipeline._disableEffect(renderEffectName, cameras);
  22374. };
  22375. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22376. var renderPipeline = this._renderPipelines[renderPipelineName];
  22377. if (!renderPipeline) {
  22378. return;
  22379. }
  22380. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22381. };
  22382. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22383. var renderPipeline = this._renderPipelines[renderPipelineName];
  22384. if (!renderPipeline) {
  22385. return;
  22386. }
  22387. renderPipeline._disableDisplayOnlyPass(cameras);
  22388. };
  22389. PostProcessRenderPipelineManager.prototype.update = function () {
  22390. for (var renderPipelineName in this._renderPipelines) {
  22391. this._renderPipelines[renderPipelineName]._update();
  22392. }
  22393. };
  22394. return PostProcessRenderPipelineManager;
  22395. })();
  22396. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22397. })(BABYLON || (BABYLON = {}));
  22398. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22399. var BABYLON;
  22400. (function (BABYLON) {
  22401. var DisplayPassPostProcess = (function (_super) {
  22402. __extends(DisplayPassPostProcess, _super);
  22403. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22404. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22405. }
  22406. return DisplayPassPostProcess;
  22407. })(BABYLON.PostProcess);
  22408. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22409. })(BABYLON || (BABYLON = {}));
  22410. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22411. (function (BABYLON) {
  22412. var BoundingBoxRenderer = (function () {
  22413. function BoundingBoxRenderer(scene) {
  22414. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22415. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22416. this.showBackLines = true;
  22417. this.renderList = new BABYLON.SmartArray(32);
  22418. this._scene = scene;
  22419. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22420. attributes: ["position"],
  22421. uniforms: ["worldViewProjection", "color"]
  22422. });
  22423. var engine = this._scene.getEngine();
  22424. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22425. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22426. 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]);
  22427. }
  22428. BoundingBoxRenderer.prototype.reset = function () {
  22429. this.renderList.reset();
  22430. };
  22431. BoundingBoxRenderer.prototype.render = function () {
  22432. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22433. return;
  22434. }
  22435. var engine = this._scene.getEngine();
  22436. engine.setDepthWrite(false);
  22437. this._colorShader._preBind();
  22438. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22439. var boundingBox = this.renderList.data[boundingBoxIndex];
  22440. var min = boundingBox.minimum;
  22441. var max = boundingBox.maximum;
  22442. var diff = max.subtract(min);
  22443. var median = min.add(diff.scale(0.5));
  22444. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22445. // VBOs
  22446. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22447. if (this.showBackLines) {
  22448. // Back
  22449. engine.setDepthFunctionToGreaterOrEqual();
  22450. this._scene.resetCachedMaterial();
  22451. this._colorShader.setColor4("color", this.backColor.toColor4());
  22452. this._colorShader.bind(worldMatrix);
  22453. // Draw order
  22454. engine.draw(false, 0, 24);
  22455. }
  22456. // Front
  22457. engine.setDepthFunctionToLess();
  22458. this._scene.resetCachedMaterial();
  22459. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22460. this._colorShader.bind(worldMatrix);
  22461. // Draw order
  22462. engine.draw(false, 0, 24);
  22463. }
  22464. this._colorShader.unbind();
  22465. engine.setDepthFunctionToLessOrEqual();
  22466. engine.setDepthWrite(true);
  22467. };
  22468. BoundingBoxRenderer.prototype.dispose = function () {
  22469. this._colorShader.dispose();
  22470. this._vb.dispose();
  22471. this._scene.getEngine()._releaseBuffer(this._ib);
  22472. };
  22473. return BoundingBoxRenderer;
  22474. })();
  22475. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22476. })(BABYLON || (BABYLON = {}));
  22477. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22478. (function (BABYLON) {
  22479. var Internals;
  22480. (function (Internals) {
  22481. /*
  22482. * Based on jsTGALoader - Javascript loader for TGA file
  22483. * By Vincent Thibault
  22484. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22485. */
  22486. var TGATools = (function () {
  22487. function TGATools() {
  22488. }
  22489. TGATools.GetTGAHeader = function (data) {
  22490. var offset = 0;
  22491. var header = {
  22492. id_length: data[offset++],
  22493. colormap_type: data[offset++],
  22494. image_type: data[offset++],
  22495. colormap_index: data[offset++] | data[offset++] << 8,
  22496. colormap_length: data[offset++] | data[offset++] << 8,
  22497. colormap_size: data[offset++],
  22498. origin: [
  22499. data[offset++] | data[offset++] << 8,
  22500. data[offset++] | data[offset++] << 8
  22501. ],
  22502. width: data[offset++] | data[offset++] << 8,
  22503. height: data[offset++] | data[offset++] << 8,
  22504. pixel_size: data[offset++],
  22505. flags: data[offset++]
  22506. };
  22507. return header;
  22508. };
  22509. TGATools.UploadContent = function (gl, data) {
  22510. // Not enough data to contain header ?
  22511. if (data.length < 19) {
  22512. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22513. return;
  22514. }
  22515. // Read Header
  22516. var offset = 18;
  22517. var header = TGATools.GetTGAHeader(data);
  22518. // Assume it's a valid Targa file.
  22519. if (header.id_length + offset > data.length) {
  22520. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22521. return;
  22522. }
  22523. // Skip not needed data
  22524. offset += header.id_length;
  22525. var use_rle = false;
  22526. var use_pal = false;
  22527. var use_rgb = false;
  22528. var use_grey = false;
  22529. switch (header.image_type) {
  22530. case TGATools._TYPE_RLE_INDEXED:
  22531. use_rle = true;
  22532. case TGATools._TYPE_INDEXED:
  22533. use_pal = true;
  22534. break;
  22535. case TGATools._TYPE_RLE_RGB:
  22536. use_rle = true;
  22537. case TGATools._TYPE_RGB:
  22538. use_rgb = true;
  22539. break;
  22540. case TGATools._TYPE_RLE_GREY:
  22541. use_rle = true;
  22542. case TGATools._TYPE_GREY:
  22543. use_grey = true;
  22544. break;
  22545. }
  22546. var pixel_data;
  22547. var numAlphaBits = header.flags & 0xf;
  22548. var pixel_size = header.pixel_size >> 3;
  22549. var pixel_total = header.width * header.height * pixel_size;
  22550. // Read palettes
  22551. var palettes;
  22552. if (use_pal) {
  22553. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22554. }
  22555. // Read LRE
  22556. if (use_rle) {
  22557. pixel_data = new Uint8Array(pixel_total);
  22558. var c, count, i;
  22559. var localOffset = 0;
  22560. var pixels = new Uint8Array(pixel_size);
  22561. while (offset < pixel_total && localOffset < pixel_total) {
  22562. c = data[offset++];
  22563. count = (c & 0x7f) + 1;
  22564. // RLE pixels
  22565. if (c & 0x80) {
  22566. for (i = 0; i < pixel_size; ++i) {
  22567. pixels[i] = data[offset++];
  22568. }
  22569. for (i = 0; i < count; ++i) {
  22570. pixel_data.set(pixels, localOffset + i * pixel_size);
  22571. }
  22572. localOffset += pixel_size * count;
  22573. }
  22574. else {
  22575. count *= pixel_size;
  22576. for (i = 0; i < count; ++i) {
  22577. pixel_data[localOffset + i] = data[offset++];
  22578. }
  22579. localOffset += count;
  22580. }
  22581. }
  22582. }
  22583. else {
  22584. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22585. }
  22586. // Load to texture
  22587. var x_start, y_start, x_step, y_step, y_end, x_end;
  22588. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22589. default:
  22590. case TGATools._ORIGIN_UL:
  22591. x_start = 0;
  22592. x_step = 1;
  22593. x_end = header.width;
  22594. y_start = 0;
  22595. y_step = 1;
  22596. y_end = header.height;
  22597. break;
  22598. case TGATools._ORIGIN_BL:
  22599. x_start = 0;
  22600. x_step = 1;
  22601. x_end = header.width;
  22602. y_start = header.height - 1;
  22603. y_step = -1;
  22604. y_end = -1;
  22605. break;
  22606. case TGATools._ORIGIN_UR:
  22607. x_start = header.width - 1;
  22608. x_step = -1;
  22609. x_end = -1;
  22610. y_start = 0;
  22611. y_step = 1;
  22612. y_end = header.height;
  22613. break;
  22614. case TGATools._ORIGIN_BR:
  22615. x_start = header.width - 1;
  22616. x_step = -1;
  22617. x_end = -1;
  22618. y_start = header.height - 1;
  22619. y_step = -1;
  22620. y_end = -1;
  22621. break;
  22622. }
  22623. // Load the specify method
  22624. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22625. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22626. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22627. };
  22628. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22629. var image = pixel_data, colormap = palettes;
  22630. var width = header.width, height = header.height;
  22631. var color, i = 0, x, y;
  22632. var imageData = new Uint8Array(width * height * 4);
  22633. for (y = y_start; y !== y_end; y += y_step) {
  22634. for (x = x_start; x !== x_end; x += x_step, i++) {
  22635. color = image[i];
  22636. imageData[(x + width * y) * 4 + 3] = 255;
  22637. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22638. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22639. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22640. }
  22641. }
  22642. return imageData;
  22643. };
  22644. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22645. var image = pixel_data;
  22646. var width = header.width, height = header.height;
  22647. var color, i = 0, x, y;
  22648. var imageData = new Uint8Array(width * height * 4);
  22649. for (y = y_start; y !== y_end; y += y_step) {
  22650. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22651. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22652. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22653. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22654. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22655. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22656. }
  22657. }
  22658. return imageData;
  22659. };
  22660. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22661. var image = pixel_data;
  22662. var width = header.width, height = header.height;
  22663. var i = 0, x, y;
  22664. var imageData = new Uint8Array(width * height * 4);
  22665. for (y = y_start; y !== y_end; y += y_step) {
  22666. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22667. imageData[(x + width * y) * 4 + 3] = 255;
  22668. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22669. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22670. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22671. }
  22672. }
  22673. return imageData;
  22674. };
  22675. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22676. var image = pixel_data;
  22677. var width = header.width, height = header.height;
  22678. var i = 0, x, y;
  22679. var imageData = new Uint8Array(width * height * 4);
  22680. for (y = y_start; y !== y_end; y += y_step) {
  22681. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22682. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22683. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22684. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22685. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22686. }
  22687. }
  22688. return imageData;
  22689. };
  22690. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22691. var image = pixel_data;
  22692. var width = header.width, height = header.height;
  22693. var color, i = 0, x, y;
  22694. var imageData = new Uint8Array(width * height * 4);
  22695. for (y = y_start; y !== y_end; y += y_step) {
  22696. for (x = x_start; x !== x_end; x += x_step, i++) {
  22697. color = image[i];
  22698. imageData[(x + width * y) * 4 + 0] = color;
  22699. imageData[(x + width * y) * 4 + 1] = color;
  22700. imageData[(x + width * y) * 4 + 2] = color;
  22701. imageData[(x + width * y) * 4 + 3] = 255;
  22702. }
  22703. }
  22704. return imageData;
  22705. };
  22706. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22707. var image = pixel_data;
  22708. var width = header.width, height = header.height;
  22709. var i = 0, x, y;
  22710. var imageData = new Uint8Array(width * height * 4);
  22711. for (y = y_start; y !== y_end; y += y_step) {
  22712. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22713. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22714. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22715. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22716. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22717. }
  22718. }
  22719. return imageData;
  22720. };
  22721. TGATools._TYPE_NO_DATA = 0;
  22722. TGATools._TYPE_INDEXED = 1;
  22723. TGATools._TYPE_RGB = 2;
  22724. TGATools._TYPE_GREY = 3;
  22725. TGATools._TYPE_RLE_INDEXED = 9;
  22726. TGATools._TYPE_RLE_RGB = 10;
  22727. TGATools._TYPE_RLE_GREY = 11;
  22728. TGATools._ORIGIN_MASK = 0x30;
  22729. TGATools._ORIGIN_SHIFT = 0x04;
  22730. TGATools._ORIGIN_BL = 0x00;
  22731. TGATools._ORIGIN_BR = 0x01;
  22732. TGATools._ORIGIN_UL = 0x02;
  22733. TGATools._ORIGIN_UR = 0x03;
  22734. return TGATools;
  22735. })();
  22736. Internals.TGATools = TGATools;
  22737. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22738. })(BABYLON || (BABYLON = {}));
  22739. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22740. (function (BABYLON) {
  22741. var Internals;
  22742. (function (Internals) {
  22743. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22744. // All values and structures referenced from:
  22745. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22746. var DDS_MAGIC = 0x20534444;
  22747. 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;
  22748. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22749. 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;
  22750. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22751. function FourCCToInt32(value) {
  22752. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22753. }
  22754. function Int32ToFourCC(value) {
  22755. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22756. }
  22757. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22758. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22759. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22760. var headerLengthInt = 31; // The header length in 32 bit ints
  22761. // Offsets into the header array
  22762. var off_magic = 0;
  22763. var off_size = 1;
  22764. var off_flags = 2;
  22765. var off_height = 3;
  22766. var off_width = 4;
  22767. var off_mipmapCount = 7;
  22768. var off_pfFlags = 20;
  22769. var off_pfFourCC = 21;
  22770. var off_RGBbpp = 22;
  22771. var off_RMask = 23;
  22772. var off_GMask = 24;
  22773. var off_BMask = 25;
  22774. var off_AMask = 26;
  22775. var off_caps1 = 27;
  22776. var off_caps2 = 28;
  22777. ;
  22778. var DDSTools = (function () {
  22779. function DDSTools() {
  22780. }
  22781. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22782. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22783. var mipmapCount = 1;
  22784. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22785. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22786. }
  22787. return {
  22788. width: header[off_width],
  22789. height: header[off_height],
  22790. mipmapCount: mipmapCount,
  22791. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22792. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22793. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22794. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22795. };
  22796. };
  22797. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22798. var byteArray = new Uint8Array(dataLength);
  22799. var srcData = new Uint8Array(arrayBuffer);
  22800. var index = 0;
  22801. for (var y = height - 1; y >= 0; y--) {
  22802. for (var x = 0; x < width; x++) {
  22803. var srcPos = dataOffset + (x + y * width) * 4;
  22804. byteArray[index + 2] = srcData[srcPos];
  22805. byteArray[index + 1] = srcData[srcPos + 1];
  22806. byteArray[index] = srcData[srcPos + 2];
  22807. byteArray[index + 3] = srcData[srcPos + 3];
  22808. index += 4;
  22809. }
  22810. }
  22811. return byteArray;
  22812. };
  22813. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22814. var byteArray = new Uint8Array(dataLength);
  22815. var srcData = new Uint8Array(arrayBuffer);
  22816. var index = 0;
  22817. for (var y = height - 1; y >= 0; y--) {
  22818. for (var x = 0; x < width; x++) {
  22819. var srcPos = dataOffset + (x + y * width) * 3;
  22820. byteArray[index + 2] = srcData[srcPos];
  22821. byteArray[index + 1] = srcData[srcPos + 1];
  22822. byteArray[index] = srcData[srcPos + 2];
  22823. index += 3;
  22824. }
  22825. }
  22826. return byteArray;
  22827. };
  22828. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22829. var byteArray = new Uint8Array(dataLength);
  22830. var srcData = new Uint8Array(arrayBuffer);
  22831. var index = 0;
  22832. for (var y = height - 1; y >= 0; y--) {
  22833. for (var x = 0; x < width; x++) {
  22834. var srcPos = dataOffset + (x + y * width);
  22835. byteArray[index] = srcData[srcPos];
  22836. index++;
  22837. }
  22838. }
  22839. return byteArray;
  22840. };
  22841. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22842. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22843. if (header[off_magic] != DDS_MAGIC) {
  22844. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22845. return;
  22846. }
  22847. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22848. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22849. return;
  22850. }
  22851. if (info.isFourCC) {
  22852. fourCC = header[off_pfFourCC];
  22853. switch (fourCC) {
  22854. case FOURCC_DXT1:
  22855. blockBytes = 8;
  22856. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22857. break;
  22858. case FOURCC_DXT3:
  22859. blockBytes = 16;
  22860. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22861. break;
  22862. case FOURCC_DXT5:
  22863. blockBytes = 16;
  22864. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22865. break;
  22866. default:
  22867. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22868. return;
  22869. }
  22870. }
  22871. mipmapCount = 1;
  22872. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22873. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22874. }
  22875. var bpp = header[off_RGBbpp];
  22876. for (var face = 0; face < faces; face++) {
  22877. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22878. width = header[off_width];
  22879. height = header[off_height];
  22880. dataOffset = header[off_size] + 4;
  22881. for (i = 0; i < mipmapCount; ++i) {
  22882. if (info.isRGB) {
  22883. if (bpp == 24) {
  22884. dataLength = width * height * 3;
  22885. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22886. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22887. }
  22888. else {
  22889. dataLength = width * height * 4;
  22890. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22891. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22892. }
  22893. }
  22894. else if (info.isLuminance) {
  22895. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22896. var unpaddedRowSize = width;
  22897. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22898. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22899. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22900. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22901. }
  22902. else {
  22903. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22904. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22905. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22906. }
  22907. dataOffset += dataLength;
  22908. width *= 0.5;
  22909. height *= 0.5;
  22910. width = Math.max(1.0, width);
  22911. height = Math.max(1.0, height);
  22912. }
  22913. }
  22914. };
  22915. return DDSTools;
  22916. })();
  22917. Internals.DDSTools = DDSTools;
  22918. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22919. })(BABYLON || (BABYLON = {}));
  22920. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22921. (function (BABYLON) {
  22922. var SmartArray = (function () {
  22923. function SmartArray(capacity) {
  22924. this.length = 0;
  22925. this._duplicateId = 0;
  22926. this.data = new Array(capacity);
  22927. this._id = SmartArray._GlobalId++;
  22928. }
  22929. SmartArray.prototype.push = function (value) {
  22930. this.data[this.length++] = value;
  22931. if (this.length > this.data.length) {
  22932. this.data.length *= 2;
  22933. }
  22934. if (!value.__smartArrayFlags) {
  22935. value.__smartArrayFlags = {};
  22936. }
  22937. value.__smartArrayFlags[this._id] = this._duplicateId;
  22938. };
  22939. SmartArray.prototype.pushNoDuplicate = function (value) {
  22940. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22941. return;
  22942. }
  22943. this.push(value);
  22944. };
  22945. SmartArray.prototype.sort = function (compareFn) {
  22946. this.data.sort(compareFn);
  22947. };
  22948. SmartArray.prototype.reset = function () {
  22949. this.length = 0;
  22950. this._duplicateId++;
  22951. };
  22952. SmartArray.prototype.concat = function (array) {
  22953. if (array.length === 0) {
  22954. return;
  22955. }
  22956. if (this.length + array.length > this.data.length) {
  22957. this.data.length = (this.length + array.length) * 2;
  22958. }
  22959. for (var index = 0; index < array.length; index++) {
  22960. this.data[this.length++] = (array.data || array)[index];
  22961. }
  22962. };
  22963. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22964. if (array.length === 0) {
  22965. return;
  22966. }
  22967. if (this.length + array.length > this.data.length) {
  22968. this.data.length = (this.length + array.length) * 2;
  22969. }
  22970. for (var index = 0; index < array.length; index++) {
  22971. var item = (array.data || array)[index];
  22972. this.pushNoDuplicate(item);
  22973. }
  22974. };
  22975. SmartArray.prototype.indexOf = function (value) {
  22976. var position = this.data.indexOf(value);
  22977. if (position >= this.length) {
  22978. return -1;
  22979. }
  22980. return position;
  22981. };
  22982. // Statics
  22983. SmartArray._GlobalId = 0;
  22984. return SmartArray;
  22985. })();
  22986. BABYLON.SmartArray = SmartArray;
  22987. })(BABYLON || (BABYLON = {}));
  22988. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22989. (function (BABYLON) {
  22990. var CannonJSPlugin = (function () {
  22991. function CannonJSPlugin() {
  22992. this._registeredMeshes = [];
  22993. this._physicsMaterials = [];
  22994. this.updateBodyPosition = function (mesh) {
  22995. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22996. var registeredMesh = this._registeredMeshes[index];
  22997. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22998. var body = registeredMesh.body;
  22999. var center = mesh.getBoundingInfo().boundingBox.center;
  23000. body.position.set(center.x, center.z, center.y);
  23001. body.quaternion.x = mesh.rotationQuaternion.x;
  23002. body.quaternion.z = mesh.rotationQuaternion.y;
  23003. body.quaternion.y = mesh.rotationQuaternion.z;
  23004. body.quaternion.w = -mesh.rotationQuaternion.w;
  23005. return;
  23006. }
  23007. }
  23008. };
  23009. }
  23010. CannonJSPlugin.prototype.initialize = function (iterations) {
  23011. if (iterations === void 0) { iterations = 10; }
  23012. this._world = new CANNON.World();
  23013. this._world.broadphase = new CANNON.NaiveBroadphase();
  23014. this._world.solver.iterations = iterations;
  23015. };
  23016. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23017. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23018. };
  23019. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23020. this._world.step(delta);
  23021. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23022. var registeredMesh = this._registeredMeshes[index];
  23023. if (registeredMesh.isChild) {
  23024. continue;
  23025. }
  23026. // Body position
  23027. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23028. var deltaPos = registeredMesh.delta;
  23029. if (deltaPos) {
  23030. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23031. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23032. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23033. }
  23034. else {
  23035. registeredMesh.mesh.position.x = bodyX;
  23036. registeredMesh.mesh.position.y = bodyZ;
  23037. registeredMesh.mesh.position.z = bodyY;
  23038. }
  23039. if (!registeredMesh.mesh.rotationQuaternion) {
  23040. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23041. }
  23042. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23043. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23044. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23045. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23046. }
  23047. };
  23048. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23049. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23050. };
  23051. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23052. this.unregisterMesh(mesh);
  23053. mesh.computeWorldMatrix(true);
  23054. switch (impostor) {
  23055. case BABYLON.PhysicsEngine.SphereImpostor:
  23056. var bbox = mesh.getBoundingInfo().boundingBox;
  23057. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23058. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23059. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23060. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23061. case BABYLON.PhysicsEngine.BoxImpostor:
  23062. bbox = mesh.getBoundingInfo().boundingBox;
  23063. var min = bbox.minimumWorld;
  23064. var max = bbox.maximumWorld;
  23065. var box = max.subtract(min).scale(0.5);
  23066. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23067. case BABYLON.PhysicsEngine.PlaneImpostor:
  23068. return this._createPlane(mesh, options);
  23069. case BABYLON.PhysicsEngine.MeshImpostor:
  23070. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23071. var rawFaces = mesh.getIndices();
  23072. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23073. }
  23074. return null;
  23075. };
  23076. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23077. var shape = new CANNON.Sphere(radius);
  23078. if (!options) {
  23079. return shape;
  23080. }
  23081. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23082. };
  23083. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23084. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23085. if (!options) {
  23086. return shape;
  23087. }
  23088. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23089. };
  23090. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23091. var shape = new CANNON.Plane();
  23092. if (!options) {
  23093. return shape;
  23094. }
  23095. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23096. };
  23097. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23098. var verts = [], faces = [];
  23099. mesh.computeWorldMatrix(true);
  23100. for (var i = 0; i < rawVerts.length; i += 3) {
  23101. var transformed = BABYLON.Vector3.Zero();
  23102. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23103. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23104. }
  23105. for (var j = 0; j < rawFaces.length; j += 3) {
  23106. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23107. }
  23108. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23109. if (!options) {
  23110. return shape;
  23111. }
  23112. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23113. };
  23114. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23115. var index;
  23116. var mat;
  23117. for (index = 0; index < this._physicsMaterials.length; index++) {
  23118. mat = this._physicsMaterials[index];
  23119. if (mat.friction === friction && mat.restitution === restitution) {
  23120. return mat;
  23121. }
  23122. }
  23123. var currentMat = new CANNON.Material();
  23124. currentMat.friction = friction;
  23125. currentMat.restitution = restitution;
  23126. this._physicsMaterials.push(currentMat);
  23127. for (index = 0; index < this._physicsMaterials.length; index++) {
  23128. mat = this._physicsMaterials[index];
  23129. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23130. contactMaterial.contactEquationStiffness = 1e10;
  23131. contactMaterial.contactEquationRegularizationTime = 10;
  23132. this._world.addContactMaterial(contactMaterial);
  23133. }
  23134. return currentMat;
  23135. };
  23136. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23137. var initialRotation = null;
  23138. if (mesh.rotationQuaternion) {
  23139. initialRotation = mesh.rotationQuaternion.clone();
  23140. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23141. }
  23142. // The delta between the mesh position and the mesh bounding box center
  23143. var bbox = mesh.getBoundingInfo().boundingBox;
  23144. var deltaPosition = mesh.position.subtract(bbox.center);
  23145. var material = this._addMaterial(friction, restitution);
  23146. var body = new CANNON.RigidBody(mass, shape, material);
  23147. if (initialRotation) {
  23148. body.quaternion.x = initialRotation.x;
  23149. body.quaternion.z = initialRotation.y;
  23150. body.quaternion.y = initialRotation.z;
  23151. body.quaternion.w = -initialRotation.w;
  23152. }
  23153. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23154. this._world.add(body);
  23155. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23156. return body;
  23157. };
  23158. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23159. var compoundShape = new CANNON.Compound();
  23160. for (var index = 0; index < parts.length; index++) {
  23161. var mesh = parts[index].mesh;
  23162. var shape = this.registerMesh(mesh, parts[index].impostor);
  23163. if (index == 0) {
  23164. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23165. }
  23166. else {
  23167. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23168. }
  23169. }
  23170. var initialMesh = parts[0].mesh;
  23171. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23172. body.parts = parts;
  23173. return body;
  23174. };
  23175. CannonJSPlugin.prototype._unbindBody = function (body) {
  23176. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23177. var registeredMesh = this._registeredMeshes[index];
  23178. if (registeredMesh.body === body) {
  23179. registeredMesh.body = null;
  23180. registeredMesh.delta = 0;
  23181. }
  23182. }
  23183. };
  23184. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23185. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23186. var registeredMesh = this._registeredMeshes[index];
  23187. if (registeredMesh.mesh === mesh) {
  23188. // Remove body
  23189. if (registeredMesh.body) {
  23190. this._world.remove(registeredMesh.body);
  23191. this._unbindBody(registeredMesh.body);
  23192. }
  23193. this._registeredMeshes.splice(index, 1);
  23194. return;
  23195. }
  23196. }
  23197. };
  23198. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23199. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23200. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23201. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23202. var registeredMesh = this._registeredMeshes[index];
  23203. if (registeredMesh.mesh === mesh) {
  23204. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23205. return;
  23206. }
  23207. }
  23208. };
  23209. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23210. var body1 = null, body2 = null;
  23211. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23212. var registeredMesh = this._registeredMeshes[index];
  23213. if (registeredMesh.mesh === mesh1) {
  23214. body1 = registeredMesh.body;
  23215. }
  23216. else if (registeredMesh.mesh === mesh2) {
  23217. body2 = registeredMesh.body;
  23218. }
  23219. }
  23220. if (!body1 || !body2) {
  23221. return false;
  23222. }
  23223. 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));
  23224. this._world.addConstraint(constraint);
  23225. return true;
  23226. };
  23227. CannonJSPlugin.prototype.dispose = function () {
  23228. while (this._registeredMeshes.length) {
  23229. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23230. }
  23231. };
  23232. CannonJSPlugin.prototype.isSupported = function () {
  23233. return window.CANNON !== undefined;
  23234. };
  23235. return CannonJSPlugin;
  23236. })();
  23237. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23238. })(BABYLON || (BABYLON = {}));
  23239. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23240. var BABYLON;
  23241. (function (BABYLON) {
  23242. var Condition = (function () {
  23243. function Condition(actionManager) {
  23244. this._actionManager = actionManager;
  23245. }
  23246. Condition.prototype.isValid = function () {
  23247. return true;
  23248. };
  23249. Condition.prototype._getProperty = function (propertyPath) {
  23250. return this._actionManager._getProperty(propertyPath);
  23251. };
  23252. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23253. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23254. };
  23255. return Condition;
  23256. })();
  23257. BABYLON.Condition = Condition;
  23258. var ValueCondition = (function (_super) {
  23259. __extends(ValueCondition, _super);
  23260. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23261. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23262. _super.call(this, actionManager);
  23263. this.propertyPath = propertyPath;
  23264. this.value = value;
  23265. this.operator = operator;
  23266. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23267. this._property = this._getProperty(this.propertyPath);
  23268. }
  23269. Object.defineProperty(ValueCondition, "IsEqual", {
  23270. get: function () {
  23271. return ValueCondition._IsEqual;
  23272. },
  23273. enumerable: true,
  23274. configurable: true
  23275. });
  23276. Object.defineProperty(ValueCondition, "IsDifferent", {
  23277. get: function () {
  23278. return ValueCondition._IsDifferent;
  23279. },
  23280. enumerable: true,
  23281. configurable: true
  23282. });
  23283. Object.defineProperty(ValueCondition, "IsGreater", {
  23284. get: function () {
  23285. return ValueCondition._IsGreater;
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. Object.defineProperty(ValueCondition, "IsLesser", {
  23291. get: function () {
  23292. return ValueCondition._IsLesser;
  23293. },
  23294. enumerable: true,
  23295. configurable: true
  23296. });
  23297. // Methods
  23298. ValueCondition.prototype.isValid = function () {
  23299. switch (this.operator) {
  23300. case ValueCondition.IsGreater:
  23301. return this._target[this._property] > this.value;
  23302. case ValueCondition.IsLesser:
  23303. return this._target[this._property] < this.value;
  23304. case ValueCondition.IsEqual:
  23305. case ValueCondition.IsDifferent:
  23306. var check;
  23307. if (this.value.equals) {
  23308. check = this.value.equals(this._target[this._property]);
  23309. }
  23310. else {
  23311. check = this.value === this._target[this._property];
  23312. }
  23313. return this.operator === ValueCondition.IsEqual ? check : !check;
  23314. }
  23315. return false;
  23316. };
  23317. // Statics
  23318. ValueCondition._IsEqual = 0;
  23319. ValueCondition._IsDifferent = 1;
  23320. ValueCondition._IsGreater = 2;
  23321. ValueCondition._IsLesser = 3;
  23322. return ValueCondition;
  23323. })(Condition);
  23324. BABYLON.ValueCondition = ValueCondition;
  23325. var PredicateCondition = (function (_super) {
  23326. __extends(PredicateCondition, _super);
  23327. function PredicateCondition(actionManager, predicate) {
  23328. _super.call(this, actionManager);
  23329. this.predicate = predicate;
  23330. }
  23331. PredicateCondition.prototype.isValid = function () {
  23332. return this.predicate();
  23333. };
  23334. return PredicateCondition;
  23335. })(Condition);
  23336. BABYLON.PredicateCondition = PredicateCondition;
  23337. var StateCondition = (function (_super) {
  23338. __extends(StateCondition, _super);
  23339. function StateCondition(actionManager, target, value) {
  23340. _super.call(this, actionManager);
  23341. this.value = value;
  23342. this._target = target;
  23343. }
  23344. // Methods
  23345. StateCondition.prototype.isValid = function () {
  23346. return this._target.state === this.value;
  23347. };
  23348. return StateCondition;
  23349. })(Condition);
  23350. BABYLON.StateCondition = StateCondition;
  23351. })(BABYLON || (BABYLON = {}));
  23352. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23353. (function (BABYLON) {
  23354. var Action = (function () {
  23355. function Action(triggerOptions, condition) {
  23356. this.triggerOptions = triggerOptions;
  23357. if (triggerOptions.parameter) {
  23358. this.trigger = triggerOptions.trigger;
  23359. this._triggerParameter = triggerOptions.parameter;
  23360. }
  23361. else {
  23362. this.trigger = triggerOptions;
  23363. }
  23364. this._nextActiveAction = this;
  23365. this._condition = condition;
  23366. }
  23367. // Methods
  23368. Action.prototype._prepare = function () {
  23369. };
  23370. Action.prototype.getTriggerParameter = function () {
  23371. return this._triggerParameter;
  23372. };
  23373. Action.prototype._executeCurrent = function (evt) {
  23374. if (this._nextActiveAction._condition) {
  23375. var condition = this._nextActiveAction._condition;
  23376. var currentRenderId = this._actionManager.getScene().getRenderId();
  23377. // We cache the current evaluation for the current frame
  23378. if (condition._evaluationId === currentRenderId) {
  23379. if (!condition._currentResult) {
  23380. return;
  23381. }
  23382. }
  23383. else {
  23384. condition._evaluationId = currentRenderId;
  23385. if (!condition.isValid()) {
  23386. condition._currentResult = false;
  23387. return;
  23388. }
  23389. condition._currentResult = true;
  23390. }
  23391. }
  23392. this._nextActiveAction.execute(evt);
  23393. if (this._nextActiveAction._child) {
  23394. if (!this._nextActiveAction._child._actionManager) {
  23395. this._nextActiveAction._child._actionManager = this._actionManager;
  23396. }
  23397. this._nextActiveAction = this._nextActiveAction._child;
  23398. }
  23399. else {
  23400. this._nextActiveAction = this;
  23401. }
  23402. };
  23403. Action.prototype.execute = function (evt) {
  23404. };
  23405. Action.prototype.then = function (action) {
  23406. this._child = action;
  23407. action._actionManager = this._actionManager;
  23408. action._prepare();
  23409. return action;
  23410. };
  23411. Action.prototype._getProperty = function (propertyPath) {
  23412. return this._actionManager._getProperty(propertyPath);
  23413. };
  23414. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23415. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23416. };
  23417. return Action;
  23418. })();
  23419. BABYLON.Action = Action;
  23420. })(BABYLON || (BABYLON = {}));
  23421. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23422. (function (BABYLON) {
  23423. /**
  23424. * ActionEvent is the event beint sent when an action is triggered.
  23425. */
  23426. var ActionEvent = (function () {
  23427. /**
  23428. * @constructor
  23429. * @param source The mesh that triggered the action.
  23430. * @param pointerX the X mouse cursor position at the time of the event
  23431. * @param pointerY the Y mouse cursor position at the time of the event
  23432. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23433. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23434. */
  23435. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23436. this.source = source;
  23437. this.pointerX = pointerX;
  23438. this.pointerY = pointerY;
  23439. this.meshUnderPointer = meshUnderPointer;
  23440. this.sourceEvent = sourceEvent;
  23441. }
  23442. /**
  23443. * Helper function to auto-create an ActionEvent from a source mesh.
  23444. * @param source the source mesh that triggered the event
  23445. * @param evt {Event} The original (browser) event
  23446. */
  23447. ActionEvent.CreateNew = function (source, evt) {
  23448. var scene = source.getScene();
  23449. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23450. };
  23451. /**
  23452. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23453. * @param scene the scene where the event occurred
  23454. * @param evt {Event} The original (browser) event
  23455. */
  23456. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23457. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23458. };
  23459. return ActionEvent;
  23460. })();
  23461. BABYLON.ActionEvent = ActionEvent;
  23462. /**
  23463. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23464. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23465. */
  23466. var ActionManager = (function () {
  23467. function ActionManager(scene) {
  23468. // Members
  23469. this.actions = new Array();
  23470. this._scene = scene;
  23471. scene._actionManagers.push(this);
  23472. }
  23473. Object.defineProperty(ActionManager, "NothingTrigger", {
  23474. get: function () {
  23475. return ActionManager._NothingTrigger;
  23476. },
  23477. enumerable: true,
  23478. configurable: true
  23479. });
  23480. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23481. get: function () {
  23482. return ActionManager._OnPickTrigger;
  23483. },
  23484. enumerable: true,
  23485. configurable: true
  23486. });
  23487. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23488. get: function () {
  23489. return ActionManager._OnLeftPickTrigger;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23495. get: function () {
  23496. return ActionManager._OnRightPickTrigger;
  23497. },
  23498. enumerable: true,
  23499. configurable: true
  23500. });
  23501. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23502. get: function () {
  23503. return ActionManager._OnCenterPickTrigger;
  23504. },
  23505. enumerable: true,
  23506. configurable: true
  23507. });
  23508. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23509. get: function () {
  23510. return ActionManager._OnPointerOverTrigger;
  23511. },
  23512. enumerable: true,
  23513. configurable: true
  23514. });
  23515. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23516. get: function () {
  23517. return ActionManager._OnPointerOutTrigger;
  23518. },
  23519. enumerable: true,
  23520. configurable: true
  23521. });
  23522. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23523. get: function () {
  23524. return ActionManager._OnEveryFrameTrigger;
  23525. },
  23526. enumerable: true,
  23527. configurable: true
  23528. });
  23529. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23530. get: function () {
  23531. return ActionManager._OnIntersectionEnterTrigger;
  23532. },
  23533. enumerable: true,
  23534. configurable: true
  23535. });
  23536. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23537. get: function () {
  23538. return ActionManager._OnIntersectionExitTrigger;
  23539. },
  23540. enumerable: true,
  23541. configurable: true
  23542. });
  23543. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23544. get: function () {
  23545. return ActionManager._OnKeyDownTrigger;
  23546. },
  23547. enumerable: true,
  23548. configurable: true
  23549. });
  23550. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23551. get: function () {
  23552. return ActionManager._OnKeyUpTrigger;
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. // Methods
  23558. ActionManager.prototype.dispose = function () {
  23559. var index = this._scene._actionManagers.indexOf(this);
  23560. if (index > -1) {
  23561. this._scene._actionManagers.splice(index, 1);
  23562. }
  23563. };
  23564. ActionManager.prototype.getScene = function () {
  23565. return this._scene;
  23566. };
  23567. /**
  23568. * Does this action manager handles actions of any of the given triggers
  23569. * @param {number[]} triggers - the triggers to be tested
  23570. * @return {boolean} whether one (or more) of the triggers is handeled
  23571. */
  23572. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23573. for (var index = 0; index < this.actions.length; index++) {
  23574. var action = this.actions[index];
  23575. if (triggers.indexOf(action.trigger) > -1) {
  23576. return true;
  23577. }
  23578. }
  23579. return false;
  23580. };
  23581. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23582. /**
  23583. * Does this action manager has pointer triggers
  23584. * @return {boolean} whether or not it has pointer triggers
  23585. */
  23586. get: function () {
  23587. for (var index = 0; index < this.actions.length; index++) {
  23588. var action = this.actions[index];
  23589. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23590. return true;
  23591. }
  23592. }
  23593. return false;
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23599. /**
  23600. * Does this action manager has pick triggers
  23601. * @return {boolean} whether or not it has pick triggers
  23602. */
  23603. get: function () {
  23604. for (var index = 0; index < this.actions.length; index++) {
  23605. var action = this.actions[index];
  23606. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23607. return true;
  23608. }
  23609. }
  23610. return false;
  23611. },
  23612. enumerable: true,
  23613. configurable: true
  23614. });
  23615. /**
  23616. * Registers an action to this action manager
  23617. * @param {BABYLON.Action} action - the action to be registered
  23618. * @return {BABYLON.Action} the action amended (prepared) after registration
  23619. */
  23620. ActionManager.prototype.registerAction = function (action) {
  23621. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23622. if (this.getScene().actionManager !== this) {
  23623. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23624. return null;
  23625. }
  23626. }
  23627. this.actions.push(action);
  23628. action._actionManager = this;
  23629. action._prepare();
  23630. return action;
  23631. };
  23632. /**
  23633. * Process a specific trigger
  23634. * @param {number} trigger - the trigger to process
  23635. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23636. */
  23637. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23638. for (var index = 0; index < this.actions.length; index++) {
  23639. var action = this.actions[index];
  23640. if (action.trigger === trigger) {
  23641. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23642. var parameter = action.getTriggerParameter();
  23643. if (parameter) {
  23644. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23645. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23646. if (actualkey !== parameter.toLowerCase()) {
  23647. continue;
  23648. }
  23649. }
  23650. }
  23651. action._executeCurrent(evt);
  23652. }
  23653. }
  23654. };
  23655. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23656. var properties = propertyPath.split(".");
  23657. for (var index = 0; index < properties.length - 1; index++) {
  23658. target = target[properties[index]];
  23659. }
  23660. return target;
  23661. };
  23662. ActionManager.prototype._getProperty = function (propertyPath) {
  23663. var properties = propertyPath.split(".");
  23664. return properties[properties.length - 1];
  23665. };
  23666. // Statics
  23667. ActionManager._NothingTrigger = 0;
  23668. ActionManager._OnPickTrigger = 1;
  23669. ActionManager._OnLeftPickTrigger = 2;
  23670. ActionManager._OnRightPickTrigger = 3;
  23671. ActionManager._OnCenterPickTrigger = 4;
  23672. ActionManager._OnPointerOverTrigger = 5;
  23673. ActionManager._OnPointerOutTrigger = 6;
  23674. ActionManager._OnEveryFrameTrigger = 7;
  23675. ActionManager._OnIntersectionEnterTrigger = 8;
  23676. ActionManager._OnIntersectionExitTrigger = 9;
  23677. ActionManager._OnKeyDownTrigger = 10;
  23678. ActionManager._OnKeyUpTrigger = 11;
  23679. return ActionManager;
  23680. })();
  23681. BABYLON.ActionManager = ActionManager;
  23682. })(BABYLON || (BABYLON = {}));
  23683. //# sourceMappingURL=babylon.actionManager.js.map
  23684. var BABYLON;
  23685. (function (BABYLON) {
  23686. var InterpolateValueAction = (function (_super) {
  23687. __extends(InterpolateValueAction, _super);
  23688. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23689. if (duration === void 0) { duration = 1000; }
  23690. _super.call(this, triggerOptions, condition);
  23691. this.propertyPath = propertyPath;
  23692. this.value = value;
  23693. this.duration = duration;
  23694. this.stopOtherAnimations = stopOtherAnimations;
  23695. this._target = target;
  23696. }
  23697. InterpolateValueAction.prototype._prepare = function () {
  23698. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23699. this._property = this._getProperty(this.propertyPath);
  23700. };
  23701. InterpolateValueAction.prototype.execute = function () {
  23702. var scene = this._actionManager.getScene();
  23703. var keys = [
  23704. {
  23705. frame: 0,
  23706. value: this._target[this._property]
  23707. },
  23708. {
  23709. frame: 100,
  23710. value: this.value
  23711. }
  23712. ];
  23713. var dataType;
  23714. if (typeof this.value === "number") {
  23715. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23716. }
  23717. else if (this.value instanceof BABYLON.Color3) {
  23718. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23719. }
  23720. else if (this.value instanceof BABYLON.Vector3) {
  23721. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23722. }
  23723. else if (this.value instanceof BABYLON.Matrix) {
  23724. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23725. }
  23726. else if (this.value instanceof BABYLON.Quaternion) {
  23727. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23728. }
  23729. else {
  23730. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23731. return;
  23732. }
  23733. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23734. animation.setKeys(keys);
  23735. if (this.stopOtherAnimations) {
  23736. scene.stopAnimation(this._target);
  23737. }
  23738. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23739. };
  23740. return InterpolateValueAction;
  23741. })(BABYLON.Action);
  23742. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23743. })(BABYLON || (BABYLON = {}));
  23744. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23745. var BABYLON;
  23746. (function (BABYLON) {
  23747. var SwitchBooleanAction = (function (_super) {
  23748. __extends(SwitchBooleanAction, _super);
  23749. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23750. _super.call(this, triggerOptions, condition);
  23751. this.propertyPath = propertyPath;
  23752. this._target = target;
  23753. }
  23754. SwitchBooleanAction.prototype._prepare = function () {
  23755. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23756. this._property = this._getProperty(this.propertyPath);
  23757. };
  23758. SwitchBooleanAction.prototype.execute = function () {
  23759. this._target[this._property] = !this._target[this._property];
  23760. };
  23761. return SwitchBooleanAction;
  23762. })(BABYLON.Action);
  23763. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23764. var SetStateAction = (function (_super) {
  23765. __extends(SetStateAction, _super);
  23766. function SetStateAction(triggerOptions, target, value, condition) {
  23767. _super.call(this, triggerOptions, condition);
  23768. this.value = value;
  23769. this._target = target;
  23770. }
  23771. SetStateAction.prototype.execute = function () {
  23772. this._target.state = this.value;
  23773. };
  23774. return SetStateAction;
  23775. })(BABYLON.Action);
  23776. BABYLON.SetStateAction = SetStateAction;
  23777. var SetValueAction = (function (_super) {
  23778. __extends(SetValueAction, _super);
  23779. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23780. _super.call(this, triggerOptions, condition);
  23781. this.propertyPath = propertyPath;
  23782. this.value = value;
  23783. this._target = target;
  23784. }
  23785. SetValueAction.prototype._prepare = function () {
  23786. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23787. this._property = this._getProperty(this.propertyPath);
  23788. };
  23789. SetValueAction.prototype.execute = function () {
  23790. this._target[this._property] = this.value;
  23791. };
  23792. return SetValueAction;
  23793. })(BABYLON.Action);
  23794. BABYLON.SetValueAction = SetValueAction;
  23795. var IncrementValueAction = (function (_super) {
  23796. __extends(IncrementValueAction, _super);
  23797. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23798. _super.call(this, triggerOptions, condition);
  23799. this.propertyPath = propertyPath;
  23800. this.value = value;
  23801. this._target = target;
  23802. }
  23803. IncrementValueAction.prototype._prepare = function () {
  23804. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23805. this._property = this._getProperty(this.propertyPath);
  23806. if (typeof this._target[this._property] !== "number") {
  23807. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23808. }
  23809. };
  23810. IncrementValueAction.prototype.execute = function () {
  23811. this._target[this._property] += this.value;
  23812. };
  23813. return IncrementValueAction;
  23814. })(BABYLON.Action);
  23815. BABYLON.IncrementValueAction = IncrementValueAction;
  23816. var PlayAnimationAction = (function (_super) {
  23817. __extends(PlayAnimationAction, _super);
  23818. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23819. _super.call(this, triggerOptions, condition);
  23820. this.from = from;
  23821. this.to = to;
  23822. this.loop = loop;
  23823. this._target = target;
  23824. }
  23825. PlayAnimationAction.prototype._prepare = function () {
  23826. };
  23827. PlayAnimationAction.prototype.execute = function () {
  23828. var scene = this._actionManager.getScene();
  23829. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23830. };
  23831. return PlayAnimationAction;
  23832. })(BABYLON.Action);
  23833. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23834. var StopAnimationAction = (function (_super) {
  23835. __extends(StopAnimationAction, _super);
  23836. function StopAnimationAction(triggerOptions, target, condition) {
  23837. _super.call(this, triggerOptions, condition);
  23838. this._target = target;
  23839. }
  23840. StopAnimationAction.prototype._prepare = function () {
  23841. };
  23842. StopAnimationAction.prototype.execute = function () {
  23843. var scene = this._actionManager.getScene();
  23844. scene.stopAnimation(this._target);
  23845. };
  23846. return StopAnimationAction;
  23847. })(BABYLON.Action);
  23848. BABYLON.StopAnimationAction = StopAnimationAction;
  23849. var DoNothingAction = (function (_super) {
  23850. __extends(DoNothingAction, _super);
  23851. function DoNothingAction(triggerOptions, condition) {
  23852. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23853. _super.call(this, triggerOptions, condition);
  23854. }
  23855. DoNothingAction.prototype.execute = function () {
  23856. };
  23857. return DoNothingAction;
  23858. })(BABYLON.Action);
  23859. BABYLON.DoNothingAction = DoNothingAction;
  23860. var CombineAction = (function (_super) {
  23861. __extends(CombineAction, _super);
  23862. function CombineAction(triggerOptions, children, condition) {
  23863. _super.call(this, triggerOptions, condition);
  23864. this.children = children;
  23865. }
  23866. CombineAction.prototype._prepare = function () {
  23867. for (var index = 0; index < this.children.length; index++) {
  23868. this.children[index]._actionManager = this._actionManager;
  23869. this.children[index]._prepare();
  23870. }
  23871. };
  23872. CombineAction.prototype.execute = function (evt) {
  23873. for (var index = 0; index < this.children.length; index++) {
  23874. this.children[index].execute(evt);
  23875. }
  23876. };
  23877. return CombineAction;
  23878. })(BABYLON.Action);
  23879. BABYLON.CombineAction = CombineAction;
  23880. var ExecuteCodeAction = (function (_super) {
  23881. __extends(ExecuteCodeAction, _super);
  23882. function ExecuteCodeAction(triggerOptions, func, condition) {
  23883. _super.call(this, triggerOptions, condition);
  23884. this.func = func;
  23885. }
  23886. ExecuteCodeAction.prototype.execute = function (evt) {
  23887. this.func(evt);
  23888. };
  23889. return ExecuteCodeAction;
  23890. })(BABYLON.Action);
  23891. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23892. var SetParentAction = (function (_super) {
  23893. __extends(SetParentAction, _super);
  23894. function SetParentAction(triggerOptions, target, parent, condition) {
  23895. _super.call(this, triggerOptions, condition);
  23896. this._target = target;
  23897. this._parent = parent;
  23898. }
  23899. SetParentAction.prototype._prepare = function () {
  23900. };
  23901. SetParentAction.prototype.execute = function () {
  23902. if (this._target.parent === this._parent) {
  23903. return;
  23904. }
  23905. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23906. invertParentWorldMatrix.invert();
  23907. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23908. this._target.parent = this._parent;
  23909. };
  23910. return SetParentAction;
  23911. })(BABYLON.Action);
  23912. BABYLON.SetParentAction = SetParentAction;
  23913. var PlaySoundAction = (function (_super) {
  23914. __extends(PlaySoundAction, _super);
  23915. function PlaySoundAction(triggerOptions, sound, condition) {
  23916. _super.call(this, triggerOptions, condition);
  23917. this._sound = sound;
  23918. }
  23919. PlaySoundAction.prototype._prepare = function () {
  23920. };
  23921. PlaySoundAction.prototype.execute = function () {
  23922. if (this._sound !== undefined)
  23923. this._sound.play();
  23924. };
  23925. return PlaySoundAction;
  23926. })(BABYLON.Action);
  23927. BABYLON.PlaySoundAction = PlaySoundAction;
  23928. var StopSoundAction = (function (_super) {
  23929. __extends(StopSoundAction, _super);
  23930. function StopSoundAction(triggerOptions, sound, condition) {
  23931. _super.call(this, triggerOptions, condition);
  23932. this._sound = sound;
  23933. }
  23934. StopSoundAction.prototype._prepare = function () {
  23935. };
  23936. StopSoundAction.prototype.execute = function () {
  23937. if (this._sound !== undefined)
  23938. this._sound.stop();
  23939. };
  23940. return StopSoundAction;
  23941. })(BABYLON.Action);
  23942. BABYLON.StopSoundAction = StopSoundAction;
  23943. })(BABYLON || (BABYLON = {}));
  23944. //# sourceMappingURL=babylon.directActions.js.map
  23945. var BABYLON;
  23946. (function (BABYLON) {
  23947. var Geometry = (function () {
  23948. function Geometry(id, scene, vertexData, updatable, mesh) {
  23949. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23950. this._totalVertices = 0;
  23951. this._indices = [];
  23952. this.id = id;
  23953. this._engine = scene.getEngine();
  23954. this._meshes = [];
  23955. this._scene = scene;
  23956. // vertexData
  23957. if (vertexData) {
  23958. this.setAllVerticesData(vertexData, updatable);
  23959. }
  23960. else {
  23961. this._totalVertices = 0;
  23962. this._indices = [];
  23963. }
  23964. // applyToMesh
  23965. if (mesh) {
  23966. this.applyToMesh(mesh);
  23967. mesh.computeWorldMatrix(true);
  23968. }
  23969. }
  23970. Geometry.prototype.getScene = function () {
  23971. return this._scene;
  23972. };
  23973. Geometry.prototype.getEngine = function () {
  23974. return this._engine;
  23975. };
  23976. Geometry.prototype.isReady = function () {
  23977. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23978. };
  23979. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23980. vertexData.applyToGeometry(this, updatable);
  23981. };
  23982. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23983. this._vertexBuffers = this._vertexBuffers || {};
  23984. if (this._vertexBuffers[kind]) {
  23985. this._vertexBuffers[kind].dispose();
  23986. }
  23987. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23988. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23989. stride = this._vertexBuffers[kind].getStrideSize();
  23990. this._totalVertices = data.length / stride;
  23991. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23992. var meshes = this._meshes;
  23993. var numOfMeshes = meshes.length;
  23994. for (var index = 0; index < numOfMeshes; index++) {
  23995. var mesh = meshes[index];
  23996. mesh._resetPointsArrayCache();
  23997. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23998. mesh._createGlobalSubMesh();
  23999. mesh.computeWorldMatrix(true);
  24000. }
  24001. }
  24002. };
  24003. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24004. var vertexBuffer = this.getVertexBuffer(kind);
  24005. if (!vertexBuffer) {
  24006. return;
  24007. }
  24008. vertexBuffer.updateDirectly(data, offset);
  24009. };
  24010. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24011. var vertexBuffer = this.getVertexBuffer(kind);
  24012. if (!vertexBuffer) {
  24013. return;
  24014. }
  24015. vertexBuffer.update(data);
  24016. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24017. var extend;
  24018. var stride = vertexBuffer.getStrideSize();
  24019. this._totalVertices = data.length / stride;
  24020. if (updateExtends) {
  24021. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24022. }
  24023. var meshes = this._meshes;
  24024. var numOfMeshes = meshes.length;
  24025. for (var index = 0; index < numOfMeshes; index++) {
  24026. var mesh = meshes[index];
  24027. mesh._resetPointsArrayCache();
  24028. if (updateExtends) {
  24029. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24030. }
  24031. }
  24032. }
  24033. };
  24034. Geometry.prototype.getTotalVertices = function () {
  24035. if (!this.isReady()) {
  24036. return 0;
  24037. }
  24038. return this._totalVertices;
  24039. };
  24040. Geometry.prototype.getVerticesData = function (kind) {
  24041. var vertexBuffer = this.getVertexBuffer(kind);
  24042. if (!vertexBuffer) {
  24043. return null;
  24044. }
  24045. return vertexBuffer.getData();
  24046. };
  24047. Geometry.prototype.getVertexBuffer = function (kind) {
  24048. if (!this.isReady()) {
  24049. return null;
  24050. }
  24051. return this._vertexBuffers[kind];
  24052. };
  24053. Geometry.prototype.getVertexBuffers = function () {
  24054. if (!this.isReady()) {
  24055. return null;
  24056. }
  24057. return this._vertexBuffers;
  24058. };
  24059. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24060. if (!this._vertexBuffers) {
  24061. if (this._delayInfo) {
  24062. return this._delayInfo.indexOf(kind) !== -1;
  24063. }
  24064. return false;
  24065. }
  24066. return this._vertexBuffers[kind] !== undefined;
  24067. };
  24068. Geometry.prototype.getVerticesDataKinds = function () {
  24069. var result = [];
  24070. if (!this._vertexBuffers && this._delayInfo) {
  24071. for (var kind in this._delayInfo) {
  24072. result.push(kind);
  24073. }
  24074. }
  24075. else {
  24076. for (kind in this._vertexBuffers) {
  24077. result.push(kind);
  24078. }
  24079. }
  24080. return result;
  24081. };
  24082. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24083. if (this._indexBuffer) {
  24084. this._engine._releaseBuffer(this._indexBuffer);
  24085. }
  24086. this._indices = indices;
  24087. if (this._meshes.length !== 0 && this._indices) {
  24088. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24089. }
  24090. if (totalVertices !== undefined) {
  24091. this._totalVertices = totalVertices;
  24092. }
  24093. var meshes = this._meshes;
  24094. var numOfMeshes = meshes.length;
  24095. for (var index = 0; index < numOfMeshes; index++) {
  24096. meshes[index]._createGlobalSubMesh();
  24097. }
  24098. };
  24099. Geometry.prototype.getTotalIndices = function () {
  24100. if (!this.isReady()) {
  24101. return 0;
  24102. }
  24103. return this._indices.length;
  24104. };
  24105. Geometry.prototype.getIndices = function () {
  24106. if (!this.isReady()) {
  24107. return null;
  24108. }
  24109. return this._indices;
  24110. };
  24111. Geometry.prototype.getIndexBuffer = function () {
  24112. if (!this.isReady()) {
  24113. return null;
  24114. }
  24115. return this._indexBuffer;
  24116. };
  24117. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24118. var meshes = this._meshes;
  24119. var index = meshes.indexOf(mesh);
  24120. if (index === -1) {
  24121. return;
  24122. }
  24123. for (var kind in this._vertexBuffers) {
  24124. this._vertexBuffers[kind].dispose();
  24125. }
  24126. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24127. this._indexBuffer = null;
  24128. }
  24129. meshes.splice(index, 1);
  24130. mesh._geometry = null;
  24131. if (meshes.length === 0 && shouldDispose) {
  24132. this.dispose();
  24133. }
  24134. };
  24135. Geometry.prototype.applyToMesh = function (mesh) {
  24136. if (mesh._geometry === this) {
  24137. return;
  24138. }
  24139. var previousGeometry = mesh._geometry;
  24140. if (previousGeometry) {
  24141. previousGeometry.releaseForMesh(mesh);
  24142. }
  24143. var meshes = this._meshes;
  24144. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24145. mesh._geometry = this;
  24146. this._scene.pushGeometry(this);
  24147. meshes.push(mesh);
  24148. if (this.isReady()) {
  24149. this._applyToMesh(mesh);
  24150. }
  24151. else {
  24152. mesh._boundingInfo = this._boundingInfo;
  24153. }
  24154. };
  24155. Geometry.prototype._applyToMesh = function (mesh) {
  24156. var numOfMeshes = this._meshes.length;
  24157. for (var kind in this._vertexBuffers) {
  24158. if (numOfMeshes === 1) {
  24159. this._vertexBuffers[kind].create();
  24160. }
  24161. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24162. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24163. mesh._resetPointsArrayCache();
  24164. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24165. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24166. mesh._createGlobalSubMesh();
  24167. //bounding info was just created again, world matrix should be applied again.
  24168. mesh._updateBoundingInfo();
  24169. }
  24170. }
  24171. // indexBuffer
  24172. if (numOfMeshes === 1 && this._indices) {
  24173. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24174. }
  24175. if (this._indexBuffer) {
  24176. this._indexBuffer.references = numOfMeshes;
  24177. }
  24178. };
  24179. Geometry.prototype.load = function (scene, onLoaded) {
  24180. var _this = this;
  24181. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24182. return;
  24183. }
  24184. if (this.isReady()) {
  24185. if (onLoaded) {
  24186. onLoaded();
  24187. }
  24188. return;
  24189. }
  24190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24191. scene._addPendingData(this);
  24192. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24193. _this._delayLoadingFunction(JSON.parse(data), _this);
  24194. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24195. _this._delayInfo = [];
  24196. scene._removePendingData(_this);
  24197. var meshes = _this._meshes;
  24198. var numOfMeshes = meshes.length;
  24199. for (var index = 0; index < numOfMeshes; index++) {
  24200. _this._applyToMesh(meshes[index]);
  24201. }
  24202. if (onLoaded) {
  24203. onLoaded();
  24204. }
  24205. }, function () {
  24206. }, scene.database);
  24207. };
  24208. Geometry.prototype.dispose = function () {
  24209. var meshes = this._meshes;
  24210. var numOfMeshes = meshes.length;
  24211. var index;
  24212. for (index = 0; index < numOfMeshes; index++) {
  24213. this.releaseForMesh(meshes[index]);
  24214. }
  24215. this._meshes = [];
  24216. for (var kind in this._vertexBuffers) {
  24217. this._vertexBuffers[kind].dispose();
  24218. }
  24219. this._vertexBuffers = [];
  24220. this._totalVertices = 0;
  24221. if (this._indexBuffer) {
  24222. this._engine._releaseBuffer(this._indexBuffer);
  24223. }
  24224. this._indexBuffer = null;
  24225. this._indices = [];
  24226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24227. this.delayLoadingFile = null;
  24228. this._delayLoadingFunction = null;
  24229. this._delayInfo = [];
  24230. this._boundingInfo = null; // todo: .dispose()
  24231. var geometries = this._scene.getGeometries();
  24232. index = geometries.indexOf(this);
  24233. if (index > -1) {
  24234. geometries.splice(index, 1);
  24235. }
  24236. };
  24237. Geometry.prototype.copy = function (id) {
  24238. var vertexData = new BABYLON.VertexData();
  24239. vertexData.indices = [];
  24240. var indices = this.getIndices();
  24241. for (var index = 0; index < indices.length; index++) {
  24242. vertexData.indices.push(indices[index]);
  24243. }
  24244. var updatable = false;
  24245. var stopChecking = false;
  24246. for (var kind in this._vertexBuffers) {
  24247. vertexData.set(this.getVerticesData(kind), kind);
  24248. if (!stopChecking) {
  24249. updatable = this.getVertexBuffer(kind).isUpdatable();
  24250. stopChecking = !updatable;
  24251. }
  24252. }
  24253. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24254. geometry.delayLoadState = this.delayLoadState;
  24255. geometry.delayLoadingFile = this.delayLoadingFile;
  24256. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24257. for (kind in this._delayInfo) {
  24258. geometry._delayInfo = geometry._delayInfo || [];
  24259. geometry._delayInfo.push(kind);
  24260. }
  24261. // Bounding info
  24262. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24263. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24264. return geometry;
  24265. };
  24266. // Statics
  24267. Geometry.ExtractFromMesh = function (mesh, id) {
  24268. var geometry = mesh._geometry;
  24269. if (!geometry) {
  24270. return null;
  24271. }
  24272. return geometry.copy(id);
  24273. };
  24274. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24275. // be aware Math.random() could cause collisions
  24276. Geometry.RandomId = function () {
  24277. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24278. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24279. return v.toString(16);
  24280. });
  24281. };
  24282. return Geometry;
  24283. })();
  24284. BABYLON.Geometry = Geometry;
  24285. /////// Primitives //////////////////////////////////////////////
  24286. var Geometry;
  24287. (function (Geometry) {
  24288. var Primitives;
  24289. (function (Primitives) {
  24290. /// Abstract class
  24291. var _Primitive = (function (_super) {
  24292. __extends(_Primitive, _super);
  24293. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24294. this._beingRegenerated = true;
  24295. this._canBeRegenerated = canBeRegenerated;
  24296. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24297. this._beingRegenerated = false;
  24298. }
  24299. _Primitive.prototype.canBeRegenerated = function () {
  24300. return this._canBeRegenerated;
  24301. };
  24302. _Primitive.prototype.regenerate = function () {
  24303. if (!this._canBeRegenerated) {
  24304. return;
  24305. }
  24306. this._beingRegenerated = true;
  24307. this.setAllVerticesData(this._regenerateVertexData(), false);
  24308. this._beingRegenerated = false;
  24309. };
  24310. _Primitive.prototype.asNewGeometry = function (id) {
  24311. return _super.prototype.copy.call(this, id);
  24312. };
  24313. // overrides
  24314. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24315. if (!this._beingRegenerated) {
  24316. return;
  24317. }
  24318. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24319. };
  24320. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24321. if (!this._beingRegenerated) {
  24322. return;
  24323. }
  24324. _super.prototype.setVerticesData.call(this, kind, data, false);
  24325. };
  24326. // to override
  24327. // protected
  24328. _Primitive.prototype._regenerateVertexData = function () {
  24329. throw new Error("Abstract method");
  24330. };
  24331. _Primitive.prototype.copy = function (id) {
  24332. throw new Error("Must be overriden in sub-classes.");
  24333. };
  24334. return _Primitive;
  24335. })(Geometry);
  24336. Primitives._Primitive = _Primitive;
  24337. var Box = (function (_super) {
  24338. __extends(Box, _super);
  24339. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24341. this.size = size;
  24342. this.side = side;
  24343. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24344. }
  24345. Box.prototype._regenerateVertexData = function () {
  24346. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24347. };
  24348. Box.prototype.copy = function (id) {
  24349. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24350. };
  24351. return Box;
  24352. })(_Primitive);
  24353. Primitives.Box = Box;
  24354. var Sphere = (function (_super) {
  24355. __extends(Sphere, _super);
  24356. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24357. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24358. this.segments = segments;
  24359. this.diameter = diameter;
  24360. this.side = side;
  24361. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24362. }
  24363. Sphere.prototype._regenerateVertexData = function () {
  24364. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24365. };
  24366. Sphere.prototype.copy = function (id) {
  24367. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24368. };
  24369. return Sphere;
  24370. })(_Primitive);
  24371. Primitives.Sphere = Sphere;
  24372. var Cylinder = (function (_super) {
  24373. __extends(Cylinder, _super);
  24374. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24375. if (subdivisions === void 0) { subdivisions = 1; }
  24376. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24377. this.height = height;
  24378. this.diameterTop = diameterTop;
  24379. this.diameterBottom = diameterBottom;
  24380. this.tessellation = tessellation;
  24381. this.subdivisions = subdivisions;
  24382. this.side = side;
  24383. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24384. }
  24385. Cylinder.prototype._regenerateVertexData = function () {
  24386. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24387. };
  24388. Cylinder.prototype.copy = function (id) {
  24389. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24390. };
  24391. return Cylinder;
  24392. })(_Primitive);
  24393. Primitives.Cylinder = Cylinder;
  24394. var Torus = (function (_super) {
  24395. __extends(Torus, _super);
  24396. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24397. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24398. this.diameter = diameter;
  24399. this.thickness = thickness;
  24400. this.tessellation = tessellation;
  24401. this.side = side;
  24402. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24403. }
  24404. Torus.prototype._regenerateVertexData = function () {
  24405. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24406. };
  24407. Torus.prototype.copy = function (id) {
  24408. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24409. };
  24410. return Torus;
  24411. })(_Primitive);
  24412. Primitives.Torus = Torus;
  24413. var Ground = (function (_super) {
  24414. __extends(Ground, _super);
  24415. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24416. this.width = width;
  24417. this.height = height;
  24418. this.subdivisions = subdivisions;
  24419. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24420. }
  24421. Ground.prototype._regenerateVertexData = function () {
  24422. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24423. };
  24424. Ground.prototype.copy = function (id) {
  24425. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24426. };
  24427. return Ground;
  24428. })(_Primitive);
  24429. Primitives.Ground = Ground;
  24430. var TiledGround = (function (_super) {
  24431. __extends(TiledGround, _super);
  24432. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24433. this.xmin = xmin;
  24434. this.zmin = zmin;
  24435. this.xmax = xmax;
  24436. this.zmax = zmax;
  24437. this.subdivisions = subdivisions;
  24438. this.precision = precision;
  24439. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24440. }
  24441. TiledGround.prototype._regenerateVertexData = function () {
  24442. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24443. };
  24444. TiledGround.prototype.copy = function (id) {
  24445. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24446. };
  24447. return TiledGround;
  24448. })(_Primitive);
  24449. Primitives.TiledGround = TiledGround;
  24450. var Plane = (function (_super) {
  24451. __extends(Plane, _super);
  24452. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24454. this.size = size;
  24455. this.side = side;
  24456. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24457. }
  24458. Plane.prototype._regenerateVertexData = function () {
  24459. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24460. };
  24461. Plane.prototype.copy = function (id) {
  24462. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24463. };
  24464. return Plane;
  24465. })(_Primitive);
  24466. Primitives.Plane = Plane;
  24467. var TorusKnot = (function (_super) {
  24468. __extends(TorusKnot, _super);
  24469. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  24470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24471. this.radius = radius;
  24472. this.tube = tube;
  24473. this.radialSegments = radialSegments;
  24474. this.tubularSegments = tubularSegments;
  24475. this.p = p;
  24476. this.q = q;
  24477. this.side = side;
  24478. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24479. }
  24480. TorusKnot.prototype._regenerateVertexData = function () {
  24481. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  24482. };
  24483. TorusKnot.prototype.copy = function (id) {
  24484. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  24485. };
  24486. return TorusKnot;
  24487. })(_Primitive);
  24488. Primitives.TorusKnot = TorusKnot;
  24489. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24490. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24491. })(BABYLON || (BABYLON = {}));
  24492. //# sourceMappingURL=babylon.geometry.js.map
  24493. var BABYLON;
  24494. (function (BABYLON) {
  24495. var Gamepads = (function () {
  24496. function Gamepads(ongamedpadconnected) {
  24497. var _this = this;
  24498. this.babylonGamepads = [];
  24499. this.oneGamepadConnected = false;
  24500. this.isMonitoring = false;
  24501. this.gamepadEventSupported = 'GamepadEvent' in window;
  24502. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24503. 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=";
  24504. this._callbackGamepadConnected = ongamedpadconnected;
  24505. if (this.gamepadSupportAvailable) {
  24506. // Checking if the gamepad connected event is supported (like in Firefox)
  24507. if (this.gamepadEventSupported) {
  24508. window.addEventListener('gamepadconnected', function (evt) {
  24509. _this._onGamepadConnected(evt);
  24510. }, false);
  24511. window.addEventListener('gamepaddisconnected', function (evt) {
  24512. _this._onGamepadDisconnected(evt);
  24513. }, false);
  24514. }
  24515. else {
  24516. this._startMonitoringGamepads();
  24517. }
  24518. if (!this.oneGamepadConnected) {
  24519. this._insertGamepadDOMInstructions();
  24520. }
  24521. }
  24522. else {
  24523. this._insertGamepadDOMNotSupported();
  24524. }
  24525. }
  24526. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24527. Gamepads.gamepadDOMInfo = document.createElement("div");
  24528. var buttonAImage = document.createElement("img");
  24529. buttonAImage.src = this.buttonADataURL;
  24530. var spanMessage = document.createElement("span");
  24531. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24532. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24533. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24534. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24535. Gamepads.gamepadDOMInfo.style.width = "100%";
  24536. Gamepads.gamepadDOMInfo.style.height = "48px";
  24537. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24538. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24539. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24540. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24541. buttonAImage.style.position = "relative";
  24542. buttonAImage.style.bottom = "8px";
  24543. spanMessage.style.position = "relative";
  24544. spanMessage.style.fontSize = "32px";
  24545. spanMessage.style.bottom = "32px";
  24546. spanMessage.style.color = "green";
  24547. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24548. };
  24549. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24550. Gamepads.gamepadDOMInfo = document.createElement("div");
  24551. var spanMessage = document.createElement("span");
  24552. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24553. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24554. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24555. Gamepads.gamepadDOMInfo.style.width = "100%";
  24556. Gamepads.gamepadDOMInfo.style.height = "40px";
  24557. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24558. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24559. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24560. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24561. spanMessage.style.position = "relative";
  24562. spanMessage.style.fontSize = "32px";
  24563. spanMessage.style.color = "red";
  24564. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24565. };
  24566. Gamepads.prototype.dispose = function () {
  24567. if (Gamepads.gamepadDOMInfo) {
  24568. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24569. }
  24570. };
  24571. Gamepads.prototype._onGamepadConnected = function (evt) {
  24572. var newGamepad = this._addNewGamepad(evt.gamepad);
  24573. if (this._callbackGamepadConnected)
  24574. this._callbackGamepadConnected(newGamepad);
  24575. this._startMonitoringGamepads();
  24576. };
  24577. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24578. if (!this.oneGamepadConnected) {
  24579. this.oneGamepadConnected = true;
  24580. if (Gamepads.gamepadDOMInfo) {
  24581. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24582. Gamepads.gamepadDOMInfo = null;
  24583. }
  24584. }
  24585. var newGamepad;
  24586. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24587. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24588. }
  24589. else {
  24590. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24591. }
  24592. this.babylonGamepads.push(newGamepad);
  24593. return newGamepad;
  24594. };
  24595. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24596. for (var i in this.babylonGamepads) {
  24597. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24598. this.babylonGamepads.splice(i, 1);
  24599. break;
  24600. }
  24601. }
  24602. // If no gamepads are left, stop the polling loop.
  24603. if (this.babylonGamepads.length == 0) {
  24604. this._stopMonitoringGamepads();
  24605. }
  24606. };
  24607. Gamepads.prototype._startMonitoringGamepads = function () {
  24608. if (!this.isMonitoring) {
  24609. this.isMonitoring = true;
  24610. this._checkGamepadsStatus();
  24611. }
  24612. };
  24613. Gamepads.prototype._stopMonitoringGamepads = function () {
  24614. this.isMonitoring = false;
  24615. };
  24616. Gamepads.prototype._checkGamepadsStatus = function () {
  24617. var _this = this;
  24618. // updating gamepad objects
  24619. this._updateGamepadObjects();
  24620. for (var i in this.babylonGamepads) {
  24621. this.babylonGamepads[i].update();
  24622. }
  24623. if (this.isMonitoring) {
  24624. if (window.requestAnimationFrame) {
  24625. window.requestAnimationFrame(function () {
  24626. _this._checkGamepadsStatus();
  24627. });
  24628. }
  24629. else if (window.mozRequestAnimationFrame) {
  24630. window.mozRequestAnimationFrame(function () {
  24631. _this._checkGamepadsStatus();
  24632. });
  24633. }
  24634. else if (window.webkitRequestAnimationFrame) {
  24635. window.webkitRequestAnimationFrame(function () {
  24636. _this._checkGamepadsStatus();
  24637. });
  24638. }
  24639. }
  24640. };
  24641. // This function is called only on Chrome, which does not yet support
  24642. // connection/disconnection events, but requires you to monitor
  24643. // an array for changes.
  24644. Gamepads.prototype._updateGamepadObjects = function () {
  24645. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24646. for (var i = 0; i < gamepads.length; i++) {
  24647. if (gamepads[i]) {
  24648. if (!(gamepads[i].index in this.babylonGamepads)) {
  24649. var newGamepad = this._addNewGamepad(gamepads[i]);
  24650. if (this._callbackGamepadConnected) {
  24651. this._callbackGamepadConnected(newGamepad);
  24652. }
  24653. }
  24654. else {
  24655. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24656. }
  24657. }
  24658. }
  24659. };
  24660. return Gamepads;
  24661. })();
  24662. BABYLON.Gamepads = Gamepads;
  24663. var StickValues = (function () {
  24664. function StickValues(x, y) {
  24665. this.x = x;
  24666. this.y = y;
  24667. }
  24668. return StickValues;
  24669. })();
  24670. BABYLON.StickValues = StickValues;
  24671. var Gamepad = (function () {
  24672. function Gamepad(id, index, browserGamepad) {
  24673. this.id = id;
  24674. this.index = index;
  24675. this.browserGamepad = browserGamepad;
  24676. if (this.browserGamepad.axes.length >= 2) {
  24677. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24678. }
  24679. if (this.browserGamepad.axes.length >= 4) {
  24680. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24681. }
  24682. }
  24683. Gamepad.prototype.onleftstickchanged = function (callback) {
  24684. this._onleftstickchanged = callback;
  24685. };
  24686. Gamepad.prototype.onrightstickchanged = function (callback) {
  24687. this._onrightstickchanged = callback;
  24688. };
  24689. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24690. get: function () {
  24691. return this._leftStick;
  24692. },
  24693. set: function (newValues) {
  24694. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24695. this._onleftstickchanged(newValues);
  24696. }
  24697. this._leftStick = newValues;
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24703. get: function () {
  24704. return this._rightStick;
  24705. },
  24706. set: function (newValues) {
  24707. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24708. this._onrightstickchanged(newValues);
  24709. }
  24710. this._rightStick = newValues;
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. Gamepad.prototype.update = function () {
  24716. if (this._leftStick) {
  24717. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24718. }
  24719. if (this._rightStick) {
  24720. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24721. }
  24722. };
  24723. return Gamepad;
  24724. })();
  24725. BABYLON.Gamepad = Gamepad;
  24726. var GenericPad = (function (_super) {
  24727. __extends(GenericPad, _super);
  24728. function GenericPad(id, index, gamepad) {
  24729. _super.call(this, id, index, gamepad);
  24730. this.id = id;
  24731. this.index = index;
  24732. this.gamepad = gamepad;
  24733. this._buttons = new Array(gamepad.buttons.length);
  24734. }
  24735. GenericPad.prototype.onbuttondown = function (callback) {
  24736. this._onbuttondown = callback;
  24737. };
  24738. GenericPad.prototype.onbuttonup = function (callback) {
  24739. this._onbuttonup = callback;
  24740. };
  24741. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24742. if (newValue !== currentValue) {
  24743. if (this._onbuttondown && newValue === 1) {
  24744. this._onbuttondown(buttonIndex);
  24745. }
  24746. if (this._onbuttonup && newValue === 0) {
  24747. this._onbuttonup(buttonIndex);
  24748. }
  24749. }
  24750. return newValue;
  24751. };
  24752. GenericPad.prototype.update = function () {
  24753. _super.prototype.update.call(this);
  24754. for (var index = 0; index < this._buttons.length; index++) {
  24755. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24756. }
  24757. };
  24758. return GenericPad;
  24759. })(Gamepad);
  24760. BABYLON.GenericPad = GenericPad;
  24761. (function (Xbox360Button) {
  24762. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24763. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24764. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24765. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24766. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24767. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24768. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24769. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24770. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24771. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24772. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24773. var Xbox360Button = BABYLON.Xbox360Button;
  24774. (function (Xbox360Dpad) {
  24775. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24776. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24777. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24778. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24779. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24780. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24781. var Xbox360Pad = (function (_super) {
  24782. __extends(Xbox360Pad, _super);
  24783. function Xbox360Pad() {
  24784. _super.apply(this, arguments);
  24785. this._leftTrigger = 0;
  24786. this._rightTrigger = 0;
  24787. this._buttonA = 0;
  24788. this._buttonB = 0;
  24789. this._buttonX = 0;
  24790. this._buttonY = 0;
  24791. this._buttonBack = 0;
  24792. this._buttonStart = 0;
  24793. this._buttonLB = 0;
  24794. this._buttonRB = 0;
  24795. this._buttonLeftStick = 0;
  24796. this._buttonRightStick = 0;
  24797. this._dPadUp = 0;
  24798. this._dPadDown = 0;
  24799. this._dPadLeft = 0;
  24800. this._dPadRight = 0;
  24801. }
  24802. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24803. this._onlefttriggerchanged = callback;
  24804. };
  24805. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24806. this._onrighttriggerchanged = callback;
  24807. };
  24808. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24809. get: function () {
  24810. return this._leftTrigger;
  24811. },
  24812. set: function (newValue) {
  24813. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24814. this._onlefttriggerchanged(newValue);
  24815. }
  24816. this._leftTrigger = newValue;
  24817. },
  24818. enumerable: true,
  24819. configurable: true
  24820. });
  24821. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24822. get: function () {
  24823. return this._rightTrigger;
  24824. },
  24825. set: function (newValue) {
  24826. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24827. this._onrighttriggerchanged(newValue);
  24828. }
  24829. this._rightTrigger = newValue;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24835. this._onbuttondown = callback;
  24836. };
  24837. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24838. this._onbuttonup = callback;
  24839. };
  24840. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24841. this._ondpaddown = callback;
  24842. };
  24843. Xbox360Pad.prototype.ondpadup = function (callback) {
  24844. this._ondpadup = callback;
  24845. };
  24846. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24847. if (newValue !== currentValue) {
  24848. if (this._onbuttondown && newValue === 1) {
  24849. this._onbuttondown(buttonType);
  24850. }
  24851. if (this._onbuttonup && newValue === 0) {
  24852. this._onbuttonup(buttonType);
  24853. }
  24854. }
  24855. return newValue;
  24856. };
  24857. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24858. if (newValue !== currentValue) {
  24859. if (this._ondpaddown && newValue === 1) {
  24860. this._ondpaddown(buttonType);
  24861. }
  24862. if (this._ondpadup && newValue === 0) {
  24863. this._ondpadup(buttonType);
  24864. }
  24865. }
  24866. return newValue;
  24867. };
  24868. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24869. get: function () {
  24870. return this._buttonA;
  24871. },
  24872. set: function (value) {
  24873. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24879. get: function () {
  24880. return this._buttonB;
  24881. },
  24882. set: function (value) {
  24883. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24889. get: function () {
  24890. return this._buttonX;
  24891. },
  24892. set: function (value) {
  24893. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24899. get: function () {
  24900. return this._buttonY;
  24901. },
  24902. set: function (value) {
  24903. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24904. },
  24905. enumerable: true,
  24906. configurable: true
  24907. });
  24908. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24909. get: function () {
  24910. return this._buttonStart;
  24911. },
  24912. set: function (value) {
  24913. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24919. get: function () {
  24920. return this._buttonBack;
  24921. },
  24922. set: function (value) {
  24923. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24929. get: function () {
  24930. return this._buttonLB;
  24931. },
  24932. set: function (value) {
  24933. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24934. },
  24935. enumerable: true,
  24936. configurable: true
  24937. });
  24938. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24939. get: function () {
  24940. return this._buttonRB;
  24941. },
  24942. set: function (value) {
  24943. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24949. get: function () {
  24950. return this._buttonLeftStick;
  24951. },
  24952. set: function (value) {
  24953. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24959. get: function () {
  24960. return this._buttonRightStick;
  24961. },
  24962. set: function (value) {
  24963. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24969. get: function () {
  24970. return this._dPadUp;
  24971. },
  24972. set: function (value) {
  24973. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24979. get: function () {
  24980. return this._dPadDown;
  24981. },
  24982. set: function (value) {
  24983. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24989. get: function () {
  24990. return this._dPadLeft;
  24991. },
  24992. set: function (value) {
  24993. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24999. get: function () {
  25000. return this._dPadRight;
  25001. },
  25002. set: function (value) {
  25003. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. Xbox360Pad.prototype.update = function () {
  25009. _super.prototype.update.call(this);
  25010. this.buttonA = this.browserGamepad.buttons[0].value;
  25011. this.buttonB = this.browserGamepad.buttons[1].value;
  25012. this.buttonX = this.browserGamepad.buttons[2].value;
  25013. this.buttonY = this.browserGamepad.buttons[3].value;
  25014. this.buttonLB = this.browserGamepad.buttons[4].value;
  25015. this.buttonRB = this.browserGamepad.buttons[5].value;
  25016. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25017. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25018. this.buttonBack = this.browserGamepad.buttons[8].value;
  25019. this.buttonStart = this.browserGamepad.buttons[9].value;
  25020. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25021. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25022. this.dPadUp = this.browserGamepad.buttons[12].value;
  25023. this.dPadDown = this.browserGamepad.buttons[13].value;
  25024. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25025. this.dPadRight = this.browserGamepad.buttons[15].value;
  25026. };
  25027. return Xbox360Pad;
  25028. })(Gamepad);
  25029. BABYLON.Xbox360Pad = Xbox360Pad;
  25030. })(BABYLON || (BABYLON = {}));
  25031. //# sourceMappingURL=babylon.gamepads.js.map
  25032. var BABYLON;
  25033. (function (BABYLON) {
  25034. // We're mainly based on the logic defined into the FreeCamera code
  25035. var GamepadCamera = (function (_super) {
  25036. __extends(GamepadCamera, _super);
  25037. function GamepadCamera(name, position, scene) {
  25038. var _this = this;
  25039. _super.call(this, name, position, scene);
  25040. this.angularSensibility = 200;
  25041. this.moveSensibility = 75;
  25042. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25043. _this._onNewGameConnected(gamepad);
  25044. });
  25045. }
  25046. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25047. // Only the first gamepad can control the camera
  25048. if (gamepad.index === 0) {
  25049. this._gamepad = gamepad;
  25050. }
  25051. };
  25052. GamepadCamera.prototype._checkInputs = function () {
  25053. if (!this._gamepad) {
  25054. return;
  25055. }
  25056. var LSValues = this._gamepad.leftStick;
  25057. var normalizedLX = LSValues.x / this.moveSensibility;
  25058. var normalizedLY = LSValues.y / this.moveSensibility;
  25059. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25060. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25061. var RSValues = this._gamepad.rightStick;
  25062. var normalizedRX = RSValues.x / this.angularSensibility;
  25063. var normalizedRY = RSValues.y / this.angularSensibility;
  25064. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25065. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25066. ;
  25067. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25068. var speed = this._computeLocalCameraSpeed() * 50.0;
  25069. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25070. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25071. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25072. };
  25073. GamepadCamera.prototype.dispose = function () {
  25074. this._gamepads.dispose();
  25075. _super.prototype.dispose.call(this);
  25076. };
  25077. return GamepadCamera;
  25078. })(BABYLON.FreeCamera);
  25079. BABYLON.GamepadCamera = GamepadCamera;
  25080. })(BABYLON || (BABYLON = {}));
  25081. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25082. var BABYLON;
  25083. (function (BABYLON) {
  25084. var LinesMesh = (function (_super) {
  25085. __extends(LinesMesh, _super);
  25086. function LinesMesh(name, scene, updatable) {
  25087. if (updatable === void 0) { updatable = false; }
  25088. _super.call(this, name, scene);
  25089. this.color = new BABYLON.Color3(1, 1, 1);
  25090. this.alpha = 1;
  25091. this._indices = new Array();
  25092. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25093. attributes: ["position"],
  25094. uniforms: ["worldViewProjection", "color"],
  25095. needAlphaBlending: true
  25096. });
  25097. }
  25098. Object.defineProperty(LinesMesh.prototype, "material", {
  25099. get: function () {
  25100. return this._colorShader;
  25101. },
  25102. enumerable: true,
  25103. configurable: true
  25104. });
  25105. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25106. get: function () {
  25107. return false;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25113. get: function () {
  25114. return false;
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25120. var engine = this.getScene().getEngine();
  25121. var indexToBind = this._geometry.getIndexBuffer();
  25122. // VBOs
  25123. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25124. // Color
  25125. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25126. };
  25127. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25128. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25129. return;
  25130. }
  25131. var engine = this.getScene().getEngine();
  25132. // Draw order
  25133. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25134. };
  25135. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25136. return null;
  25137. };
  25138. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25139. this._colorShader.dispose();
  25140. _super.prototype.dispose.call(this, doNotRecurse);
  25141. };
  25142. return LinesMesh;
  25143. })(BABYLON.Mesh);
  25144. BABYLON.LinesMesh = LinesMesh;
  25145. })(BABYLON || (BABYLON = {}));
  25146. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25147. (function (BABYLON) {
  25148. var OutlineRenderer = (function () {
  25149. function OutlineRenderer(scene) {
  25150. this._scene = scene;
  25151. }
  25152. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25153. var _this = this;
  25154. if (useOverlay === void 0) { useOverlay = false; }
  25155. var scene = this._scene;
  25156. var engine = this._scene.getEngine();
  25157. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25158. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25159. return;
  25160. }
  25161. var mesh = subMesh.getRenderingMesh();
  25162. var material = subMesh.getMaterial();
  25163. engine.enableEffect(this._effect);
  25164. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25165. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25166. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25167. // Bones
  25168. if (mesh.useBones) {
  25169. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25170. }
  25171. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25172. // Alpha test
  25173. if (material && material.needAlphaTesting()) {
  25174. var alphaTexture = material.getAlphaTestTexture();
  25175. this._effect.setTexture("diffuseSampler", alphaTexture);
  25176. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25177. }
  25178. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25179. _this._effect.setMatrix("world", world);
  25180. });
  25181. };
  25182. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25183. var defines = [];
  25184. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25185. var mesh = subMesh.getMesh();
  25186. var material = subMesh.getMaterial();
  25187. // Alpha test
  25188. if (material && material.needAlphaTesting()) {
  25189. defines.push("#define ALPHATEST");
  25190. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25191. attribs.push(BABYLON.VertexBuffer.UVKind);
  25192. defines.push("#define UV1");
  25193. }
  25194. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25195. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25196. defines.push("#define UV2");
  25197. }
  25198. }
  25199. // Bones
  25200. if (mesh.useBones) {
  25201. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25202. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25203. defines.push("#define BONES");
  25204. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25205. }
  25206. // Instances
  25207. if (useInstances) {
  25208. defines.push("#define INSTANCES");
  25209. attribs.push("world0");
  25210. attribs.push("world1");
  25211. attribs.push("world2");
  25212. attribs.push("world3");
  25213. }
  25214. // Get correct effect
  25215. var join = defines.join("\n");
  25216. if (this._cachedDefines !== join) {
  25217. this._cachedDefines = join;
  25218. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25219. }
  25220. return this._effect.isReady();
  25221. };
  25222. return OutlineRenderer;
  25223. })();
  25224. BABYLON.OutlineRenderer = OutlineRenderer;
  25225. })(BABYLON || (BABYLON = {}));
  25226. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25227. (function (BABYLON) {
  25228. var MeshAssetTask = (function () {
  25229. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25230. this.name = name;
  25231. this.meshesNames = meshesNames;
  25232. this.rootUrl = rootUrl;
  25233. this.sceneFilename = sceneFilename;
  25234. this.isCompleted = false;
  25235. }
  25236. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25237. var _this = this;
  25238. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25239. _this.loadedMeshes = meshes;
  25240. _this.loadedParticleSystems = particleSystems;
  25241. _this.loadedSkeletons = skeletons;
  25242. _this.isCompleted = true;
  25243. if (_this.onSuccess) {
  25244. _this.onSuccess(_this);
  25245. }
  25246. onSuccess();
  25247. }, null, function () {
  25248. if (_this.onError) {
  25249. _this.onError(_this);
  25250. }
  25251. onError();
  25252. });
  25253. };
  25254. return MeshAssetTask;
  25255. })();
  25256. BABYLON.MeshAssetTask = MeshAssetTask;
  25257. var TextFileAssetTask = (function () {
  25258. function TextFileAssetTask(name, url) {
  25259. this.name = name;
  25260. this.url = url;
  25261. this.isCompleted = false;
  25262. }
  25263. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25264. var _this = this;
  25265. BABYLON.Tools.LoadFile(this.url, function (data) {
  25266. _this.text = data;
  25267. _this.isCompleted = true;
  25268. if (_this.onSuccess) {
  25269. _this.onSuccess(_this);
  25270. }
  25271. onSuccess();
  25272. }, null, scene.database, false, function () {
  25273. if (_this.onError) {
  25274. _this.onError(_this);
  25275. }
  25276. onError();
  25277. });
  25278. };
  25279. return TextFileAssetTask;
  25280. })();
  25281. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25282. var BinaryFileAssetTask = (function () {
  25283. function BinaryFileAssetTask(name, url) {
  25284. this.name = name;
  25285. this.url = url;
  25286. this.isCompleted = false;
  25287. }
  25288. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25289. var _this = this;
  25290. BABYLON.Tools.LoadFile(this.url, function (data) {
  25291. _this.data = data;
  25292. _this.isCompleted = true;
  25293. if (_this.onSuccess) {
  25294. _this.onSuccess(_this);
  25295. }
  25296. onSuccess();
  25297. }, null, scene.database, true, function () {
  25298. if (_this.onError) {
  25299. _this.onError(_this);
  25300. }
  25301. onError();
  25302. });
  25303. };
  25304. return BinaryFileAssetTask;
  25305. })();
  25306. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25307. var ImageAssetTask = (function () {
  25308. function ImageAssetTask(name, url) {
  25309. this.name = name;
  25310. this.url = url;
  25311. this.isCompleted = false;
  25312. }
  25313. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25314. var _this = this;
  25315. var img = new Image();
  25316. img.onload = function () {
  25317. _this.image = img;
  25318. _this.isCompleted = true;
  25319. if (_this.onSuccess) {
  25320. _this.onSuccess(_this);
  25321. }
  25322. onSuccess();
  25323. };
  25324. img.onerror = function () {
  25325. if (_this.onError) {
  25326. _this.onError(_this);
  25327. }
  25328. onError();
  25329. };
  25330. img.src = this.url;
  25331. };
  25332. return ImageAssetTask;
  25333. })();
  25334. BABYLON.ImageAssetTask = ImageAssetTask;
  25335. var TextureAssetTask = (function () {
  25336. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25338. this.name = name;
  25339. this.url = url;
  25340. this.noMipmap = noMipmap;
  25341. this.invertY = invertY;
  25342. this.samplingMode = samplingMode;
  25343. this.isCompleted = false;
  25344. }
  25345. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25346. var _this = this;
  25347. var onload = function () {
  25348. _this.isCompleted = true;
  25349. if (_this.onSuccess) {
  25350. _this.onSuccess(_this);
  25351. }
  25352. onSuccess();
  25353. };
  25354. var onerror = function () {
  25355. if (_this.onError) {
  25356. _this.onError(_this);
  25357. }
  25358. onError();
  25359. };
  25360. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25361. };
  25362. return TextureAssetTask;
  25363. })();
  25364. BABYLON.TextureAssetTask = TextureAssetTask;
  25365. var AssetsManager = (function () {
  25366. function AssetsManager(scene) {
  25367. this._tasks = new Array();
  25368. this._waitingTasksCount = 0;
  25369. this.useDefaultLoadingScreen = true;
  25370. this._scene = scene;
  25371. }
  25372. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25373. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25374. this._tasks.push(task);
  25375. return task;
  25376. };
  25377. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25378. var task = new TextFileAssetTask(taskName, url);
  25379. this._tasks.push(task);
  25380. return task;
  25381. };
  25382. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25383. var task = new BinaryFileAssetTask(taskName, url);
  25384. this._tasks.push(task);
  25385. return task;
  25386. };
  25387. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25388. var task = new ImageAssetTask(taskName, url);
  25389. this._tasks.push(task);
  25390. return task;
  25391. };
  25392. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25394. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25395. this._tasks.push(task);
  25396. return task;
  25397. };
  25398. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25399. this._waitingTasksCount--;
  25400. if (this._waitingTasksCount === 0) {
  25401. if (this.onFinish) {
  25402. this.onFinish(this._tasks);
  25403. }
  25404. this._scene.getEngine().hideLoadingUI();
  25405. }
  25406. };
  25407. AssetsManager.prototype._runTask = function (task) {
  25408. var _this = this;
  25409. task.run(this._scene, function () {
  25410. if (_this.onTaskSuccess) {
  25411. _this.onTaskSuccess(task);
  25412. }
  25413. _this._decreaseWaitingTasksCount();
  25414. }, function () {
  25415. if (_this.onTaskError) {
  25416. _this.onTaskError(task);
  25417. }
  25418. _this._decreaseWaitingTasksCount();
  25419. });
  25420. };
  25421. AssetsManager.prototype.reset = function () {
  25422. this._tasks = new Array();
  25423. return this;
  25424. };
  25425. AssetsManager.prototype.load = function () {
  25426. this._waitingTasksCount = this._tasks.length;
  25427. if (this._waitingTasksCount === 0) {
  25428. if (this.onFinish) {
  25429. this.onFinish(this._tasks);
  25430. }
  25431. return this;
  25432. }
  25433. if (this.useDefaultLoadingScreen) {
  25434. this._scene.getEngine().displayLoadingUI();
  25435. }
  25436. for (var index = 0; index < this._tasks.length; index++) {
  25437. var task = this._tasks[index];
  25438. this._runTask(task);
  25439. }
  25440. return this;
  25441. };
  25442. return AssetsManager;
  25443. })();
  25444. BABYLON.AssetsManager = AssetsManager;
  25445. })(BABYLON || (BABYLON = {}));
  25446. //# sourceMappingURL=babylon.assetsManager.js.map
  25447. var BABYLON;
  25448. (function (BABYLON) {
  25449. var VRDeviceOrientationCamera = (function (_super) {
  25450. __extends(VRDeviceOrientationCamera, _super);
  25451. function VRDeviceOrientationCamera(name, position, scene) {
  25452. _super.call(this, name, position, scene);
  25453. this._alpha = 0;
  25454. this._beta = 0;
  25455. this._gamma = 0;
  25456. }
  25457. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25458. this._alpha = +evt.alpha | 0;
  25459. this._beta = +evt.beta | 0;
  25460. this._gamma = +evt.gamma | 0;
  25461. if (this._gamma < 0) {
  25462. this._gamma = 90 + this._gamma;
  25463. }
  25464. else {
  25465. // Incline it in the correct angle.
  25466. this._gamma = 270 - this._gamma;
  25467. }
  25468. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25469. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25470. this.rotation.z = this._beta / 180.0 * Math.PI;
  25471. };
  25472. return VRDeviceOrientationCamera;
  25473. })(BABYLON.OculusCamera);
  25474. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25475. })(BABYLON || (BABYLON = {}));
  25476. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25477. var BABYLON;
  25478. (function (BABYLON) {
  25479. var WebVRCamera = (function (_super) {
  25480. __extends(WebVRCamera, _super);
  25481. function WebVRCamera(name, position, scene) {
  25482. _super.call(this, name, position, scene);
  25483. this._hmdDevice = null;
  25484. this._sensorDevice = null;
  25485. this._cacheState = null;
  25486. this._cacheQuaternion = new BABYLON.Quaternion();
  25487. this._cacheRotation = BABYLON.Vector3.Zero();
  25488. this._vrEnabled = false;
  25489. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25490. }
  25491. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25492. var size = devices.length;
  25493. var i = 0;
  25494. // Reset devices.
  25495. this._sensorDevice = null;
  25496. this._hmdDevice = null;
  25497. while (i < size && this._hmdDevice === null) {
  25498. if (devices[i] instanceof HMDVRDevice) {
  25499. this._hmdDevice = devices[i];
  25500. }
  25501. i++;
  25502. }
  25503. i = 0;
  25504. while (i < size && this._sensorDevice === null) {
  25505. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25506. this._sensorDevice = devices[i];
  25507. }
  25508. i++;
  25509. }
  25510. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25511. };
  25512. WebVRCamera.prototype._update = function () {
  25513. if (this._vrEnabled) {
  25514. this._cacheState = this._sensorDevice.getState();
  25515. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25516. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25517. this.rotation.x = -this._cacheRotation.z;
  25518. this.rotation.y = -this._cacheRotation.y;
  25519. this.rotation.z = this._cacheRotation.x;
  25520. }
  25521. _super.prototype._update.call(this);
  25522. };
  25523. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25524. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25525. if (navigator.getVRDevices) {
  25526. navigator.getVRDevices().then(this._getWebVRDevices);
  25527. }
  25528. else if (navigator.mozGetVRDevices) {
  25529. navigator.mozGetVRDevices(this._getWebVRDevices);
  25530. }
  25531. };
  25532. WebVRCamera.prototype.detachControl = function (element) {
  25533. _super.prototype.detachControl.call(this, element);
  25534. this._vrEnabled = false;
  25535. };
  25536. return WebVRCamera;
  25537. })(BABYLON.OculusCamera);
  25538. BABYLON.WebVRCamera = WebVRCamera;
  25539. })(BABYLON || (BABYLON = {}));
  25540. //# sourceMappingURL=babylon.webVRCamera.js.map
  25541. var BABYLON;
  25542. (function (BABYLON) {
  25543. // Standard optimizations
  25544. var SceneOptimization = (function () {
  25545. function SceneOptimization(priority) {
  25546. if (priority === void 0) { priority = 0; }
  25547. this.priority = priority;
  25548. this.apply = function (scene) {
  25549. return true; // Return true if everything that can be done was applied
  25550. };
  25551. }
  25552. return SceneOptimization;
  25553. })();
  25554. BABYLON.SceneOptimization = SceneOptimization;
  25555. var TextureOptimization = (function (_super) {
  25556. __extends(TextureOptimization, _super);
  25557. function TextureOptimization(priority, maximumSize) {
  25558. var _this = this;
  25559. if (priority === void 0) { priority = 0; }
  25560. if (maximumSize === void 0) { maximumSize = 1024; }
  25561. _super.call(this, priority);
  25562. this.priority = priority;
  25563. this.maximumSize = maximumSize;
  25564. this.apply = function (scene) {
  25565. var allDone = true;
  25566. for (var index = 0; index < scene.textures.length; index++) {
  25567. var texture = scene.textures[index];
  25568. if (!texture.canRescale) {
  25569. continue;
  25570. }
  25571. var currentSize = texture.getSize();
  25572. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25573. if (maxDimension > _this.maximumSize) {
  25574. texture.scale(0.5);
  25575. allDone = false;
  25576. }
  25577. }
  25578. return allDone;
  25579. };
  25580. }
  25581. return TextureOptimization;
  25582. })(SceneOptimization);
  25583. BABYLON.TextureOptimization = TextureOptimization;
  25584. var HardwareScalingOptimization = (function (_super) {
  25585. __extends(HardwareScalingOptimization, _super);
  25586. function HardwareScalingOptimization(priority, maximumScale) {
  25587. var _this = this;
  25588. if (priority === void 0) { priority = 0; }
  25589. if (maximumScale === void 0) { maximumScale = 2; }
  25590. _super.call(this, priority);
  25591. this.priority = priority;
  25592. this.maximumScale = maximumScale;
  25593. this._currentScale = 1;
  25594. this.apply = function (scene) {
  25595. _this._currentScale++;
  25596. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25597. return _this._currentScale >= _this.maximumScale;
  25598. };
  25599. }
  25600. return HardwareScalingOptimization;
  25601. })(SceneOptimization);
  25602. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25603. var ShadowsOptimization = (function (_super) {
  25604. __extends(ShadowsOptimization, _super);
  25605. function ShadowsOptimization() {
  25606. _super.apply(this, arguments);
  25607. this.apply = function (scene) {
  25608. scene.shadowsEnabled = false;
  25609. return true;
  25610. };
  25611. }
  25612. return ShadowsOptimization;
  25613. })(SceneOptimization);
  25614. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25615. var PostProcessesOptimization = (function (_super) {
  25616. __extends(PostProcessesOptimization, _super);
  25617. function PostProcessesOptimization() {
  25618. _super.apply(this, arguments);
  25619. this.apply = function (scene) {
  25620. scene.postProcessesEnabled = false;
  25621. return true;
  25622. };
  25623. }
  25624. return PostProcessesOptimization;
  25625. })(SceneOptimization);
  25626. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25627. var LensFlaresOptimization = (function (_super) {
  25628. __extends(LensFlaresOptimization, _super);
  25629. function LensFlaresOptimization() {
  25630. _super.apply(this, arguments);
  25631. this.apply = function (scene) {
  25632. scene.lensFlaresEnabled = false;
  25633. return true;
  25634. };
  25635. }
  25636. return LensFlaresOptimization;
  25637. })(SceneOptimization);
  25638. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25639. var ParticlesOptimization = (function (_super) {
  25640. __extends(ParticlesOptimization, _super);
  25641. function ParticlesOptimization() {
  25642. _super.apply(this, arguments);
  25643. this.apply = function (scene) {
  25644. scene.particlesEnabled = false;
  25645. return true;
  25646. };
  25647. }
  25648. return ParticlesOptimization;
  25649. })(SceneOptimization);
  25650. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25651. var RenderTargetsOptimization = (function (_super) {
  25652. __extends(RenderTargetsOptimization, _super);
  25653. function RenderTargetsOptimization() {
  25654. _super.apply(this, arguments);
  25655. this.apply = function (scene) {
  25656. scene.renderTargetsEnabled = false;
  25657. return true;
  25658. };
  25659. }
  25660. return RenderTargetsOptimization;
  25661. })(SceneOptimization);
  25662. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25663. var MergeMeshesOptimization = (function (_super) {
  25664. __extends(MergeMeshesOptimization, _super);
  25665. function MergeMeshesOptimization() {
  25666. var _this = this;
  25667. _super.apply(this, arguments);
  25668. this._canBeMerged = function (abstractMesh) {
  25669. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25670. return false;
  25671. }
  25672. var mesh = abstractMesh;
  25673. if (!mesh.isVisible || !mesh.isEnabled()) {
  25674. return false;
  25675. }
  25676. if (mesh.instances.length > 0) {
  25677. return false;
  25678. }
  25679. if (mesh.skeleton || mesh.hasLODLevels) {
  25680. return false;
  25681. }
  25682. return true;
  25683. };
  25684. this.apply = function (scene) {
  25685. var globalPool = scene.meshes.slice(0);
  25686. var globalLength = globalPool.length;
  25687. for (var index = 0; index < globalLength; index++) {
  25688. var currentPool = new Array();
  25689. var current = globalPool[index];
  25690. // Checks
  25691. if (!_this._canBeMerged(current)) {
  25692. continue;
  25693. }
  25694. currentPool.push(current);
  25695. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25696. var otherMesh = globalPool[subIndex];
  25697. if (!_this._canBeMerged(otherMesh)) {
  25698. continue;
  25699. }
  25700. if (otherMesh.material !== current.material) {
  25701. continue;
  25702. }
  25703. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25704. continue;
  25705. }
  25706. currentPool.push(otherMesh);
  25707. globalLength--;
  25708. globalPool.splice(subIndex, 1);
  25709. subIndex--;
  25710. }
  25711. if (currentPool.length < 2) {
  25712. continue;
  25713. }
  25714. // Merge meshes
  25715. BABYLON.Mesh.MergeMeshes(currentPool);
  25716. }
  25717. return true;
  25718. };
  25719. }
  25720. return MergeMeshesOptimization;
  25721. })(SceneOptimization);
  25722. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25723. // Options
  25724. var SceneOptimizerOptions = (function () {
  25725. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25726. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25727. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25728. this.targetFrameRate = targetFrameRate;
  25729. this.trackerDuration = trackerDuration;
  25730. this.optimizations = new Array();
  25731. }
  25732. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25733. var result = new SceneOptimizerOptions(targetFrameRate);
  25734. var priority = 0;
  25735. result.optimizations.push(new MergeMeshesOptimization(priority));
  25736. result.optimizations.push(new ShadowsOptimization(priority));
  25737. result.optimizations.push(new LensFlaresOptimization(priority));
  25738. // Next priority
  25739. priority++;
  25740. result.optimizations.push(new PostProcessesOptimization(priority));
  25741. result.optimizations.push(new ParticlesOptimization(priority));
  25742. // Next priority
  25743. priority++;
  25744. result.optimizations.push(new TextureOptimization(priority, 1024));
  25745. return result;
  25746. };
  25747. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25748. var result = new SceneOptimizerOptions(targetFrameRate);
  25749. var priority = 0;
  25750. result.optimizations.push(new MergeMeshesOptimization(priority));
  25751. result.optimizations.push(new ShadowsOptimization(priority));
  25752. result.optimizations.push(new LensFlaresOptimization(priority));
  25753. // Next priority
  25754. priority++;
  25755. result.optimizations.push(new PostProcessesOptimization(priority));
  25756. result.optimizations.push(new ParticlesOptimization(priority));
  25757. // Next priority
  25758. priority++;
  25759. result.optimizations.push(new TextureOptimization(priority, 512));
  25760. // Next priority
  25761. priority++;
  25762. result.optimizations.push(new RenderTargetsOptimization(priority));
  25763. // Next priority
  25764. priority++;
  25765. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25766. return result;
  25767. };
  25768. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25769. var result = new SceneOptimizerOptions(targetFrameRate);
  25770. var priority = 0;
  25771. result.optimizations.push(new MergeMeshesOptimization(priority));
  25772. result.optimizations.push(new ShadowsOptimization(priority));
  25773. result.optimizations.push(new LensFlaresOptimization(priority));
  25774. // Next priority
  25775. priority++;
  25776. result.optimizations.push(new PostProcessesOptimization(priority));
  25777. result.optimizations.push(new ParticlesOptimization(priority));
  25778. // Next priority
  25779. priority++;
  25780. result.optimizations.push(new TextureOptimization(priority, 256));
  25781. // Next priority
  25782. priority++;
  25783. result.optimizations.push(new RenderTargetsOptimization(priority));
  25784. // Next priority
  25785. priority++;
  25786. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25787. return result;
  25788. };
  25789. return SceneOptimizerOptions;
  25790. })();
  25791. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25792. // Scene optimizer tool
  25793. var SceneOptimizer = (function () {
  25794. function SceneOptimizer() {
  25795. }
  25796. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25797. // TODO: add an epsilon
  25798. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25799. if (onSuccess) {
  25800. onSuccess();
  25801. }
  25802. return;
  25803. }
  25804. // Apply current level of optimizations
  25805. var allDone = true;
  25806. var noOptimizationApplied = true;
  25807. for (var index = 0; index < options.optimizations.length; index++) {
  25808. var optimization = options.optimizations[index];
  25809. if (optimization.priority === currentPriorityLevel) {
  25810. noOptimizationApplied = false;
  25811. allDone = allDone && optimization.apply(scene);
  25812. }
  25813. }
  25814. // If no optimization was applied, this is a failure :(
  25815. if (noOptimizationApplied) {
  25816. if (onFailure) {
  25817. onFailure();
  25818. }
  25819. return;
  25820. }
  25821. // If all optimizations were done, move to next level
  25822. if (allDone) {
  25823. currentPriorityLevel++;
  25824. }
  25825. // Let's the system running for a specific amount of time before checking FPS
  25826. scene.executeWhenReady(function () {
  25827. setTimeout(function () {
  25828. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25829. }, options.trackerDuration);
  25830. });
  25831. };
  25832. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25833. if (!options) {
  25834. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25835. }
  25836. // Let's the system running for a specific amount of time before checking FPS
  25837. scene.executeWhenReady(function () {
  25838. setTimeout(function () {
  25839. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25840. }, options.trackerDuration);
  25841. });
  25842. };
  25843. return SceneOptimizer;
  25844. })();
  25845. BABYLON.SceneOptimizer = SceneOptimizer;
  25846. })(BABYLON || (BABYLON = {}));
  25847. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25848. (function (BABYLON) {
  25849. var Internals;
  25850. (function (Internals) {
  25851. var MeshLODLevel = (function () {
  25852. function MeshLODLevel(distance, mesh) {
  25853. this.distance = distance;
  25854. this.mesh = mesh;
  25855. }
  25856. return MeshLODLevel;
  25857. })();
  25858. Internals.MeshLODLevel = MeshLODLevel;
  25859. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25860. })(BABYLON || (BABYLON = {}));
  25861. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25862. (function (BABYLON) {
  25863. var AudioEngine = (function () {
  25864. function AudioEngine() {
  25865. this.audioContext = null;
  25866. this.canUseWebAudio = false;
  25867. this.WarnedWebAudioUnsupported = false;
  25868. try {
  25869. if (typeof AudioContext !== 'undefined') {
  25870. this.audioContext = new AudioContext();
  25871. this.canUseWebAudio = true;
  25872. }
  25873. else if (typeof webkitAudioContext !== 'undefined') {
  25874. this.audioContext = new webkitAudioContext();
  25875. this.canUseWebAudio = true;
  25876. }
  25877. }
  25878. catch (e) {
  25879. this.canUseWebAudio = false;
  25880. BABYLON.Tools.Error("Web Audio: " + e.message);
  25881. }
  25882. // create a global volume gain node
  25883. if (this.canUseWebAudio) {
  25884. this.masterGain = this.audioContext.createGain();
  25885. this.masterGain.gain.value = 1;
  25886. this.masterGain.connect(this.audioContext.destination);
  25887. }
  25888. }
  25889. AudioEngine.prototype.dispose = function () {
  25890. if (this.canUseWebAudio) {
  25891. if (this._connectedAnalyser) {
  25892. this._connectedAnalyser.stopDebugCanvas();
  25893. this._connectedAnalyser.dispose();
  25894. this.masterGain.disconnect();
  25895. this.masterGain.connect(this.audioContext.destination);
  25896. this._connectedAnalyser = null;
  25897. }
  25898. this.masterGain.gain.value = 1;
  25899. }
  25900. this.WarnedWebAudioUnsupported = false;
  25901. };
  25902. AudioEngine.prototype.getGlobalVolume = function () {
  25903. if (this.canUseWebAudio) {
  25904. return this.masterGain.gain.value;
  25905. }
  25906. else {
  25907. return -1;
  25908. }
  25909. };
  25910. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25911. if (this.canUseWebAudio) {
  25912. this.masterGain.gain.value = newVolume;
  25913. }
  25914. };
  25915. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25916. if (this._connectedAnalyser) {
  25917. this._connectedAnalyser.stopDebugCanvas();
  25918. }
  25919. this._connectedAnalyser = analyser;
  25920. if (this.canUseWebAudio) {
  25921. this.masterGain.disconnect();
  25922. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25923. }
  25924. };
  25925. return AudioEngine;
  25926. })();
  25927. BABYLON.AudioEngine = AudioEngine;
  25928. })(BABYLON || (BABYLON = {}));
  25929. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25930. (function (BABYLON) {
  25931. var Sound = (function () {
  25932. /**
  25933. * Create a sound and attach it to a scene
  25934. * @param name Name of your sound
  25935. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25936. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25937. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25938. */
  25939. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25940. var _this = this;
  25941. this.autoplay = false;
  25942. this.loop = false;
  25943. this.useCustomAttenuation = false;
  25944. this.spatialSound = false;
  25945. this.refDistance = 1;
  25946. this.rolloffFactor = 1;
  25947. this.maxDistance = 100;
  25948. this.distanceModel = "linear";
  25949. this.panningModel = "HRTF";
  25950. this._playbackRate = 1;
  25951. this._startTime = 0;
  25952. this._startOffset = 0;
  25953. this._position = BABYLON.Vector3.Zero();
  25954. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25955. this._volume = 1;
  25956. this._isLoaded = false;
  25957. this._isReadyToPlay = false;
  25958. this._isPlaying = false;
  25959. this._isDirectional = false;
  25960. // Used if you'd like to create a directional sound.
  25961. // If not set, the sound will be omnidirectional
  25962. this._coneInnerAngle = 360;
  25963. this._coneOuterAngle = 360;
  25964. this._coneOuterGain = 0;
  25965. this.name = name;
  25966. this._scene = scene;
  25967. this._readyToPlayCallback = readyToPlayCallback;
  25968. // Default custom attenuation function is a linear attenuation
  25969. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25970. if (currentDistance < maxDistance) {
  25971. return currentVolume * (1 - currentDistance / maxDistance);
  25972. }
  25973. else {
  25974. return 0;
  25975. }
  25976. };
  25977. if (options) {
  25978. this.autoplay = options.autoplay || false;
  25979. this.loop = options.loop || false;
  25980. // if volume === 0, we need another way to check this option
  25981. if (options.volume !== undefined) {
  25982. this._volume = options.volume;
  25983. }
  25984. this.spatialSound = options.spatialSound || false;
  25985. this.maxDistance = options.maxDistance || 100;
  25986. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25987. this.rolloffFactor = options.rolloffFactor || 1;
  25988. this.refDistance = options.refDistance || 1;
  25989. this.distanceModel = options.distanceModel || "linear";
  25990. this.panningModel = options.panningModel || "HRTF";
  25991. this._playbackRate = options.playbackRate || 1;
  25992. }
  25993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25994. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25995. this._soundGain.gain.value = this._volume;
  25996. this._inputAudioNode = this._soundGain;
  25997. this._ouputAudioNode = this._soundGain;
  25998. if (this.spatialSound) {
  25999. this._createSpatialParameters();
  26000. }
  26001. this._scene.mainSoundTrack.AddSound(this);
  26002. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26003. if (urlOrArrayBuffer) {
  26004. // If it's an URL
  26005. if (typeof (urlOrArrayBuffer) === "string") {
  26006. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26007. _this._soundLoaded(data);
  26008. }, null, null, true);
  26009. }
  26010. else {
  26011. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26012. this._soundLoaded(urlOrArrayBuffer);
  26013. }
  26014. else {
  26015. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26016. }
  26017. }
  26018. }
  26019. }
  26020. else {
  26021. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26022. this._scene.mainSoundTrack.AddSound(this);
  26023. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26024. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26025. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26026. }
  26027. }
  26028. }
  26029. Sound.prototype.dispose = function () {
  26030. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26031. if (this._isPlaying) {
  26032. this.stop();
  26033. }
  26034. this._isReadyToPlay = false;
  26035. if (this.soundTrackId === -1) {
  26036. this._scene.mainSoundTrack.RemoveSound(this);
  26037. }
  26038. else {
  26039. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26040. }
  26041. this._soundGain.disconnect();
  26042. this._soundSource.disconnect();
  26043. if (this._soundPanner) {
  26044. this._soundPanner.disconnect();
  26045. this._soundPanner = null;
  26046. }
  26047. this._audioBuffer = null;
  26048. this._soundGain = null;
  26049. this._soundSource = null;
  26050. if (this._connectedMesh) {
  26051. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26052. this._connectedMesh = null;
  26053. }
  26054. }
  26055. };
  26056. Sound.prototype._soundLoaded = function (audioData) {
  26057. var _this = this;
  26058. this._isLoaded = true;
  26059. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26060. _this._audioBuffer = buffer;
  26061. _this._isReadyToPlay = true;
  26062. if (_this.autoplay) {
  26063. _this.play();
  26064. }
  26065. if (_this._readyToPlayCallback) {
  26066. _this._readyToPlayCallback();
  26067. }
  26068. }, function (error) {
  26069. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26070. });
  26071. };
  26072. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26073. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26074. this._audioBuffer = audioBuffer;
  26075. this._isReadyToPlay = true;
  26076. }
  26077. };
  26078. Sound.prototype.updateOptions = function (options) {
  26079. if (options) {
  26080. this.loop = options.loop || this.loop;
  26081. this.maxDistance = options.maxDistance || this.maxDistance;
  26082. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26083. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26084. this.refDistance = options.refDistance || this.refDistance;
  26085. this.distanceModel = options.distanceModel || this.distanceModel;
  26086. this.panningModel = options.panningModel || this.panningModel;
  26087. this._playbackRate = options.playbackRate || this._playbackRate;
  26088. }
  26089. };
  26090. Sound.prototype._createSpatialParameters = function () {
  26091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26092. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26093. if (this.useCustomAttenuation) {
  26094. // Tricks to disable in a way embedded Web Audio attenuation
  26095. this._soundPanner.distanceModel = "linear";
  26096. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26097. this._soundPanner.refDistance = 1;
  26098. this._soundPanner.rolloffFactor = 1;
  26099. this._soundPanner.panningModel = "HRTF";
  26100. }
  26101. else {
  26102. this._soundPanner.distanceModel = this.distanceModel;
  26103. this._soundPanner.maxDistance = this.maxDistance;
  26104. this._soundPanner.refDistance = this.refDistance;
  26105. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26106. this._soundPanner.panningModel = this.panningModel;
  26107. }
  26108. this._soundPanner.connect(this._ouputAudioNode);
  26109. this._inputAudioNode = this._soundPanner;
  26110. }
  26111. };
  26112. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26113. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26114. this._ouputAudioNode.disconnect();
  26115. this._ouputAudioNode.connect(soundTrackAudioNode);
  26116. }
  26117. };
  26118. /**
  26119. * Transform this sound into a directional source
  26120. * @param coneInnerAngle Size of the inner cone in degree
  26121. * @param coneOuterAngle Size of the outer cone in degree
  26122. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26123. */
  26124. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26125. if (coneOuterAngle < coneInnerAngle) {
  26126. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26127. return;
  26128. }
  26129. this._coneInnerAngle = coneInnerAngle;
  26130. this._coneOuterAngle = coneOuterAngle;
  26131. this._coneOuterGain = coneOuterGain;
  26132. this._isDirectional = true;
  26133. if (this._isPlaying && this.loop) {
  26134. this.stop();
  26135. this.play();
  26136. }
  26137. };
  26138. Sound.prototype.setPosition = function (newPosition) {
  26139. this._position = newPosition;
  26140. if (this._isPlaying && this.spatialSound) {
  26141. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26142. }
  26143. };
  26144. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26145. this._localDirection = newLocalDirection;
  26146. if (this._connectedMesh && this._isPlaying) {
  26147. this._updateDirection();
  26148. }
  26149. };
  26150. Sound.prototype._updateDirection = function () {
  26151. var mat = this._connectedMesh.getWorldMatrix();
  26152. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26153. direction.normalize();
  26154. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26155. };
  26156. Sound.prototype.updateDistanceFromListener = function () {
  26157. if (this._connectedMesh && this.useCustomAttenuation) {
  26158. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26159. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26160. }
  26161. };
  26162. Sound.prototype.setAttenuationFunction = function (callback) {
  26163. this._customAttenuationFunction = callback;
  26164. };
  26165. /**
  26166. * Play the sound
  26167. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26168. */
  26169. Sound.prototype.play = function (time) {
  26170. if (this._isReadyToPlay) {
  26171. try {
  26172. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26173. if (!this._soundSource) {
  26174. if (this.spatialSound) {
  26175. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26176. if (this._isDirectional) {
  26177. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26178. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26179. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26180. if (this._connectedMesh) {
  26181. this._updateDirection();
  26182. }
  26183. else {
  26184. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26185. }
  26186. }
  26187. }
  26188. }
  26189. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26190. this._soundSource.buffer = this._audioBuffer;
  26191. this._soundSource.connect(this._inputAudioNode);
  26192. this._soundSource.loop = this.loop;
  26193. this._soundSource.playbackRate.value = this._playbackRate;
  26194. this._startTime = startTime;
  26195. if (this.onended) {
  26196. this._soundSource.onended = this.onended;
  26197. }
  26198. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  26199. this._isPlaying = true;
  26200. }
  26201. catch (ex) {
  26202. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26203. }
  26204. }
  26205. };
  26206. /**
  26207. * Stop the sound
  26208. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26209. */
  26210. Sound.prototype.stop = function (time) {
  26211. if (this._isPlaying) {
  26212. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26213. this._soundSource.stop(stopTime);
  26214. this._isPlaying = false;
  26215. }
  26216. };
  26217. Sound.prototype.pause = function () {
  26218. if (this._isPlaying) {
  26219. this._soundSource.stop(0);
  26220. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26221. }
  26222. };
  26223. Sound.prototype.setVolume = function (newVolume, time) {
  26224. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26225. if (time) {
  26226. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26227. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26228. }
  26229. else {
  26230. this._soundGain.gain.value = newVolume;
  26231. }
  26232. }
  26233. this._volume = newVolume;
  26234. };
  26235. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26236. this._playbackRate = newPlaybackRate;
  26237. if (this._isPlaying) {
  26238. this._soundSource.playbackRate.value = this._playbackRate;
  26239. }
  26240. };
  26241. Sound.prototype.getVolume = function () {
  26242. return this._volume;
  26243. };
  26244. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26245. var _this = this;
  26246. this._connectedMesh = meshToConnectTo;
  26247. if (!this.spatialSound) {
  26248. this._createSpatialParameters();
  26249. this.spatialSound = true;
  26250. if (this._isPlaying && this.loop) {
  26251. this.stop();
  26252. this.play();
  26253. }
  26254. }
  26255. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26256. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26257. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26258. };
  26259. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26260. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26261. if (this._isDirectional && this._isPlaying) {
  26262. this._updateDirection();
  26263. }
  26264. };
  26265. return Sound;
  26266. })();
  26267. BABYLON.Sound = Sound;
  26268. })(BABYLON || (BABYLON = {}));
  26269. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26270. (function (BABYLON) {
  26271. var SoundTrack = (function () {
  26272. function SoundTrack(scene, options) {
  26273. this.id = -1;
  26274. this._isMainTrack = false;
  26275. this._scene = scene;
  26276. this._audioEngine = BABYLON.Engine.audioEngine;
  26277. this.soundCollection = new Array();
  26278. if (this._audioEngine.canUseWebAudio) {
  26279. this._trackGain = this._audioEngine.audioContext.createGain();
  26280. this._trackGain.connect(this._audioEngine.masterGain);
  26281. if (options) {
  26282. if (options.volume) {
  26283. this._trackGain.gain.value = options.volume;
  26284. }
  26285. if (options.mainTrack) {
  26286. this._isMainTrack = options.mainTrack;
  26287. }
  26288. }
  26289. }
  26290. if (!this._isMainTrack) {
  26291. this._scene.soundTracks.push(this);
  26292. this.id = this._scene.soundTracks.length - 1;
  26293. }
  26294. }
  26295. SoundTrack.prototype.dispose = function () {
  26296. if (this._audioEngine.canUseWebAudio) {
  26297. if (this._connectedAnalyser) {
  26298. this._connectedAnalyser.stopDebugCanvas();
  26299. }
  26300. while (this.soundCollection.length) {
  26301. this.soundCollection[0].dispose();
  26302. }
  26303. this._trackGain.disconnect();
  26304. this._trackGain = null;
  26305. }
  26306. };
  26307. SoundTrack.prototype.AddSound = function (sound) {
  26308. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26309. sound.connectToSoundTrackAudioNode(this._trackGain);
  26310. }
  26311. if (sound.soundTrackId) {
  26312. if (sound.soundTrackId === -1) {
  26313. this._scene.mainSoundTrack.RemoveSound(sound);
  26314. }
  26315. else {
  26316. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26317. }
  26318. }
  26319. this.soundCollection.push(sound);
  26320. sound.soundTrackId = this.id;
  26321. };
  26322. SoundTrack.prototype.RemoveSound = function (sound) {
  26323. var index = this.soundCollection.indexOf(sound);
  26324. if (index !== -1) {
  26325. this.soundCollection.splice(index, 1);
  26326. }
  26327. };
  26328. SoundTrack.prototype.setVolume = function (newVolume) {
  26329. if (this._audioEngine.canUseWebAudio) {
  26330. this._trackGain.gain.value = newVolume;
  26331. }
  26332. };
  26333. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26334. if (this._connectedAnalyser) {
  26335. this._connectedAnalyser.stopDebugCanvas();
  26336. }
  26337. this._connectedAnalyser = analyser;
  26338. if (this._audioEngine.canUseWebAudio) {
  26339. this._trackGain.disconnect();
  26340. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26341. }
  26342. };
  26343. return SoundTrack;
  26344. })();
  26345. BABYLON.SoundTrack = SoundTrack;
  26346. })(BABYLON || (BABYLON = {}));
  26347. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26348. (function (BABYLON) {
  26349. var DebugLayer = (function () {
  26350. function DebugLayer(scene) {
  26351. var _this = this;
  26352. this._transformationMatrix = BABYLON.Matrix.Identity();
  26353. this._enabled = false;
  26354. this._labelsEnabled = false;
  26355. this._displayStatistics = true;
  26356. this._displayTree = false;
  26357. this._displayLogs = false;
  26358. this._identityMatrix = BABYLON.Matrix.Identity();
  26359. this.axisRatio = 0.02;
  26360. this.accentColor = "orange";
  26361. this._scene = scene;
  26362. this._syncPositions = function () {
  26363. var engine = _this._scene.getEngine();
  26364. var canvasRect = engine.getRenderingCanvasClientRect();
  26365. if (_this._showUI) {
  26366. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26367. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26368. _this._statsDiv.style.width = "400px";
  26369. _this._statsDiv.style.height = "auto";
  26370. _this._statsSubsetDiv.style.maxHeight = "240px";
  26371. _this._optionsDiv.style.left = "0px";
  26372. _this._optionsDiv.style.top = "10px";
  26373. _this._optionsDiv.style.width = "200px";
  26374. _this._optionsDiv.style.height = "auto";
  26375. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26376. _this._logDiv.style.left = "0px";
  26377. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26378. _this._logDiv.style.width = "600px";
  26379. _this._logDiv.style.height = "160px";
  26380. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26381. _this._treeDiv.style.top = "10px";
  26382. _this._treeDiv.style.width = "300px";
  26383. _this._treeDiv.style.height = "auto";
  26384. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26385. }
  26386. _this._globalDiv.style.left = canvasRect.left + "px";
  26387. _this._globalDiv.style.top = canvasRect.top + "px";
  26388. _this._drawingCanvas.style.left = "0px";
  26389. _this._drawingCanvas.style.top = "0px";
  26390. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26391. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26392. var devicePixelRatio = window.devicePixelRatio || 1;
  26393. var context = _this._drawingContext;
  26394. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26395. _this._ratio = devicePixelRatio / backingStoreRatio;
  26396. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26397. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26398. };
  26399. this._onCanvasClick = function (evt) {
  26400. _this._clickPosition = {
  26401. x: evt.clientX * _this._ratio,
  26402. y: evt.clientY * _this._ratio
  26403. };
  26404. };
  26405. this._syncData = function () {
  26406. if (_this._showUI) {
  26407. if (_this._displayStatistics) {
  26408. _this._displayStats();
  26409. _this._statsDiv.style.display = "";
  26410. }
  26411. else {
  26412. _this._statsDiv.style.display = "none";
  26413. }
  26414. if (_this._displayLogs) {
  26415. _this._logDiv.style.display = "";
  26416. }
  26417. else {
  26418. _this._logDiv.style.display = "none";
  26419. }
  26420. if (_this._displayTree) {
  26421. _this._treeDiv.style.display = "";
  26422. if (_this._needToRefreshMeshesTree) {
  26423. _this._needToRefreshMeshesTree = false;
  26424. _this._refreshMeshesTreeContent();
  26425. }
  26426. }
  26427. else {
  26428. _this._treeDiv.style.display = "none";
  26429. }
  26430. }
  26431. if (_this._labelsEnabled || !_this._showUI) {
  26432. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26433. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26434. var engine = _this._scene.getEngine();
  26435. var viewport = _this._camera.viewport;
  26436. var globalViewport = viewport.toGlobal(engine);
  26437. // Meshes
  26438. var meshes = _this._camera.getActiveMeshes();
  26439. for (var index = 0; index < meshes.length; index++) {
  26440. var mesh = meshes.data[index];
  26441. var position = mesh.getBoundingInfo().boundingSphere.center;
  26442. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26443. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26444. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26445. }
  26446. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26447. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26448. mesh.renderOverlay = !mesh.renderOverlay;
  26449. }, function () {
  26450. return mesh.renderOverlay ? 'red' : 'black';
  26451. });
  26452. }
  26453. }
  26454. // Cameras
  26455. var cameras = _this._scene.cameras;
  26456. for (index = 0; index < cameras.length; index++) {
  26457. var camera = cameras[index];
  26458. if (camera === _this._camera) {
  26459. continue;
  26460. }
  26461. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26462. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26463. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26464. _this._camera.detachControl(engine.getRenderingCanvas());
  26465. _this._camera = camera;
  26466. _this._camera.attachControl(engine.getRenderingCanvas());
  26467. }, function () {
  26468. return "purple";
  26469. });
  26470. }
  26471. }
  26472. // Lights
  26473. var lights = _this._scene.lights;
  26474. for (index = 0; index < lights.length; index++) {
  26475. var light = lights[index];
  26476. if (light.position) {
  26477. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26478. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26479. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26480. light.setEnabled(!light.isEnabled());
  26481. }, function () {
  26482. return light.isEnabled() ? "orange" : "gray";
  26483. });
  26484. }
  26485. }
  26486. }
  26487. }
  26488. _this._clickPosition = undefined;
  26489. };
  26490. }
  26491. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26492. while (this._treeSubsetDiv.hasChildNodes()) {
  26493. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26494. }
  26495. // Add meshes
  26496. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26497. sortedArray.sort(function (a, b) {
  26498. if (a.name === b.name) {
  26499. return 0;
  26500. }
  26501. return (a.name > b.name) ? 1 : -1;
  26502. });
  26503. for (var index = 0; index < sortedArray.length; index++) {
  26504. var mesh = sortedArray[index];
  26505. if (!mesh.isEnabled()) {
  26506. continue;
  26507. }
  26508. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26509. m.isVisible = element.checked;
  26510. }, mesh);
  26511. }
  26512. };
  26513. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26514. this._drawingContext.beginPath();
  26515. this._drawingContext.moveTo(zero.x, zero.y);
  26516. this._drawingContext.lineTo(unit.x, unit.y);
  26517. this._drawingContext.strokeStyle = color;
  26518. this._drawingContext.lineWidth = 4;
  26519. this._drawingContext.stroke();
  26520. this._drawingContext.font = "normal 14px Segoe UI";
  26521. this._drawingContext.fillStyle = color;
  26522. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26523. };
  26524. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26525. var position = mesh.getBoundingInfo().boundingSphere.center;
  26526. var worldMatrix = mesh.getWorldMatrix();
  26527. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26528. var unit = (unprojectedVector.subtract(position)).length();
  26529. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26530. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26531. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26532. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26533. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26534. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26535. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26536. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26537. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26538. };
  26539. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26540. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26541. this._drawingContext.font = "normal 12px Segoe UI";
  26542. var textMetrics = this._drawingContext.measureText(text);
  26543. var centerX = projectedPosition.x - textMetrics.width / 2;
  26544. var centerY = projectedPosition.y;
  26545. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26546. if (this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26547. onClick();
  26548. }
  26549. this._drawingContext.beginPath();
  26550. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26551. this._drawingContext.fillStyle = getFillStyle();
  26552. this._drawingContext.globalAlpha = 0.5;
  26553. this._drawingContext.fill();
  26554. this._drawingContext.globalAlpha = 1.0;
  26555. this._drawingContext.strokeStyle = '#FFFFFF';
  26556. this._drawingContext.lineWidth = 1;
  26557. this._drawingContext.stroke();
  26558. this._drawingContext.fillStyle = "#FFFFFF";
  26559. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26560. this._drawingContext.beginPath();
  26561. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26562. this._drawingContext.fill();
  26563. }
  26564. };
  26565. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26566. if (!this._clickPosition) {
  26567. return false;
  26568. }
  26569. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26570. return false;
  26571. }
  26572. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26573. return false;
  26574. }
  26575. return true;
  26576. };
  26577. DebugLayer.prototype.isVisible = function () {
  26578. return this._enabled;
  26579. };
  26580. DebugLayer.prototype.hide = function () {
  26581. if (!this._enabled) {
  26582. return;
  26583. }
  26584. this._enabled = false;
  26585. var engine = this._scene.getEngine();
  26586. this._scene.unregisterAfterRender(this._syncData);
  26587. document.body.removeChild(this._globalDiv);
  26588. window.removeEventListener("resize", this._syncPositions);
  26589. this._scene.forceShowBoundingBoxes = false;
  26590. this._scene.forceWireframe = false;
  26591. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26592. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26593. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26594. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26595. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26596. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26597. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26598. this._scene.shadowsEnabled = true;
  26599. this._scene.particlesEnabled = true;
  26600. this._scene.postProcessesEnabled = true;
  26601. this._scene.collisionsEnabled = true;
  26602. this._scene.lightsEnabled = true;
  26603. this._scene.texturesEnabled = true;
  26604. this._scene.lensFlaresEnabled = true;
  26605. this._scene.proceduralTexturesEnabled = true;
  26606. this._scene.renderTargetsEnabled = true;
  26607. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26608. };
  26609. DebugLayer.prototype.show = function (showUI, camera) {
  26610. if (showUI === void 0) { showUI = true; }
  26611. if (camera === void 0) { camera = null; }
  26612. if (this._enabled) {
  26613. return;
  26614. }
  26615. if (camera) {
  26616. this._camera = camera;
  26617. }
  26618. else {
  26619. this._camera = this._scene.activeCamera;
  26620. }
  26621. this._enabled = true;
  26622. this._showUI = showUI;
  26623. var engine = this._scene.getEngine();
  26624. this._globalDiv = document.createElement("div");
  26625. document.body.appendChild(this._globalDiv);
  26626. this._generateDOMelements();
  26627. window.addEventListener("resize", this._syncPositions);
  26628. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26629. this._syncPositions();
  26630. this._scene.registerAfterRender(this._syncData);
  26631. };
  26632. DebugLayer.prototype._clearLabels = function () {
  26633. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26634. for (var index = 0; index < this._scene.meshes.length; index++) {
  26635. var mesh = this._scene.meshes[index];
  26636. mesh.renderOverlay = false;
  26637. }
  26638. };
  26639. DebugLayer.prototype._generateheader = function (root, text) {
  26640. var header = document.createElement("div");
  26641. header.innerHTML = text + "&nbsp;";
  26642. header.style.textAlign = "right";
  26643. header.style.width = "100%";
  26644. header.style.color = "white";
  26645. header.style.backgroundColor = "Black";
  26646. header.style.padding = "5px 5px 4px 0px";
  26647. header.style.marginLeft = "-5px";
  26648. header.style.fontWeight = "bold";
  26649. root.appendChild(header);
  26650. };
  26651. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26652. var label = document.createElement("label");
  26653. label.innerHTML = title;
  26654. label.style.color = color;
  26655. root.appendChild(label);
  26656. root.appendChild(document.createElement("br"));
  26657. };
  26658. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26659. if (tag === void 0) { tag = null; }
  26660. var label = document.createElement("label");
  26661. var boundingBoxesCheckbox = document.createElement("input");
  26662. boundingBoxesCheckbox.type = "checkbox";
  26663. boundingBoxesCheckbox.checked = initialState;
  26664. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26665. task(evt.target, tag);
  26666. });
  26667. label.appendChild(boundingBoxesCheckbox);
  26668. var container = document.createElement("span");
  26669. var leftPart = document.createElement("span");
  26670. var rightPart = document.createElement("span");
  26671. rightPart.style.cssFloat = "right";
  26672. leftPart.innerHTML = leftTitle;
  26673. rightPart.innerHTML = rightTitle;
  26674. rightPart.style.fontSize = "12px";
  26675. rightPart.style.maxWidth = "200px";
  26676. container.appendChild(leftPart);
  26677. container.appendChild(rightPart);
  26678. label.appendChild(container);
  26679. root.appendChild(label);
  26680. root.appendChild(document.createElement("br"));
  26681. };
  26682. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26683. if (tag === void 0) { tag = null; }
  26684. var label = document.createElement("label");
  26685. var boundingBoxesCheckbox = document.createElement("input");
  26686. boundingBoxesCheckbox.type = "checkbox";
  26687. boundingBoxesCheckbox.checked = initialState;
  26688. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26689. task(evt.target, tag);
  26690. });
  26691. label.appendChild(boundingBoxesCheckbox);
  26692. label.appendChild(document.createTextNode(title));
  26693. root.appendChild(label);
  26694. root.appendChild(document.createElement("br"));
  26695. };
  26696. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26697. if (tag === void 0) { tag = null; }
  26698. var label = document.createElement("label");
  26699. var boundingBoxesRadio = document.createElement("input");
  26700. boundingBoxesRadio.type = "radio";
  26701. boundingBoxesRadio.name = name;
  26702. boundingBoxesRadio.checked = initialState;
  26703. boundingBoxesRadio.addEventListener("change", function (evt) {
  26704. task(evt.target, tag);
  26705. });
  26706. label.appendChild(boundingBoxesRadio);
  26707. label.appendChild(document.createTextNode(title));
  26708. root.appendChild(label);
  26709. root.appendChild(document.createElement("br"));
  26710. };
  26711. DebugLayer.prototype._generateDOMelements = function () {
  26712. var _this = this;
  26713. this._globalDiv.id = "DebugLayer";
  26714. this._globalDiv.style.position = "absolute";
  26715. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26716. this._globalDiv.style.fontSize = "14px";
  26717. this._globalDiv.style.color = "white";
  26718. // Drawing canvas
  26719. this._drawingCanvas = document.createElement("canvas");
  26720. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26721. this._drawingCanvas.style.position = "absolute";
  26722. this._drawingCanvas.style.pointerEvents = "none";
  26723. this._drawingContext = this._drawingCanvas.getContext("2d");
  26724. this._globalDiv.appendChild(this._drawingCanvas);
  26725. if (this._showUI) {
  26726. var background = "rgba(128, 128, 128, 0.4)";
  26727. var border = "rgb(180, 180, 180) solid 1px";
  26728. // Stats
  26729. this._statsDiv = document.createElement("div");
  26730. this._statsDiv.id = "DebugLayerStats";
  26731. this._statsDiv.style.border = border;
  26732. this._statsDiv.style.position = "absolute";
  26733. this._statsDiv.style.background = background;
  26734. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26735. this._generateheader(this._statsDiv, "STATISTICS");
  26736. this._statsSubsetDiv = document.createElement("div");
  26737. this._statsSubsetDiv.style.paddingTop = "5px";
  26738. this._statsSubsetDiv.style.paddingBottom = "5px";
  26739. this._statsSubsetDiv.style.overflowY = "auto";
  26740. this._statsDiv.appendChild(this._statsSubsetDiv);
  26741. // Tree
  26742. this._treeDiv = document.createElement("div");
  26743. this._treeDiv.id = "DebugLayerTree";
  26744. this._treeDiv.style.border = border;
  26745. this._treeDiv.style.position = "absolute";
  26746. this._treeDiv.style.background = background;
  26747. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26748. this._treeDiv.style.display = "none";
  26749. this._generateheader(this._treeDiv, "MESHES TREE");
  26750. this._treeSubsetDiv = document.createElement("div");
  26751. this._treeSubsetDiv.style.paddingTop = "5px";
  26752. this._treeSubsetDiv.style.paddingRight = "5px";
  26753. this._treeSubsetDiv.style.overflowY = "auto";
  26754. this._treeSubsetDiv.style.maxHeight = "300px";
  26755. this._treeDiv.appendChild(this._treeSubsetDiv);
  26756. this._needToRefreshMeshesTree = true;
  26757. // Logs
  26758. this._logDiv = document.createElement("div");
  26759. this._logDiv.style.border = border;
  26760. this._logDiv.id = "DebugLayerLogs";
  26761. this._logDiv.style.position = "absolute";
  26762. this._logDiv.style.background = background;
  26763. this._logDiv.style.padding = "0px 0px 0px 5px";
  26764. this._logDiv.style.display = "none";
  26765. this._generateheader(this._logDiv, "LOGS");
  26766. this._logSubsetDiv = document.createElement("div");
  26767. this._logSubsetDiv.style.height = "127px";
  26768. this._logSubsetDiv.style.paddingTop = "5px";
  26769. this._logSubsetDiv.style.overflowY = "auto";
  26770. this._logSubsetDiv.style.fontSize = "12px";
  26771. this._logSubsetDiv.style.fontFamily = "consolas";
  26772. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26773. this._logDiv.appendChild(this._logSubsetDiv);
  26774. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26775. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26776. };
  26777. // Options
  26778. this._optionsDiv = document.createElement("div");
  26779. this._optionsDiv.id = "DebugLayerOptions";
  26780. this._optionsDiv.style.border = border;
  26781. this._optionsDiv.style.position = "absolute";
  26782. this._optionsDiv.style.background = background;
  26783. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26784. this._optionsDiv.style.overflowY = "auto";
  26785. this._generateheader(this._optionsDiv, "OPTIONS");
  26786. this._optionsSubsetDiv = document.createElement("div");
  26787. this._optionsSubsetDiv.style.paddingTop = "5px";
  26788. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26789. this._optionsSubsetDiv.style.overflowY = "auto";
  26790. this._optionsSubsetDiv.style.maxHeight = "200px";
  26791. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26792. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26793. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26794. _this._displayStatistics = element.checked;
  26795. });
  26796. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26797. _this._displayLogs = element.checked;
  26798. });
  26799. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26800. _this._displayTree = element.checked;
  26801. _this._needToRefreshMeshesTree = true;
  26802. });
  26803. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26804. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26805. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26806. _this._scene.forceShowBoundingBoxes = element.checked;
  26807. });
  26808. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26809. _this._labelsEnabled = element.checked;
  26810. if (!_this._labelsEnabled) {
  26811. _this._clearLabels();
  26812. }
  26813. });
  26814. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26815. if (element.checked) {
  26816. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26817. }
  26818. else {
  26819. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26820. }
  26821. });
  26822. ;
  26823. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26824. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26825. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26826. if (element.checked) {
  26827. _this._scene.forceWireframe = false;
  26828. _this._scene.forcePointsCloud = false;
  26829. }
  26830. });
  26831. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26832. if (element.checked) {
  26833. _this._scene.forceWireframe = true;
  26834. _this._scene.forcePointsCloud = false;
  26835. }
  26836. });
  26837. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26838. if (element.checked) {
  26839. _this._scene.forceWireframe = false;
  26840. _this._scene.forcePointsCloud = true;
  26841. }
  26842. });
  26843. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26844. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26845. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26846. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26847. });
  26848. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26849. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26850. });
  26851. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26852. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26853. });
  26854. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26855. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26856. });
  26857. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26858. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26859. });
  26860. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26861. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26862. });
  26863. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26864. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26865. });
  26866. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26867. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26868. });
  26869. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26870. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26871. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26872. _this._scene.animationsEnabled = element.checked;
  26873. });
  26874. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26875. _this._scene.collisionsEnabled = element.checked;
  26876. });
  26877. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26878. _this._scene.fogEnabled = element.checked;
  26879. });
  26880. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26881. _this._scene.lensFlaresEnabled = element.checked;
  26882. });
  26883. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26884. _this._scene.lightsEnabled = element.checked;
  26885. });
  26886. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26887. _this._scene.particlesEnabled = element.checked;
  26888. });
  26889. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26890. _this._scene.postProcessesEnabled = element.checked;
  26891. });
  26892. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26893. _this._scene.proceduralTexturesEnabled = element.checked;
  26894. });
  26895. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26896. _this._scene.renderTargetsEnabled = element.checked;
  26897. });
  26898. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26899. _this._scene.shadowsEnabled = element.checked;
  26900. });
  26901. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26902. _this._scene.skeletonsEnabled = element.checked;
  26903. });
  26904. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  26905. _this._scene.spritesEnabled = element.checked;
  26906. });
  26907. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26908. _this._scene.texturesEnabled = element.checked;
  26909. });
  26910. this._globalDiv.appendChild(this._statsDiv);
  26911. this._globalDiv.appendChild(this._logDiv);
  26912. this._globalDiv.appendChild(this._optionsDiv);
  26913. this._globalDiv.appendChild(this._treeDiv);
  26914. }
  26915. };
  26916. DebugLayer.prototype._displayStats = function () {
  26917. var scene = this._scene;
  26918. var engine = scene.getEngine();
  26919. var glInfo = engine.getGlInfo();
  26920. 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>";
  26921. if (this.customStatsFunction) {
  26922. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26923. }
  26924. };
  26925. return DebugLayer;
  26926. })();
  26927. BABYLON.DebugLayer = DebugLayer;
  26928. })(BABYLON || (BABYLON = {}));
  26929. //# sourceMappingURL=babylon.debugLayer.js.map
  26930. var BABYLON;
  26931. (function (BABYLON) {
  26932. var RawTexture = (function (_super) {
  26933. __extends(RawTexture, _super);
  26934. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26935. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26936. if (invertY === void 0) { invertY = false; }
  26937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26938. _super.call(this, null, scene, !generateMipMaps, invertY);
  26939. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26940. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26941. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26942. }
  26943. // Statics
  26944. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26945. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26946. if (invertY === void 0) { invertY = false; }
  26947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26948. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26949. };
  26950. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26951. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26952. if (invertY === void 0) { invertY = false; }
  26953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26954. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26955. };
  26956. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26957. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26958. if (invertY === void 0) { invertY = false; }
  26959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26960. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26961. };
  26962. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26963. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26964. if (invertY === void 0) { invertY = false; }
  26965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26966. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26967. };
  26968. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26969. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26970. if (invertY === void 0) { invertY = false; }
  26971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26972. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26973. };
  26974. return RawTexture;
  26975. })(BABYLON.Texture);
  26976. BABYLON.RawTexture = RawTexture;
  26977. })(BABYLON || (BABYLON = {}));
  26978. //# sourceMappingURL=babylon.rawTexture.js.map
  26979. var BABYLON;
  26980. (function (BABYLON) {
  26981. var IndexedVector2 = (function (_super) {
  26982. __extends(IndexedVector2, _super);
  26983. function IndexedVector2(original, index) {
  26984. _super.call(this, original.x, original.y);
  26985. this.index = index;
  26986. }
  26987. return IndexedVector2;
  26988. })(BABYLON.Vector2);
  26989. var PolygonPoints = (function () {
  26990. function PolygonPoints() {
  26991. this.elements = new Array();
  26992. }
  26993. PolygonPoints.prototype.add = function (originalPoints) {
  26994. var _this = this;
  26995. var result = new Array();
  26996. originalPoints.forEach(function (point) {
  26997. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26998. var newPoint = new IndexedVector2(point, _this.elements.length);
  26999. result.push(newPoint);
  27000. _this.elements.push(newPoint);
  27001. }
  27002. });
  27003. return result;
  27004. };
  27005. PolygonPoints.prototype.computeBounds = function () {
  27006. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27007. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27008. this.elements.forEach(function (point) {
  27009. // x
  27010. if (point.x < lmin.x) {
  27011. lmin.x = point.x;
  27012. }
  27013. else if (point.x > lmax.x) {
  27014. lmax.x = point.x;
  27015. }
  27016. // y
  27017. if (point.y < lmin.y) {
  27018. lmin.y = point.y;
  27019. }
  27020. else if (point.y > lmax.y) {
  27021. lmax.y = point.y;
  27022. }
  27023. });
  27024. return {
  27025. min: lmin,
  27026. max: lmax,
  27027. width: lmax.x - lmin.x,
  27028. height: lmax.y - lmin.y
  27029. };
  27030. };
  27031. return PolygonPoints;
  27032. })();
  27033. var Polygon = (function () {
  27034. function Polygon() {
  27035. }
  27036. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27037. return [
  27038. new BABYLON.Vector2(xmin, ymin),
  27039. new BABYLON.Vector2(xmax, ymin),
  27040. new BABYLON.Vector2(xmax, ymax),
  27041. new BABYLON.Vector2(xmin, ymax)
  27042. ];
  27043. };
  27044. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27045. if (cx === void 0) { cx = 0; }
  27046. if (cy === void 0) { cy = 0; }
  27047. if (numberOfSides === void 0) { numberOfSides = 32; }
  27048. var result = new Array();
  27049. var angle = 0;
  27050. var increment = (Math.PI * 2) / numberOfSides;
  27051. for (var i = 0; i < numberOfSides; i++) {
  27052. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27053. angle -= increment;
  27054. }
  27055. return result;
  27056. };
  27057. Polygon.Parse = function (input) {
  27058. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27059. var i, result = [];
  27060. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27061. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27062. }
  27063. return result;
  27064. };
  27065. Polygon.StartingAt = function (x, y) {
  27066. return BABYLON.Path2.StartingAt(x, y);
  27067. };
  27068. return Polygon;
  27069. })();
  27070. BABYLON.Polygon = Polygon;
  27071. var PolygonMeshBuilder = (function () {
  27072. function PolygonMeshBuilder(name, contours, scene) {
  27073. this._points = new PolygonPoints();
  27074. if (!("poly2tri" in window)) {
  27075. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27076. }
  27077. this._name = name;
  27078. this._scene = scene;
  27079. var points;
  27080. if (contours instanceof BABYLON.Path2) {
  27081. points = contours.getPoints();
  27082. }
  27083. else {
  27084. points = contours;
  27085. }
  27086. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27087. }
  27088. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27089. this._swctx.addHole(this._points.add(hole));
  27090. return this;
  27091. };
  27092. PolygonMeshBuilder.prototype.build = function (updatable) {
  27093. if (updatable === void 0) { updatable = false; }
  27094. var result = new BABYLON.Mesh(this._name, this._scene);
  27095. var normals = [];
  27096. var positions = [];
  27097. var uvs = [];
  27098. var bounds = this._points.computeBounds();
  27099. this._points.elements.forEach(function (p) {
  27100. normals.push(0, 1.0, 0);
  27101. positions.push(p.x, 0, p.y);
  27102. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27103. });
  27104. var indices = [];
  27105. this._swctx.triangulate();
  27106. this._swctx.getTriangles().forEach(function (triangle) {
  27107. triangle.getPoints().forEach(function (point) {
  27108. indices.push(point.index);
  27109. });
  27110. });
  27111. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27112. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27113. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27114. result.setIndices(indices);
  27115. return result;
  27116. };
  27117. return PolygonMeshBuilder;
  27118. })();
  27119. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27120. })(BABYLON || (BABYLON = {}));
  27121. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27122. (function (BABYLON) {
  27123. var SimplificationSettings = (function () {
  27124. function SimplificationSettings(quality, distance) {
  27125. this.quality = quality;
  27126. this.distance = distance;
  27127. }
  27128. return SimplificationSettings;
  27129. })();
  27130. BABYLON.SimplificationSettings = SimplificationSettings;
  27131. /**
  27132. * The implemented types of simplification.
  27133. * At the moment only Quadratic Error Decimation is implemented.
  27134. */
  27135. (function (SimplificationType) {
  27136. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27137. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27138. var SimplificationType = BABYLON.SimplificationType;
  27139. var DecimationTriangle = (function () {
  27140. function DecimationTriangle(vertices) {
  27141. this.vertices = vertices;
  27142. this.error = new Array(4);
  27143. this.deleted = false;
  27144. this.isDirty = false;
  27145. this.borderFactor = 0;
  27146. }
  27147. return DecimationTriangle;
  27148. })();
  27149. BABYLON.DecimationTriangle = DecimationTriangle;
  27150. var DecimationVertex = (function () {
  27151. function DecimationVertex(position, normal, uv, id) {
  27152. this.position = position;
  27153. this.normal = normal;
  27154. this.uv = uv;
  27155. this.id = id;
  27156. this.isBorder = true;
  27157. this.q = new QuadraticMatrix();
  27158. this.triangleCount = 0;
  27159. this.triangleStart = 0;
  27160. }
  27161. return DecimationVertex;
  27162. })();
  27163. BABYLON.DecimationVertex = DecimationVertex;
  27164. var QuadraticMatrix = (function () {
  27165. function QuadraticMatrix(data) {
  27166. this.data = new Array(10);
  27167. for (var i = 0; i < 10; ++i) {
  27168. if (data && data[i]) {
  27169. this.data[i] = data[i];
  27170. }
  27171. else {
  27172. this.data[i] = 0;
  27173. }
  27174. }
  27175. }
  27176. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27177. 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];
  27178. return det;
  27179. };
  27180. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27181. for (var i = 0; i < 10; ++i) {
  27182. this.data[i] += matrix.data[i];
  27183. }
  27184. };
  27185. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27186. for (var i = 0; i < 10; ++i) {
  27187. this.data[i] += data[i];
  27188. }
  27189. };
  27190. QuadraticMatrix.prototype.add = function (matrix) {
  27191. var m = new QuadraticMatrix();
  27192. for (var i = 0; i < 10; ++i) {
  27193. m.data[i] = this.data[i] + matrix.data[i];
  27194. }
  27195. return m;
  27196. };
  27197. QuadraticMatrix.FromData = function (a, b, c, d) {
  27198. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27199. };
  27200. //returning an array to avoid garbage collection
  27201. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27202. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27203. };
  27204. return QuadraticMatrix;
  27205. })();
  27206. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27207. var Reference = (function () {
  27208. function Reference(vertexId, triangleId) {
  27209. this.vertexId = vertexId;
  27210. this.triangleId = triangleId;
  27211. }
  27212. return Reference;
  27213. })();
  27214. BABYLON.Reference = Reference;
  27215. /**
  27216. * An implementation of the Quadratic Error simplification algorithm.
  27217. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27218. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27219. * @author RaananW
  27220. */
  27221. var QuadraticErrorSimplification = (function () {
  27222. function QuadraticErrorSimplification(_mesh) {
  27223. this._mesh = _mesh;
  27224. this.initialised = false;
  27225. this.syncIterations = 5000;
  27226. this.aggressiveness = 7;
  27227. this.decimationIterations = 100;
  27228. }
  27229. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27230. var _this = this;
  27231. this.initWithMesh(this._mesh, function () {
  27232. _this.runDecimation(settings, successCallback);
  27233. });
  27234. };
  27235. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  27236. var _this = this;
  27237. var targetCount = ~~(this.triangles.length * settings.quality);
  27238. var deletedTriangles = 0;
  27239. var triangleCount = this.triangles.length;
  27240. var iterationFunction = function (iteration, callback) {
  27241. setTimeout(function () {
  27242. if (iteration % 5 === 0) {
  27243. _this.updateMesh(iteration === 0);
  27244. }
  27245. for (var i = 0; i < _this.triangles.length; ++i) {
  27246. _this.triangles[i].isDirty = false;
  27247. }
  27248. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27249. var trianglesIterator = function (i) {
  27250. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27251. var t = _this.triangles[tIdx];
  27252. if (!t)
  27253. return;
  27254. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27255. return;
  27256. }
  27257. for (var j = 0; j < 3; ++j) {
  27258. if (t.error[j] < threshold) {
  27259. var deleted0 = [];
  27260. var deleted1 = [];
  27261. var i0 = t.vertices[j];
  27262. var i1 = t.vertices[(j + 1) % 3];
  27263. var v0 = _this.vertices[i0];
  27264. var v1 = _this.vertices[i1];
  27265. if (v0.isBorder !== v1.isBorder)
  27266. continue;
  27267. var p = BABYLON.Vector3.Zero();
  27268. var n = BABYLON.Vector3.Zero();
  27269. var uv = BABYLON.Vector2.Zero();
  27270. var color = new BABYLON.Color4(0, 0, 0, 1);
  27271. _this.calculateError(v0, v1, p, n, uv, color);
  27272. var delTr = [];
  27273. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27274. continue;
  27275. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27276. continue;
  27277. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27278. continue;
  27279. }
  27280. v0.normal = n;
  27281. if (v0.uv)
  27282. v0.uv = uv;
  27283. else if (v0.color)
  27284. v0.color = color;
  27285. v0.q = v1.q.add(v0.q);
  27286. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27287. continue;
  27288. if (p.equals(v0.position))
  27289. continue;
  27290. v0.position = p;
  27291. var tStart = _this.references.length;
  27292. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27293. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27294. var tCount = _this.references.length - tStart;
  27295. if (tCount <= v0.triangleCount) {
  27296. if (tCount) {
  27297. for (var c = 0; c < tCount; c++) {
  27298. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27299. }
  27300. }
  27301. }
  27302. else {
  27303. v0.triangleStart = tStart;
  27304. }
  27305. v0.triangleCount = tCount;
  27306. break;
  27307. }
  27308. }
  27309. };
  27310. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27311. return (triangleCount - deletedTriangles <= targetCount);
  27312. });
  27313. }, 0);
  27314. };
  27315. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27316. if (triangleCount - deletedTriangles <= targetCount)
  27317. loop.breakLoop();
  27318. else {
  27319. iterationFunction(loop.index, function () {
  27320. loop.executeNext();
  27321. });
  27322. }
  27323. }, function () {
  27324. setTimeout(function () {
  27325. successCallback(_this.reconstructMesh());
  27326. }, 0);
  27327. });
  27328. };
  27329. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27330. var _this = this;
  27331. if (!mesh)
  27332. return;
  27333. this.vertices = [];
  27334. this.triangles = [];
  27335. this._mesh = mesh;
  27336. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27337. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27338. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27339. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27340. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27341. var indices = mesh.getIndices();
  27342. var vertexInit = function (i) {
  27343. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27344. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27345. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27346. }
  27347. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27348. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27349. }
  27350. _this.vertices.push(vertex);
  27351. };
  27352. var totalVertices = mesh.getTotalVertices();
  27353. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27354. var indicesInit = function (i) {
  27355. var pos = i * 3;
  27356. var i0 = indices[pos + 0];
  27357. var i1 = indices[pos + 1];
  27358. var i2 = indices[pos + 2];
  27359. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27360. _this.triangles.push(triangle);
  27361. };
  27362. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27363. _this.init(callback);
  27364. });
  27365. });
  27366. };
  27367. QuadraticErrorSimplification.prototype.init = function (callback) {
  27368. var _this = this;
  27369. var triangleInit1 = function (i) {
  27370. var t = _this.triangles[i];
  27371. 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();
  27372. for (var j = 0; j < 3; j++) {
  27373. _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))));
  27374. }
  27375. };
  27376. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27377. var triangleInit2 = function (i) {
  27378. var t = _this.triangles[i];
  27379. for (var j = 0; j < 3; ++j) {
  27380. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27381. }
  27382. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27383. };
  27384. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27385. _this.initialised = true;
  27386. callback();
  27387. });
  27388. });
  27389. };
  27390. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27391. var newTriangles = [];
  27392. var i;
  27393. for (i = 0; i < this.vertices.length; ++i) {
  27394. this.vertices[i].triangleCount = 0;
  27395. }
  27396. var t;
  27397. var j;
  27398. for (i = 0; i < this.triangles.length; ++i) {
  27399. if (!this.triangles[i].deleted) {
  27400. t = this.triangles[i];
  27401. for (j = 0; j < 3; ++j) {
  27402. this.vertices[t.vertices[j]].triangleCount = 1;
  27403. }
  27404. newTriangles.push(t);
  27405. }
  27406. }
  27407. var newVerticesOrder = [];
  27408. //compact vertices, get the IDs of the vertices used.
  27409. var dst = 0;
  27410. for (i = 0; i < this.vertices.length; ++i) {
  27411. if (this.vertices[i].triangleCount) {
  27412. this.vertices[i].triangleStart = dst;
  27413. this.vertices[dst].position = this.vertices[i].position;
  27414. this.vertices[dst].normal = this.vertices[i].normal;
  27415. this.vertices[dst].uv = this.vertices[i].uv;
  27416. this.vertices[dst].color = this.vertices[i].color;
  27417. newVerticesOrder.push(i);
  27418. dst++;
  27419. }
  27420. }
  27421. for (i = 0; i < newTriangles.length; ++i) {
  27422. t = newTriangles[i];
  27423. for (j = 0; j < 3; ++j) {
  27424. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27425. }
  27426. }
  27427. this.vertices = this.vertices.slice(0, dst);
  27428. var newPositionData = [];
  27429. var newNormalData = [];
  27430. var newUVsData = [];
  27431. var newColorsData = [];
  27432. for (i = 0; i < newVerticesOrder.length; ++i) {
  27433. newPositionData.push(this.vertices[i].position.x);
  27434. newPositionData.push(this.vertices[i].position.y);
  27435. newPositionData.push(this.vertices[i].position.z);
  27436. newNormalData.push(this.vertices[i].normal.x);
  27437. newNormalData.push(this.vertices[i].normal.y);
  27438. newNormalData.push(this.vertices[i].normal.z);
  27439. if (this.vertices[i].uv) {
  27440. newUVsData.push(this.vertices[i].uv.x);
  27441. newUVsData.push(this.vertices[i].uv.y);
  27442. }
  27443. else if (this.vertices[i].color) {
  27444. newColorsData.push(this.vertices[i].color.r);
  27445. newColorsData.push(this.vertices[i].color.g);
  27446. newColorsData.push(this.vertices[i].color.b);
  27447. newColorsData.push(this.vertices[i].color.a);
  27448. }
  27449. }
  27450. var newIndicesArray = [];
  27451. for (i = 0; i < newTriangles.length; ++i) {
  27452. newIndicesArray.push(newTriangles[i].vertices[0]);
  27453. newIndicesArray.push(newTriangles[i].vertices[1]);
  27454. newIndicesArray.push(newTriangles[i].vertices[2]);
  27455. }
  27456. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27457. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27458. newMesh.material = this._mesh.material;
  27459. newMesh.parent = this._mesh.parent;
  27460. newMesh.setIndices(newIndicesArray);
  27461. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27462. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27463. if (newUVsData.length > 0)
  27464. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27465. if (newColorsData.length > 0)
  27466. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27467. //preparing the skeleton support
  27468. if (this._mesh.skeleton) {
  27469. }
  27470. return newMesh;
  27471. };
  27472. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27473. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27474. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27475. if (t.deleted)
  27476. continue;
  27477. var s = this.references[vertex1.triangleStart + i].vertexId;
  27478. var id1 = t.vertices[(s + 1) % 3];
  27479. var id2 = t.vertices[(s + 2) % 3];
  27480. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27481. deletedArray[i] = true;
  27482. delTr.push(t);
  27483. continue;
  27484. }
  27485. var d1 = this.vertices[id1].position.subtract(point);
  27486. d1 = d1.normalize();
  27487. var d2 = this.vertices[id2].position.subtract(point);
  27488. d2 = d2.normalize();
  27489. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27490. return true;
  27491. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27492. deletedArray[i] = false;
  27493. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27494. return true;
  27495. }
  27496. return false;
  27497. };
  27498. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27499. var newDeleted = deletedTriangles;
  27500. for (var i = 0; i < vertex.triangleCount; ++i) {
  27501. var ref = this.references[vertex.triangleStart + i];
  27502. var t = this.triangles[ref.triangleId];
  27503. if (t.deleted)
  27504. continue;
  27505. if (deletedArray[i]) {
  27506. t.deleted = true;
  27507. newDeleted++;
  27508. continue;
  27509. }
  27510. t.vertices[ref.vertexId] = vertexId;
  27511. t.isDirty = true;
  27512. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27513. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27514. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27515. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27516. this.references.push(ref);
  27517. }
  27518. return newDeleted;
  27519. };
  27520. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27521. for (var i = 0; i < this.vertices.length; ++i) {
  27522. var vCount = [];
  27523. var vId = [];
  27524. var v = this.vertices[i];
  27525. var j;
  27526. for (j = 0; j < v.triangleCount; ++j) {
  27527. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27528. for (var ii = 0; ii < 3; ii++) {
  27529. var ofs = 0;
  27530. var id = triangle.vertices[ii];
  27531. while (ofs < vCount.length) {
  27532. if (vId[ofs] === id)
  27533. break;
  27534. ++ofs;
  27535. }
  27536. if (ofs === vCount.length) {
  27537. vCount.push(1);
  27538. vId.push(id);
  27539. }
  27540. else {
  27541. vCount[ofs]++;
  27542. }
  27543. }
  27544. }
  27545. for (j = 0; j < vCount.length; ++j) {
  27546. if (vCount[j] === 1) {
  27547. this.vertices[vId[j]].isBorder = true;
  27548. }
  27549. else {
  27550. this.vertices[vId[j]].isBorder = false;
  27551. }
  27552. }
  27553. }
  27554. };
  27555. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27556. if (identifyBorders === void 0) { identifyBorders = false; }
  27557. var i;
  27558. if (!identifyBorders) {
  27559. var newTrianglesVector = [];
  27560. for (i = 0; i < this.triangles.length; ++i) {
  27561. if (!this.triangles[i].deleted) {
  27562. newTrianglesVector.push(this.triangles[i]);
  27563. }
  27564. }
  27565. this.triangles = newTrianglesVector;
  27566. }
  27567. for (i = 0; i < this.vertices.length; ++i) {
  27568. this.vertices[i].triangleCount = 0;
  27569. this.vertices[i].triangleStart = 0;
  27570. }
  27571. var t;
  27572. var j;
  27573. var v;
  27574. for (i = 0; i < this.triangles.length; ++i) {
  27575. t = this.triangles[i];
  27576. for (j = 0; j < 3; ++j) {
  27577. v = this.vertices[t.vertices[j]];
  27578. v.triangleCount++;
  27579. }
  27580. }
  27581. var tStart = 0;
  27582. for (i = 0; i < this.vertices.length; ++i) {
  27583. this.vertices[i].triangleStart = tStart;
  27584. tStart += this.vertices[i].triangleCount;
  27585. this.vertices[i].triangleCount = 0;
  27586. }
  27587. var newReferences = new Array(this.triangles.length * 3);
  27588. for (i = 0; i < this.triangles.length; ++i) {
  27589. t = this.triangles[i];
  27590. for (j = 0; j < 3; ++j) {
  27591. v = this.vertices[t.vertices[j]];
  27592. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27593. v.triangleCount++;
  27594. }
  27595. }
  27596. this.references = newReferences;
  27597. if (identifyBorders) {
  27598. this.identifyBorder();
  27599. }
  27600. };
  27601. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27602. var x = point.x;
  27603. var y = point.y;
  27604. var z = point.z;
  27605. 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];
  27606. };
  27607. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27608. var q = vertex1.q.add(vertex2.q);
  27609. var border = vertex1.isBorder && vertex2.isBorder;
  27610. var error = 0;
  27611. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27612. if (qDet !== 0 && !border) {
  27613. if (!pointResult) {
  27614. pointResult = BABYLON.Vector3.Zero();
  27615. }
  27616. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27617. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27618. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27619. error = this.vertexError(q, pointResult);
  27620. //TODO this should be correctly calculated
  27621. if (normalResult) {
  27622. normalResult.copyFrom(vertex1.normal);
  27623. if (vertex1.uv)
  27624. uvResult.copyFrom(vertex1.uv);
  27625. else if (vertex1.color)
  27626. colorResult.copyFrom(vertex1.color);
  27627. }
  27628. }
  27629. else {
  27630. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27631. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27632. var error1 = this.vertexError(q, vertex1.position);
  27633. var error2 = this.vertexError(q, vertex2.position);
  27634. var error3 = this.vertexError(q, p3);
  27635. error = Math.min(error1, error2, error3);
  27636. if (error === error1) {
  27637. if (pointResult) {
  27638. pointResult.copyFrom(vertex1.position);
  27639. normalResult.copyFrom(vertex1.normal);
  27640. if (vertex1.uv)
  27641. uvResult.copyFrom(vertex1.uv);
  27642. else if (vertex1.color)
  27643. colorResult.copyFrom(vertex1.color);
  27644. }
  27645. }
  27646. else if (error === error2) {
  27647. if (pointResult) {
  27648. pointResult.copyFrom(vertex2.position);
  27649. normalResult.copyFrom(vertex2.normal);
  27650. if (vertex2.uv)
  27651. uvResult.copyFrom(vertex2.uv);
  27652. else if (vertex2.color)
  27653. colorResult.copyFrom(vertex2.color);
  27654. }
  27655. }
  27656. else {
  27657. if (pointResult) {
  27658. pointResult.copyFrom(p3);
  27659. normalResult.copyFrom(vertex1.normal);
  27660. if (vertex1.uv)
  27661. uvResult.copyFrom(vertex1.uv);
  27662. else if (vertex1.color)
  27663. colorResult.copyFrom(vertex1.color);
  27664. }
  27665. }
  27666. }
  27667. return error;
  27668. };
  27669. return QuadraticErrorSimplification;
  27670. })();
  27671. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27672. })(BABYLON || (BABYLON = {}));
  27673. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27674. (function (BABYLON) {
  27675. var Analyser = (function () {
  27676. function Analyser(scene) {
  27677. this.SMOOTHING = 0.75;
  27678. this.FFT_SIZE = 512;
  27679. this.BARGRAPHAMPLITUDE = 256;
  27680. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27681. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27682. this._scene = scene;
  27683. this._audioEngine = BABYLON.Engine.audioEngine;
  27684. if (this._audioEngine.canUseWebAudio) {
  27685. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27686. this._webAudioAnalyser.minDecibels = -140;
  27687. this._webAudioAnalyser.maxDecibels = 0;
  27688. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27689. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27690. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27691. }
  27692. }
  27693. Analyser.prototype.getFrequencyBinCount = function () {
  27694. if (this._audioEngine.canUseWebAudio) {
  27695. return this._webAudioAnalyser.frequencyBinCount;
  27696. }
  27697. else {
  27698. return 0;
  27699. }
  27700. };
  27701. Analyser.prototype.getByteFrequencyData = function () {
  27702. if (this._audioEngine.canUseWebAudio) {
  27703. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27704. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27705. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27706. }
  27707. return this._byteFreqs;
  27708. };
  27709. Analyser.prototype.getByteTimeDomainData = function () {
  27710. if (this._audioEngine.canUseWebAudio) {
  27711. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27712. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27713. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27714. }
  27715. return this._byteTime;
  27716. };
  27717. Analyser.prototype.getFloatFrequencyData = function () {
  27718. if (this._audioEngine.canUseWebAudio) {
  27719. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27720. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27721. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27722. }
  27723. return this._floatFreqs;
  27724. };
  27725. Analyser.prototype.drawDebugCanvas = function () {
  27726. var _this = this;
  27727. if (this._audioEngine.canUseWebAudio) {
  27728. if (!this._debugCanvas) {
  27729. this._debugCanvas = document.createElement("canvas");
  27730. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27731. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27732. this._debugCanvas.style.position = "absolute";
  27733. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27734. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27735. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27736. document.body.appendChild(this._debugCanvas);
  27737. this._registerFunc = function () {
  27738. _this.drawDebugCanvas();
  27739. };
  27740. this._scene.registerBeforeRender(this._registerFunc);
  27741. }
  27742. if (this._registerFunc) {
  27743. var workingArray = this.getByteFrequencyData();
  27744. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27745. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27746. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27747. var value = workingArray[i];
  27748. var percent = value / this.BARGRAPHAMPLITUDE;
  27749. var height = this.DEBUGCANVASSIZE.height * percent;
  27750. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27751. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27752. var hue = i / this.getFrequencyBinCount() * 360;
  27753. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27754. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27755. }
  27756. }
  27757. }
  27758. };
  27759. Analyser.prototype.stopDebugCanvas = function () {
  27760. if (this._debugCanvas) {
  27761. this._scene.unregisterBeforeRender(this._registerFunc);
  27762. this._registerFunc = null;
  27763. document.body.removeChild(this._debugCanvas);
  27764. this._debugCanvas = null;
  27765. this._debugCanvasContext = null;
  27766. }
  27767. };
  27768. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27769. if (this._audioEngine.canUseWebAudio) {
  27770. inputAudioNode.connect(this._webAudioAnalyser);
  27771. this._webAudioAnalyser.connect(outputAudioNode);
  27772. }
  27773. };
  27774. Analyser.prototype.dispose = function () {
  27775. if (this._audioEngine.canUseWebAudio) {
  27776. this._webAudioAnalyser.disconnect();
  27777. }
  27778. };
  27779. return Analyser;
  27780. })();
  27781. BABYLON.Analyser = Analyser;
  27782. })(BABYLON || (BABYLON = {}));
  27783. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27784. (function (BABYLON) {
  27785. var DepthRenderer = (function () {
  27786. function DepthRenderer(scene, type) {
  27787. var _this = this;
  27788. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27789. this._viewMatrix = BABYLON.Matrix.Zero();
  27790. this._projectionMatrix = BABYLON.Matrix.Zero();
  27791. this._transformMatrix = BABYLON.Matrix.Zero();
  27792. this._worldViewProjection = BABYLON.Matrix.Zero();
  27793. this._scene = scene;
  27794. var engine = scene.getEngine();
  27795. // Render target
  27796. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27797. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27798. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27799. this._depthMap.refreshRate = 1;
  27800. this._depthMap.renderParticles = false;
  27801. this._depthMap.renderList = null;
  27802. // Custom render function
  27803. var renderSubMesh = function (subMesh) {
  27804. var mesh = subMesh.getRenderingMesh();
  27805. var scene = _this._scene;
  27806. var engine = scene.getEngine();
  27807. // Culling
  27808. engine.setState(subMesh.getMaterial().backFaceCulling);
  27809. // Managing instances
  27810. var batch = mesh._getInstancesRenderList(subMesh._id);
  27811. if (batch.mustReturn) {
  27812. return;
  27813. }
  27814. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27815. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27816. engine.enableEffect(_this._effect);
  27817. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27818. var material = subMesh.getMaterial();
  27819. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27820. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27821. // Alpha test
  27822. if (material && material.needAlphaTesting()) {
  27823. var alphaTexture = material.getAlphaTestTexture();
  27824. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27825. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27826. }
  27827. // Bones
  27828. if (mesh.useBones) {
  27829. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27830. }
  27831. // Draw
  27832. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27833. }
  27834. };
  27835. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27836. var index;
  27837. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27838. renderSubMesh(opaqueSubMeshes.data[index]);
  27839. }
  27840. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27841. renderSubMesh(alphaTestSubMeshes.data[index]);
  27842. }
  27843. };
  27844. }
  27845. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27846. var defines = [];
  27847. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27848. var mesh = subMesh.getMesh();
  27849. var scene = mesh.getScene();
  27850. var material = subMesh.getMaterial();
  27851. // Alpha test
  27852. if (material && material.needAlphaTesting()) {
  27853. defines.push("#define ALPHATEST");
  27854. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27855. attribs.push(BABYLON.VertexBuffer.UVKind);
  27856. defines.push("#define UV1");
  27857. }
  27858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27859. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27860. defines.push("#define UV2");
  27861. }
  27862. }
  27863. // Bones
  27864. if (mesh.useBones) {
  27865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27867. defines.push("#define BONES");
  27868. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27869. }
  27870. // Instances
  27871. if (useInstances) {
  27872. defines.push("#define INSTANCES");
  27873. attribs.push("world0");
  27874. attribs.push("world1");
  27875. attribs.push("world2");
  27876. attribs.push("world3");
  27877. }
  27878. // Get correct effect
  27879. var join = defines.join("\n");
  27880. if (this._cachedDefines !== join) {
  27881. this._cachedDefines = join;
  27882. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27883. }
  27884. return this._effect.isReady();
  27885. };
  27886. DepthRenderer.prototype.getDepthMap = function () {
  27887. return this._depthMap;
  27888. };
  27889. // Methods
  27890. DepthRenderer.prototype.dispose = function () {
  27891. this._depthMap.dispose();
  27892. };
  27893. return DepthRenderer;
  27894. })();
  27895. BABYLON.DepthRenderer = DepthRenderer;
  27896. })(BABYLON || (BABYLON = {}));
  27897. //# sourceMappingURL=babylon.depthRenderer.js.map
  27898. var BABYLON;
  27899. (function (BABYLON) {
  27900. var SSAORenderingPipeline = (function (_super) {
  27901. __extends(SSAORenderingPipeline, _super);
  27902. /**
  27903. * @constructor
  27904. * @param {string} name - The rendering pipeline name
  27905. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  27906. * @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)
  27907. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  27908. */
  27909. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27910. var _this = this;
  27911. _super.call(this, scene.getEngine(), name);
  27912. // Members
  27913. /**
  27914. * The PassPostProcess id in the pipeline that contains the original scene color
  27915. * @type {string}
  27916. */
  27917. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27918. /**
  27919. * The SSAO PostProcess id in the pipeline
  27920. * @type {string}
  27921. */
  27922. this.SSAORenderEffect = "SSAORenderEffect";
  27923. /**
  27924. * The horizontal blur PostProcess id in the pipeline
  27925. * @type {string}
  27926. */
  27927. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27928. /**
  27929. * The vertical blur PostProcess id in the pipeline
  27930. * @type {string}
  27931. */
  27932. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27933. /**
  27934. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  27935. * @type {string}
  27936. */
  27937. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27938. this._firstUpdate = true;
  27939. this._scene = scene;
  27940. // Set up assets
  27941. this._createRandomTexture();
  27942. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27943. var ssaoRatio = ratio.ssaoRatio || ratio;
  27944. var combineRatio = ratio.combineRatio || ratio;
  27945. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27946. this._createSSAOPostProcess(ssaoRatio);
  27947. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27948. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27949. this._createSSAOCombinePostProcess(combineRatio);
  27950. // Set up pipeline
  27951. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27952. return _this._originalColorPostProcess;
  27953. }, true));
  27954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27955. return _this._ssaoPostProcess;
  27956. }, true));
  27957. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27958. return _this._blurHPostProcess;
  27959. }, true));
  27960. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27961. return _this._blurVPostProcess;
  27962. }, true));
  27963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27964. return _this._ssaoCombinePostProcess;
  27965. }, true));
  27966. // Finish
  27967. scene.postProcessRenderPipelineManager.addPipeline(this);
  27968. if (cameras)
  27969. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27970. }
  27971. // Public Methods
  27972. /**
  27973. * Returns the horizontal blur PostProcess
  27974. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  27975. */
  27976. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27977. return this._blurHPostProcess;
  27978. };
  27979. /**
  27980. * Returns the vertical blur PostProcess
  27981. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  27982. */
  27983. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27984. return this._blurVPostProcess;
  27985. };
  27986. /**
  27987. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  27988. */
  27989. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  27990. if (disableDepthRender === void 0) { disableDepthRender = false; }
  27991. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  27992. this._originalColorPostProcess = undefined;
  27993. this._ssaoPostProcess = undefined;
  27994. this._blurHPostProcess = undefined;
  27995. this._blurVPostProcess = undefined;
  27996. this._ssaoCombinePostProcess = undefined;
  27997. this._randomTexture.dispose();
  27998. if (disableDepthRender)
  27999. this._scene.disableDepthRenderer();
  28000. };
  28001. // Private Methods
  28002. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28003. var _this = this;
  28004. var sampleSphere = [
  28005. 0.5381,
  28006. 0.1856,
  28007. -0.4319,
  28008. 0.1379,
  28009. 0.2486,
  28010. 0.4430,
  28011. 0.3371,
  28012. 0.5679,
  28013. -0.0057,
  28014. -0.6999,
  28015. -0.0451,
  28016. -0.0019,
  28017. 0.0689,
  28018. -0.1598,
  28019. -0.8547,
  28020. 0.0560,
  28021. 0.0069,
  28022. -0.1843,
  28023. -0.0146,
  28024. 0.1402,
  28025. 0.0762,
  28026. 0.0100,
  28027. -0.1924,
  28028. -0.0344,
  28029. -0.3577,
  28030. -0.5301,
  28031. -0.4358,
  28032. -0.3169,
  28033. 0.1063,
  28034. 0.0158,
  28035. 0.0103,
  28036. -0.5869,
  28037. 0.0046,
  28038. -0.0897,
  28039. -0.4940,
  28040. 0.3287,
  28041. 0.7119,
  28042. -0.0154,
  28043. -0.0918,
  28044. -0.0533,
  28045. 0.0596,
  28046. -0.5411,
  28047. 0.0352,
  28048. -0.0631,
  28049. 0.5460,
  28050. -0.4776,
  28051. 0.2847,
  28052. -0.0271
  28053. ];
  28054. var samplesFactor = 1.0 / 16.0;
  28055. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28056. this._ssaoPostProcess.onApply = function (effect) {
  28057. if (_this._firstUpdate) {
  28058. effect.setArray3("sampleSphere", sampleSphere);
  28059. effect.setFloat("samplesFactor", samplesFactor);
  28060. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28061. _this._firstUpdate = false;
  28062. }
  28063. effect.setTexture("textureSampler", _this._depthTexture);
  28064. effect.setTexture("randomSampler", _this._randomTexture);
  28065. };
  28066. };
  28067. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28068. var _this = this;
  28069. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28070. this._ssaoCombinePostProcess.onApply = function (effect) {
  28071. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28072. };
  28073. };
  28074. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28075. var size = 512;
  28076. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28077. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28078. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28079. var context = this._randomTexture.getContext();
  28080. var rand = function (min, max) {
  28081. return Math.random() * (max - min) + min;
  28082. };
  28083. for (var x = 0; x < size; x++) {
  28084. for (var y = 0; y < size; y++) {
  28085. var randVector = BABYLON.Vector3.Zero();
  28086. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28087. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28088. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28089. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28090. context.fillRect(x, y, 1, 1);
  28091. }
  28092. }
  28093. this._randomTexture.update(false);
  28094. };
  28095. return SSAORenderingPipeline;
  28096. })(BABYLON.PostProcessRenderPipeline);
  28097. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28098. })(BABYLON || (BABYLON = {}));
  28099. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28100. var BABYLON;
  28101. (function (BABYLON) {
  28102. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28103. var VolumetricLightScatteringPostProcess = (function (_super) {
  28104. __extends(VolumetricLightScatteringPostProcess, _super);
  28105. /**
  28106. * @constructor
  28107. * @param {string} name - The post-process name
  28108. * @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)
  28109. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28110. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28111. * @param {number} samples - The post-process quality, default 100
  28112. * @param {number} samplingMode - The post-process filtering mode
  28113. * @param {BABYLON.Engine} engine - The babylon engine
  28114. * @param {boolean} reusable - If the post-process is reusable
  28115. */
  28116. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28117. var _this = this;
  28118. if (samples === void 0) { samples = 100; }
  28119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28120. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28121. this._screenCoordinates = BABYLON.Vector2.Zero();
  28122. /**
  28123. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28124. * @type {boolean}
  28125. */
  28126. this.useCustomMeshPosition = false;
  28127. /**
  28128. * If the post-process should inverse the light scattering direction
  28129. * @type {boolean}
  28130. */
  28131. this.invert = true;
  28132. /**
  28133. * Array containing the excluded meshes not rendered in the internal pass
  28134. */
  28135. this.excludedMeshes = new Array();
  28136. this.exposure = 0.3;
  28137. this.decay = 0.96815;
  28138. this.weight = 0.58767;
  28139. this.density = 0.926;
  28140. var scene = camera.getScene();
  28141. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28142. // Configure mesh
  28143. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28144. // Configure
  28145. this._createPass(scene, ratio.passRatio || ratio);
  28146. this.onApply = function (effect) {
  28147. _this._updateMeshScreenCoordinates(scene);
  28148. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28149. effect.setFloat("exposure", _this.exposure);
  28150. effect.setFloat("decay", _this.decay);
  28151. effect.setFloat("weight", _this.weight);
  28152. effect.setFloat("density", _this.density);
  28153. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28154. };
  28155. }
  28156. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28157. var mesh = subMesh.getMesh();
  28158. var defines = [];
  28159. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28160. var material = subMesh.getMaterial();
  28161. // Render this.mesh as default
  28162. if (mesh === this.mesh) {
  28163. defines.push("#define BASIC_RENDER");
  28164. }
  28165. // Alpha test
  28166. if (material) {
  28167. if (material.needAlphaTesting() || mesh === this.mesh)
  28168. defines.push("#define ALPHATEST");
  28169. if (material.opacityTexture !== undefined)
  28170. defines.push("#define OPACITY");
  28171. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28172. attribs.push(BABYLON.VertexBuffer.UVKind);
  28173. defines.push("#define UV1");
  28174. }
  28175. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28176. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28177. defines.push("#define UV2");
  28178. }
  28179. }
  28180. // Bones
  28181. if (mesh.useBones) {
  28182. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28183. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28184. defines.push("#define BONES");
  28185. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28186. }
  28187. // Instances
  28188. if (useInstances) {
  28189. defines.push("#define INSTANCES");
  28190. attribs.push("world0");
  28191. attribs.push("world1");
  28192. attribs.push("world2");
  28193. attribs.push("world3");
  28194. }
  28195. // Get correct effect
  28196. var join = defines.join("\n");
  28197. if (this._cachedDefines !== join) {
  28198. this._cachedDefines = join;
  28199. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28200. }
  28201. return this._volumetricLightScatteringPass.isReady();
  28202. };
  28203. /**
  28204. * Sets the new light position for light scattering effect
  28205. * @param {BABYLON.Vector3} The new custom light position
  28206. */
  28207. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28208. this._customMeshPosition = position;
  28209. };
  28210. /**
  28211. * Returns the light position for light scattering effect
  28212. * @return {BABYLON.Vector3} The custom light position
  28213. */
  28214. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28215. return this._customMeshPosition;
  28216. };
  28217. /**
  28218. * Disposes the internal assets and detaches the post-process from the camera
  28219. */
  28220. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28221. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28222. if (rttIndex !== -1) {
  28223. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28224. }
  28225. this._volumetricLightScatteringRTT.dispose();
  28226. _super.prototype.dispose.call(this, camera);
  28227. };
  28228. /**
  28229. * Returns the render target texture used by the post-process
  28230. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28231. */
  28232. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28233. return this._volumetricLightScatteringRTT;
  28234. };
  28235. // Private methods
  28236. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28237. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28238. return true;
  28239. }
  28240. return false;
  28241. };
  28242. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28243. var _this = this;
  28244. var engine = scene.getEngine();
  28245. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28246. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28247. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28248. this._volumetricLightScatteringRTT.renderList = null;
  28249. this._volumetricLightScatteringRTT.renderParticles = false;
  28250. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28251. // Custom render function for submeshes
  28252. var renderSubMesh = function (subMesh) {
  28253. var mesh = subMesh.getRenderingMesh();
  28254. if (_this._meshExcluded(mesh)) {
  28255. return;
  28256. }
  28257. var scene = mesh.getScene();
  28258. var engine = scene.getEngine();
  28259. // Culling
  28260. engine.setState(subMesh.getMaterial().backFaceCulling);
  28261. // Managing instances
  28262. var batch = mesh._getInstancesRenderList(subMesh._id);
  28263. if (batch.mustReturn) {
  28264. return;
  28265. }
  28266. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28267. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28268. engine.enableEffect(_this._volumetricLightScatteringPass);
  28269. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28270. var material = subMesh.getMaterial();
  28271. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28272. // Alpha test
  28273. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28274. var alphaTexture = material.getAlphaTestTexture();
  28275. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28276. if (_this.mesh.material && alphaTexture)
  28277. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28278. if (material.opacityTexture !== undefined)
  28279. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28280. }
  28281. // Bones
  28282. if (mesh.useBones) {
  28283. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28284. }
  28285. // Draw
  28286. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28287. }
  28288. };
  28289. // Render target texture callbacks
  28290. var savedSceneClearColor;
  28291. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28292. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28293. savedSceneClearColor = scene.clearColor;
  28294. scene.clearColor = sceneClearColor;
  28295. };
  28296. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28297. scene.clearColor = savedSceneClearColor;
  28298. };
  28299. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28300. var index;
  28301. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28302. renderSubMesh(opaqueSubMeshes.data[index]);
  28303. }
  28304. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28305. renderSubMesh(alphaTestSubMeshes.data[index]);
  28306. }
  28307. for (index = 0; index < transparentSubMeshes.length; index++) {
  28308. renderSubMesh(transparentSubMeshes.data[index]);
  28309. }
  28310. };
  28311. };
  28312. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28313. var transform = scene.getTransformMatrix();
  28314. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28315. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28316. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28317. if (this.invert)
  28318. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28319. };
  28320. // Static methods
  28321. /**
  28322. * Creates a default mesh for the Volumeric Light Scattering post-process
  28323. * @param {string} The mesh name
  28324. * @param {BABYLON.Scene} The scene where to create the mesh
  28325. * @return {BABYLON.Mesh} the default mesh
  28326. */
  28327. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28328. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28329. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28330. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28331. return mesh;
  28332. };
  28333. return VolumetricLightScatteringPostProcess;
  28334. })(BABYLON.PostProcess);
  28335. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28336. })(BABYLON || (BABYLON = {}));
  28337. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  28338. var BABYLON;
  28339. (function (BABYLON) {
  28340. var LensRenderingPipeline = (function (_super) {
  28341. __extends(LensRenderingPipeline, _super);
  28342. /**
  28343. * @constructor
  28344. * @param {string} name - The rendering pipeline name
  28345. * @param {object} parameters - An object containing all parameters (see below)
  28346. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28347. * @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)
  28348. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28349. Effect parameters are as follow:
  28350. {
  28351. chromatic_aberration: number; // from 0 to x (1 for realism)
  28352. edge_blur: number; // from 0 to x (1 for realism)
  28353. distortion: number; // from 0 to x (1 for realism)
  28354. grain_amount: number; // from 0 to 1
  28355. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  28356. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  28357. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  28358. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  28359. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  28360. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  28361. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  28362. }
  28363. Note: if an effect parameter is unset, effect is disabled
  28364. */
  28365. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  28366. var _this = this;
  28367. if (ratio === void 0) { ratio = 1.0; }
  28368. _super.call(this, scene.getEngine(), name);
  28369. // Lens effects can be of the following:
  28370. // - chromatic aberration (slight shift of RGB colors)
  28371. // - blur on the edge of the lens
  28372. // - lens distortion
  28373. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  28374. // - grain/dust-on-lens effect
  28375. // Two additional texture samplers are needed:
  28376. // - depth map (for depth-of-field)
  28377. // - grain texture
  28378. /**
  28379. * The chromatic aberration PostProcess id in the pipeline
  28380. * @type {string}
  28381. */
  28382. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  28383. /**
  28384. * The depth-of-field PostProcess id in the pipeline
  28385. * @type {string}
  28386. */
  28387. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  28388. this._scene = scene;
  28389. // Fetch texture samplers
  28390. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28391. if (parameters.grain_texture) {
  28392. this._grainTexture = parameters.grain_texture;
  28393. }
  28394. else {
  28395. this._createGrainTexture();
  28396. }
  28397. // save parameters
  28398. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  28399. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  28400. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  28401. this._distortion = parameters.distortion ? parameters.distortion : 0;
  28402. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  28403. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  28404. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  28405. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  28406. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  28407. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  28408. // Create effects
  28409. this._createChromaticAberrationPostProcess(ratio);
  28410. this._createDepthOfFieldPostProcess(ratio);
  28411. // Set up pipeline
  28412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  28413. return _this._chromaticAberrationPostProcess;
  28414. }, true));
  28415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  28416. return _this._depthOfFieldPostProcess;
  28417. }, true));
  28418. // Finish
  28419. scene.postProcessRenderPipelineManager.addPipeline(this);
  28420. if (cameras) {
  28421. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28422. }
  28423. }
  28424. // public methods
  28425. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  28426. this._edgeBlur = amount;
  28427. };
  28428. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  28429. this._edgeBlur = 0;
  28430. };
  28431. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  28432. this._grainAmount = amount;
  28433. };
  28434. LensRenderingPipeline.prototype.disableGrain = function () {
  28435. this._grainAmount = 0;
  28436. };
  28437. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  28438. this._chromaticAberration = amount;
  28439. };
  28440. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  28441. this._chromaticAberration = 0;
  28442. };
  28443. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  28444. this._distortion = amount;
  28445. };
  28446. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  28447. this._distortion = 0;
  28448. };
  28449. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  28450. this._highlightsGain = amount;
  28451. };
  28452. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  28453. this._highlightsThreshold = amount;
  28454. };
  28455. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  28456. this._dofDepth = amount;
  28457. };
  28458. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  28459. this._dofDepth = -1;
  28460. };
  28461. LensRenderingPipeline.prototype.setAperture = function (amount) {
  28462. this._dofAperture = amount;
  28463. };
  28464. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  28465. this._dofPentagon = true;
  28466. };
  28467. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  28468. this._dofPentagon = false;
  28469. };
  28470. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  28471. this._blurNoise = true;
  28472. };
  28473. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  28474. this._blurNoise = false;
  28475. };
  28476. /**
  28477. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  28478. */
  28479. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28480. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28481. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28482. this._chromaticAberrationPostProcess = undefined;
  28483. this._depthOfFieldPostProcess = undefined;
  28484. this._grainTexture.dispose();
  28485. if (disableDepthRender)
  28486. this._scene.disableDepthRenderer();
  28487. };
  28488. // colors shifting and distortion
  28489. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  28490. var _this = this;
  28491. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28492. this._chromaticAberrationPostProcess.onApply = function (effect) {
  28493. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  28494. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28495. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28496. };
  28497. };
  28498. // colors shifting and distortion
  28499. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  28500. var _this = this;
  28501. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  28502. "gain",
  28503. "threshold",
  28504. "focus_depth",
  28505. "aperture",
  28506. "pentagon",
  28507. "maxZ",
  28508. "edge_blur",
  28509. "chromatic_aberration",
  28510. "distortion",
  28511. "blur_noise",
  28512. "grain_amount",
  28513. "screen_width",
  28514. "screen_height"
  28515. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28516. this._depthOfFieldPostProcess.onApply = function (effect) {
  28517. effect.setBool('pentagon', _this._dofPentagon);
  28518. effect.setBool('blur_noise', _this._blurNoise);
  28519. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  28520. effect.setFloat('grain_amount', _this._grainAmount);
  28521. effect.setTexture("depthSampler", _this._depthTexture);
  28522. effect.setTexture("grainSampler", _this._grainTexture);
  28523. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28524. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28525. effect.setFloat('distortion', _this._distortion);
  28526. effect.setFloat('focus_depth', _this._dofDepth);
  28527. effect.setFloat('aperture', _this._dofAperture);
  28528. effect.setFloat('gain', _this._highlightsGain);
  28529. effect.setFloat('threshold', _this._highlightsThreshold);
  28530. effect.setFloat('edge_blur', _this._edgeBlur);
  28531. };
  28532. };
  28533. // creates a black and white random noise texture, 512x512
  28534. LensRenderingPipeline.prototype._createGrainTexture = function () {
  28535. var size = 512;
  28536. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28537. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28538. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28539. var context = this._grainTexture.getContext();
  28540. var rand = function (min, max) {
  28541. return Math.random() * (max - min) + min;
  28542. };
  28543. var value;
  28544. for (var x = 0; x < size; x++) {
  28545. for (var y = 0; y < size; y++) {
  28546. value = Math.floor(rand(0.42, 0.58) * 255);
  28547. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  28548. context.fillRect(x, y, 1, 1);
  28549. }
  28550. }
  28551. this._grainTexture.update(false);
  28552. };
  28553. return LensRenderingPipeline;
  28554. })(BABYLON.PostProcessRenderPipeline);
  28555. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  28556. })(BABYLON || (BABYLON = {}));
  28557. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map