babylon.2.1-alpha.debug.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355
  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 matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. 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);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * 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
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. 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);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = new Array();
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = new Array();
  2418. this._distances = new Array();
  2419. this._tangents = new Array();
  2420. this._normals = new Array();
  2421. this._binormals = new Array();
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. var Curve3 = (function () {
  2499. function Curve3(points) {
  2500. this._points = points;
  2501. }
  2502. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2503. Curve3.QuadraticBezier = function (v0, v1, v2, nbPoints) {
  2504. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2505. var bez = new Array();
  2506. var step = 1 / nbPoints;
  2507. var equation = function (t, val0, val1, val2) {
  2508. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2509. return res;
  2510. };
  2511. for (var i = 0; i <= 1; i += step) {
  2512. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2513. }
  2514. return new Curve3(bez);
  2515. };
  2516. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2517. Curve3.CubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2518. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2519. var bez = new Array();
  2520. var step = 1 / nbPoints;
  2521. var equation = function (t, val0, val1, val2, val3) {
  2522. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2523. return res;
  2524. };
  2525. for (var i = 0; i <= 1; i += step) {
  2526. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2527. }
  2528. return new Curve3(bez);
  2529. };
  2530. Curve3.prototype.getPoints = function () {
  2531. return this._points;
  2532. };
  2533. return Curve3;
  2534. })();
  2535. BABYLON.Curve3 = Curve3;
  2536. })(BABYLON || (BABYLON = {}));
  2537. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2538. (function (BABYLON) {
  2539. // Screenshots
  2540. var screenshotCanvas;
  2541. var cloneValue = function (source, destinationObject) {
  2542. if (!source)
  2543. return null;
  2544. if (source instanceof BABYLON.Mesh) {
  2545. return null;
  2546. }
  2547. if (source instanceof BABYLON.SubMesh) {
  2548. return source.clone(destinationObject);
  2549. }
  2550. else if (source.clone) {
  2551. return source.clone();
  2552. }
  2553. return null;
  2554. };
  2555. var Tools = (function () {
  2556. function Tools() {
  2557. }
  2558. Tools.GetFilename = function (path) {
  2559. var index = path.lastIndexOf("/");
  2560. if (index < 0)
  2561. return path;
  2562. return path.substring(index + 1);
  2563. };
  2564. Tools.GetDOMTextContent = function (element) {
  2565. var result = "";
  2566. var child = element.firstChild;
  2567. while (child) {
  2568. if (child.nodeType === 3) {
  2569. result += child.textContent;
  2570. }
  2571. child = child.nextSibling;
  2572. }
  2573. return result;
  2574. };
  2575. Tools.ToDegrees = function (angle) {
  2576. return angle * 180 / Math.PI;
  2577. };
  2578. Tools.ToRadians = function (angle) {
  2579. return angle * Math.PI / 180;
  2580. };
  2581. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2582. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2583. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2584. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2585. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2586. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2587. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2588. }
  2589. return {
  2590. minimum: minimum,
  2591. maximum: maximum
  2592. };
  2593. };
  2594. Tools.ExtractMinAndMax = function (positions, start, count) {
  2595. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2596. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2597. for (var index = start; index < start + count; index++) {
  2598. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2599. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2600. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2601. }
  2602. return {
  2603. minimum: minimum,
  2604. maximum: maximum
  2605. };
  2606. };
  2607. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2608. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2609. return undefined;
  2610. return Array.isArray(obj) ? obj : [obj];
  2611. };
  2612. // Misc.
  2613. Tools.GetPointerPrefix = function () {
  2614. var eventPrefix = "pointer";
  2615. // Check if hand.js is referenced or if the browser natively supports pointer events
  2616. if (!navigator.pointerEnabled) {
  2617. eventPrefix = "mouse";
  2618. }
  2619. return eventPrefix;
  2620. };
  2621. Tools.QueueNewFrame = function (func) {
  2622. if (window.requestAnimationFrame)
  2623. window.requestAnimationFrame(func);
  2624. else if (window.msRequestAnimationFrame)
  2625. window.msRequestAnimationFrame(func);
  2626. else if (window.webkitRequestAnimationFrame)
  2627. window.webkitRequestAnimationFrame(func);
  2628. else if (window.mozRequestAnimationFrame)
  2629. window.mozRequestAnimationFrame(func);
  2630. else if (window.oRequestAnimationFrame)
  2631. window.oRequestAnimationFrame(func);
  2632. else {
  2633. window.setTimeout(func, 16);
  2634. }
  2635. };
  2636. Tools.RequestFullscreen = function (element) {
  2637. if (element.requestFullscreen)
  2638. element.requestFullscreen();
  2639. else if (element.msRequestFullscreen)
  2640. element.msRequestFullscreen();
  2641. else if (element.webkitRequestFullscreen)
  2642. element.webkitRequestFullscreen();
  2643. else if (element.mozRequestFullScreen)
  2644. element.mozRequestFullScreen();
  2645. };
  2646. Tools.ExitFullscreen = function () {
  2647. if (document.exitFullscreen) {
  2648. document.exitFullscreen();
  2649. }
  2650. else if (document.mozCancelFullScreen) {
  2651. document.mozCancelFullScreen();
  2652. }
  2653. else if (document.webkitCancelFullScreen) {
  2654. document.webkitCancelFullScreen();
  2655. }
  2656. else if (document.msCancelFullScreen) {
  2657. document.msCancelFullScreen();
  2658. }
  2659. };
  2660. // External files
  2661. Tools.CleanUrl = function (url) {
  2662. url = url.replace(/#/mg, "%23");
  2663. return url;
  2664. };
  2665. Tools.LoadImage = function (url, onload, onerror, database) {
  2666. url = Tools.CleanUrl(url);
  2667. var img = new Image();
  2668. if (url.substr(0, 5) !== "data:")
  2669. img.crossOrigin = 'anonymous';
  2670. img.onload = function () {
  2671. onload(img);
  2672. };
  2673. img.onerror = function (err) {
  2674. onerror(img, err);
  2675. };
  2676. var noIndexedDB = function () {
  2677. img.src = url;
  2678. };
  2679. var loadFromIndexedDB = function () {
  2680. database.loadImageFromDB(url, img);
  2681. };
  2682. //ANY database to do!
  2683. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2684. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2685. }
  2686. else {
  2687. if (url.indexOf("file:") === -1) {
  2688. noIndexedDB();
  2689. }
  2690. else {
  2691. try {
  2692. var textureName = url.substring(5);
  2693. var blobURL;
  2694. try {
  2695. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2696. }
  2697. catch (ex) {
  2698. // Chrome doesn't support oneTimeOnly parameter
  2699. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2700. }
  2701. img.src = blobURL;
  2702. }
  2703. catch (e) {
  2704. Tools.Log("Error while trying to load texture: " + textureName);
  2705. img.src = null;
  2706. }
  2707. }
  2708. }
  2709. return img;
  2710. };
  2711. //ANY
  2712. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2713. url = Tools.CleanUrl(url);
  2714. var noIndexedDB = function () {
  2715. var request = new XMLHttpRequest();
  2716. var loadUrl = Tools.BaseUrl + url;
  2717. request.open('GET', loadUrl, true);
  2718. if (useArrayBuffer) {
  2719. request.responseType = "arraybuffer";
  2720. }
  2721. request.onprogress = progressCallBack;
  2722. request.onreadystatechange = function () {
  2723. if (request.readyState === 4) {
  2724. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2725. callback(!useArrayBuffer ? request.responseText : request.response);
  2726. }
  2727. else {
  2728. if (onError) {
  2729. onError();
  2730. }
  2731. else {
  2732. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2733. }
  2734. }
  2735. }
  2736. };
  2737. request.send(null);
  2738. };
  2739. var loadFromIndexedDB = function () {
  2740. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2741. };
  2742. if (url.indexOf("file:") !== -1) {
  2743. var fileName = url.substring(5);
  2744. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2745. }
  2746. else {
  2747. // Caching all files
  2748. if (database && database.enableSceneOffline) {
  2749. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2750. }
  2751. else {
  2752. noIndexedDB();
  2753. }
  2754. }
  2755. };
  2756. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2757. var reader = new FileReader();
  2758. reader.onload = function (e) {
  2759. //target doesn't have result from ts 1.3
  2760. callback(e.target['result']);
  2761. };
  2762. reader.onprogress = progressCallback;
  2763. reader.readAsDataURL(fileToLoad);
  2764. };
  2765. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2766. var reader = new FileReader();
  2767. reader.onerror = function (e) {
  2768. Tools.Log("Error while reading file: " + fileToLoad.name);
  2769. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2770. };
  2771. reader.onload = function (e) {
  2772. //target doesn't have result from ts 1.3
  2773. callback(e.target['result']);
  2774. };
  2775. reader.onprogress = progressCallBack;
  2776. if (!useArrayBuffer) {
  2777. // Asynchronous read
  2778. reader.readAsText(fileToLoad);
  2779. }
  2780. else {
  2781. reader.readAsArrayBuffer(fileToLoad);
  2782. }
  2783. };
  2784. // Misc.
  2785. Tools.Clamp = function (value, min, max) {
  2786. if (min === void 0) { min = 0; }
  2787. if (max === void 0) { max = 1; }
  2788. return Math.min(max, Math.max(min, value));
  2789. };
  2790. // Returns -1 when value is a negative number and
  2791. // +1 when value is a positive number.
  2792. Tools.Sign = function (value) {
  2793. value = +value; // convert to a number
  2794. if (value === 0 || isNaN(value))
  2795. return value;
  2796. return value > 0 ? 1 : -1;
  2797. };
  2798. Tools.Format = function (value, decimals) {
  2799. if (decimals === void 0) { decimals = 2; }
  2800. return value.toFixed(decimals);
  2801. };
  2802. Tools.CheckExtends = function (v, min, max) {
  2803. if (v.x < min.x)
  2804. min.x = v.x;
  2805. if (v.y < min.y)
  2806. min.y = v.y;
  2807. if (v.z < min.z)
  2808. min.z = v.z;
  2809. if (v.x > max.x)
  2810. max.x = v.x;
  2811. if (v.y > max.y)
  2812. max.y = v.y;
  2813. if (v.z > max.z)
  2814. max.z = v.z;
  2815. };
  2816. Tools.WithinEpsilon = function (a, b, epsilon) {
  2817. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2818. var num = a - b;
  2819. return -epsilon <= num && num <= epsilon;
  2820. };
  2821. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2822. for (var prop in source) {
  2823. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2824. continue;
  2825. }
  2826. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2827. continue;
  2828. }
  2829. var sourceValue = source[prop];
  2830. var typeOfSourceValue = typeof sourceValue;
  2831. if (typeOfSourceValue === "function") {
  2832. continue;
  2833. }
  2834. if (typeOfSourceValue === "object") {
  2835. if (sourceValue instanceof Array) {
  2836. destination[prop] = [];
  2837. if (sourceValue.length > 0) {
  2838. if (typeof sourceValue[0] == "object") {
  2839. for (var index = 0; index < sourceValue.length; index++) {
  2840. var clonedValue = cloneValue(sourceValue[index], destination);
  2841. if (destination[prop].indexOf(clonedValue) === -1) {
  2842. destination[prop].push(clonedValue);
  2843. }
  2844. }
  2845. }
  2846. else {
  2847. destination[prop] = sourceValue.slice(0);
  2848. }
  2849. }
  2850. }
  2851. else {
  2852. destination[prop] = cloneValue(sourceValue, destination);
  2853. }
  2854. }
  2855. else {
  2856. destination[prop] = sourceValue;
  2857. }
  2858. }
  2859. };
  2860. Tools.IsEmpty = function (obj) {
  2861. for (var i in obj) {
  2862. return false;
  2863. }
  2864. return true;
  2865. };
  2866. Tools.RegisterTopRootEvents = function (events) {
  2867. for (var index = 0; index < events.length; index++) {
  2868. var event = events[index];
  2869. window.addEventListener(event.name, event.handler, false);
  2870. try {
  2871. if (window.parent) {
  2872. window.parent.addEventListener(event.name, event.handler, false);
  2873. }
  2874. }
  2875. catch (e) {
  2876. }
  2877. }
  2878. };
  2879. Tools.UnregisterTopRootEvents = function (events) {
  2880. for (var index = 0; index < events.length; index++) {
  2881. var event = events[index];
  2882. window.removeEventListener(event.name, event.handler);
  2883. try {
  2884. if (window.parent) {
  2885. window.parent.removeEventListener(event.name, event.handler);
  2886. }
  2887. }
  2888. catch (e) {
  2889. }
  2890. }
  2891. };
  2892. Tools.DumpFramebuffer = function (width, height, engine) {
  2893. // Read the contents of the framebuffer
  2894. var numberOfChannelsByLine = width * 4;
  2895. var halfHeight = height / 2;
  2896. //Reading datas from WebGL
  2897. var data = engine.readPixels(0, 0, width, height);
  2898. for (var i = 0; i < halfHeight; i++) {
  2899. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2900. var currentCell = j + i * numberOfChannelsByLine;
  2901. var targetLine = height - i - 1;
  2902. var targetCell = j + targetLine * numberOfChannelsByLine;
  2903. var temp = data[currentCell];
  2904. data[currentCell] = data[targetCell];
  2905. data[targetCell] = temp;
  2906. }
  2907. }
  2908. // Create a 2D canvas to store the result
  2909. if (!screenshotCanvas) {
  2910. screenshotCanvas = document.createElement('canvas');
  2911. }
  2912. screenshotCanvas.width = width;
  2913. screenshotCanvas.height = height;
  2914. var context = screenshotCanvas.getContext('2d');
  2915. // Copy the pixels to a 2D canvas
  2916. var imageData = context.createImageData(width, height);
  2917. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2918. var castData = imageData.data;
  2919. castData.set(data);
  2920. context.putImageData(imageData, 0, 0);
  2921. var base64Image = screenshotCanvas.toDataURL();
  2922. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2923. if (("download" in document.createElement("a"))) {
  2924. var a = window.document.createElement("a");
  2925. a.href = base64Image;
  2926. var date = new Date();
  2927. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2928. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2929. window.document.body.appendChild(a);
  2930. a.addEventListener("click", function () {
  2931. a.parentElement.removeChild(a);
  2932. });
  2933. a.click();
  2934. }
  2935. else {
  2936. var newWindow = window.open("");
  2937. var img = newWindow.document.createElement("img");
  2938. img.src = base64Image;
  2939. newWindow.document.body.appendChild(img);
  2940. }
  2941. };
  2942. Tools.CreateScreenshot = function (engine, camera, size) {
  2943. var width;
  2944. var height;
  2945. var scene = camera.getScene();
  2946. var previousCamera = null;
  2947. if (scene.activeCamera !== camera) {
  2948. previousCamera = scene.activeCamera;
  2949. scene.activeCamera = camera;
  2950. }
  2951. //If a precision value is specified
  2952. if (size.precision) {
  2953. width = Math.round(engine.getRenderWidth() * size.precision);
  2954. height = Math.round(width / engine.getAspectRatio(camera));
  2955. size = { width: width, height: height };
  2956. }
  2957. else if (size.width && size.height) {
  2958. width = size.width;
  2959. height = size.height;
  2960. }
  2961. else if (size.width && !size.height) {
  2962. width = size.width;
  2963. height = Math.round(width / engine.getAspectRatio(camera));
  2964. size = { width: width, height: height };
  2965. }
  2966. else if (size.height && !size.width) {
  2967. height = size.height;
  2968. width = Math.round(height * engine.getAspectRatio(camera));
  2969. size = { width: width, height: height };
  2970. }
  2971. else if (!isNaN(size)) {
  2972. height = size;
  2973. width = size;
  2974. }
  2975. else {
  2976. Tools.Error("Invalid 'size' parameter !");
  2977. return;
  2978. }
  2979. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2980. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2981. texture.renderList = scene.meshes;
  2982. texture.onAfterRender = function () {
  2983. Tools.DumpFramebuffer(width, height, engine);
  2984. };
  2985. scene.incrementRenderId();
  2986. texture.render(true);
  2987. texture.dispose();
  2988. if (previousCamera) {
  2989. scene.activeCamera = previousCamera;
  2990. }
  2991. };
  2992. // XHR response validator for local file scenario
  2993. Tools.ValidateXHRData = function (xhr, dataType) {
  2994. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2995. if (dataType === void 0) { dataType = 7; }
  2996. try {
  2997. if (dataType & 1) {
  2998. if (xhr.responseText && xhr.responseText.length > 0) {
  2999. return true;
  3000. }
  3001. else if (dataType === 1) {
  3002. return false;
  3003. }
  3004. }
  3005. if (dataType & 2) {
  3006. // Check header width and height since there is no "TGA" magic number
  3007. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3008. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3009. return true;
  3010. }
  3011. else if (dataType === 2) {
  3012. return false;
  3013. }
  3014. }
  3015. if (dataType & 4) {
  3016. // Check for the "DDS" magic number
  3017. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3018. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3019. return true;
  3020. }
  3021. else {
  3022. return false;
  3023. }
  3024. }
  3025. }
  3026. catch (e) {
  3027. }
  3028. return false;
  3029. };
  3030. Object.defineProperty(Tools, "NoneLogLevel", {
  3031. get: function () {
  3032. return Tools._NoneLogLevel;
  3033. },
  3034. enumerable: true,
  3035. configurable: true
  3036. });
  3037. Object.defineProperty(Tools, "MessageLogLevel", {
  3038. get: function () {
  3039. return Tools._MessageLogLevel;
  3040. },
  3041. enumerable: true,
  3042. configurable: true
  3043. });
  3044. Object.defineProperty(Tools, "WarningLogLevel", {
  3045. get: function () {
  3046. return Tools._WarningLogLevel;
  3047. },
  3048. enumerable: true,
  3049. configurable: true
  3050. });
  3051. Object.defineProperty(Tools, "ErrorLogLevel", {
  3052. get: function () {
  3053. return Tools._ErrorLogLevel;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. Object.defineProperty(Tools, "AllLogLevel", {
  3059. get: function () {
  3060. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3061. },
  3062. enumerable: true,
  3063. configurable: true
  3064. });
  3065. Tools._AddLogEntry = function (entry) {
  3066. Tools._LogCache = entry + Tools._LogCache;
  3067. if (Tools.OnNewCacheEntry) {
  3068. Tools.OnNewCacheEntry(entry);
  3069. }
  3070. };
  3071. Tools._FormatMessage = function (message) {
  3072. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3073. var date = new Date();
  3074. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3075. };
  3076. Tools._LogDisabled = function (message) {
  3077. // nothing to do
  3078. };
  3079. Tools._LogEnabled = function (message) {
  3080. var formattedMessage = Tools._FormatMessage(message);
  3081. console.log("BJS - " + formattedMessage);
  3082. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3083. Tools._AddLogEntry(entry);
  3084. };
  3085. Tools._WarnDisabled = function (message) {
  3086. // nothing to do
  3087. };
  3088. Tools._WarnEnabled = function (message) {
  3089. var formattedMessage = Tools._FormatMessage(message);
  3090. console.warn("BJS - " + formattedMessage);
  3091. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3092. Tools._AddLogEntry(entry);
  3093. };
  3094. Tools._ErrorDisabled = function (message) {
  3095. // nothing to do
  3096. };
  3097. Tools._ErrorEnabled = function (message) {
  3098. var formattedMessage = Tools._FormatMessage(message);
  3099. console.error("BJS - " + formattedMessage);
  3100. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3101. Tools._AddLogEntry(entry);
  3102. };
  3103. Object.defineProperty(Tools, "LogCache", {
  3104. get: function () {
  3105. return Tools._LogCache;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "LogLevels", {
  3111. set: function (level) {
  3112. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3113. Tools.Log = Tools._LogEnabled;
  3114. }
  3115. else {
  3116. Tools.Log = Tools._LogDisabled;
  3117. }
  3118. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3119. Tools.Warn = Tools._WarnEnabled;
  3120. }
  3121. else {
  3122. Tools.Warn = Tools._WarnDisabled;
  3123. }
  3124. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3125. Tools.Error = Tools._ErrorEnabled;
  3126. }
  3127. else {
  3128. Tools.Error = Tools._ErrorDisabled;
  3129. }
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3135. get: function () {
  3136. return Tools._PerformanceNoneLogLevel;
  3137. },
  3138. enumerable: true,
  3139. configurable: true
  3140. });
  3141. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3142. get: function () {
  3143. return Tools._PerformanceUserMarkLogLevel;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3149. get: function () {
  3150. return Tools._PerformanceConsoleLogLevel;
  3151. },
  3152. enumerable: true,
  3153. configurable: true
  3154. });
  3155. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3156. set: function (level) {
  3157. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3158. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3159. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3160. return;
  3161. }
  3162. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3163. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3164. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3165. return;
  3166. }
  3167. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3168. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3169. },
  3170. enumerable: true,
  3171. configurable: true
  3172. });
  3173. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3174. };
  3175. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3176. };
  3177. Tools._StartUserMark = function (counterName, condition) {
  3178. if (condition === void 0) { condition = true; }
  3179. if (!condition || !Tools._performance.mark) {
  3180. return;
  3181. }
  3182. Tools._performance.mark(counterName + "-Begin");
  3183. };
  3184. Tools._EndUserMark = function (counterName, condition) {
  3185. if (condition === void 0) { condition = true; }
  3186. if (!condition || !Tools._performance.mark) {
  3187. return;
  3188. }
  3189. Tools._performance.mark(counterName + "-End");
  3190. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3191. };
  3192. Tools._StartPerformanceConsole = function (counterName, condition) {
  3193. if (condition === void 0) { condition = true; }
  3194. if (!condition) {
  3195. return;
  3196. }
  3197. Tools._StartUserMark(counterName, condition);
  3198. if (console.time) {
  3199. console.time(counterName);
  3200. }
  3201. };
  3202. Tools._EndPerformanceConsole = function (counterName, condition) {
  3203. if (condition === void 0) { condition = true; }
  3204. if (!condition) {
  3205. return;
  3206. }
  3207. Tools._EndUserMark(counterName, condition);
  3208. if (console.time) {
  3209. console.timeEnd(counterName);
  3210. }
  3211. };
  3212. Object.defineProperty(Tools, "Now", {
  3213. get: function () {
  3214. if (window.performance && window.performance.now) {
  3215. return window.performance.now();
  3216. }
  3217. return new Date().getTime();
  3218. },
  3219. enumerable: true,
  3220. configurable: true
  3221. });
  3222. // Deprecated
  3223. Tools.GetFps = function () {
  3224. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3225. return 0;
  3226. };
  3227. Tools.BaseUrl = "";
  3228. Tools.GetExponantOfTwo = function (value, max) {
  3229. var count = 1;
  3230. do {
  3231. count *= 2;
  3232. } while (count < value);
  3233. if (count > max)
  3234. count = max;
  3235. return count;
  3236. };
  3237. // Logs
  3238. Tools._NoneLogLevel = 0;
  3239. Tools._MessageLogLevel = 1;
  3240. Tools._WarningLogLevel = 2;
  3241. Tools._ErrorLogLevel = 4;
  3242. Tools._LogCache = "";
  3243. Tools.Log = Tools._LogEnabled;
  3244. Tools.Warn = Tools._WarnEnabled;
  3245. Tools.Error = Tools._ErrorEnabled;
  3246. // Performances
  3247. Tools._PerformanceNoneLogLevel = 0;
  3248. Tools._PerformanceUserMarkLogLevel = 1;
  3249. Tools._PerformanceConsoleLogLevel = 2;
  3250. Tools._performance = window.performance;
  3251. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3252. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3253. return Tools;
  3254. })();
  3255. BABYLON.Tools = Tools;
  3256. /**
  3257. * An implementation of a loop for asynchronous functions.
  3258. */
  3259. var AsyncLoop = (function () {
  3260. /**
  3261. * Constroctor.
  3262. * @param iterations the number of iterations.
  3263. * @param _fn the function to run each iteration
  3264. * @param _successCallback the callback that will be called upon succesful execution
  3265. * @param offset starting offset.
  3266. */
  3267. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3268. if (offset === void 0) { offset = 0; }
  3269. this.iterations = iterations;
  3270. this._fn = _fn;
  3271. this._successCallback = _successCallback;
  3272. this.index = offset - 1;
  3273. this._done = false;
  3274. }
  3275. /**
  3276. * Execute the next iteration. Must be called after the last iteration was finished.
  3277. */
  3278. AsyncLoop.prototype.executeNext = function () {
  3279. if (!this._done) {
  3280. if (this.index + 1 < this.iterations) {
  3281. ++this.index;
  3282. this._fn(this);
  3283. }
  3284. else {
  3285. this.breakLoop();
  3286. }
  3287. }
  3288. };
  3289. /**
  3290. * Break the loop and run the success callback.
  3291. */
  3292. AsyncLoop.prototype.breakLoop = function () {
  3293. this._done = true;
  3294. this._successCallback();
  3295. };
  3296. /**
  3297. * Helper function
  3298. */
  3299. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3300. if (offset === void 0) { offset = 0; }
  3301. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3302. loop.executeNext();
  3303. return loop;
  3304. };
  3305. /**
  3306. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3307. * @param iterations total number of iterations
  3308. * @param syncedIterations number of synchronous iterations in each async iteration.
  3309. * @param fn the function to call each iteration.
  3310. * @param callback a success call back that will be called when iterating stops.
  3311. * @param breakFunction a break condition (optional)
  3312. * @param timeout timeout settings for the setTimeout function. default - 0.
  3313. * @constructor
  3314. */
  3315. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3316. if (timeout === void 0) { timeout = 0; }
  3317. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3318. if (breakFunction && breakFunction())
  3319. loop.breakLoop();
  3320. else {
  3321. setTimeout(function () {
  3322. for (var i = 0; i < syncedIterations; ++i) {
  3323. var iteration = (loop.index * syncedIterations) + i;
  3324. if (iteration >= iterations)
  3325. break;
  3326. fn(iteration);
  3327. if (breakFunction && breakFunction()) {
  3328. loop.breakLoop();
  3329. break;
  3330. }
  3331. }
  3332. loop.executeNext();
  3333. }, timeout);
  3334. }
  3335. }, callback);
  3336. };
  3337. return AsyncLoop;
  3338. })();
  3339. BABYLON.AsyncLoop = AsyncLoop;
  3340. })(BABYLON || (BABYLON = {}));
  3341. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3342. (function (BABYLON) {
  3343. var _DepthCullingState = (function () {
  3344. function _DepthCullingState() {
  3345. this._isDepthTestDirty = false;
  3346. this._isDepthMaskDirty = false;
  3347. this._isDepthFuncDirty = false;
  3348. this._isCullFaceDirty = false;
  3349. this._isCullDirty = false;
  3350. }
  3351. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3352. get: function () {
  3353. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3354. },
  3355. enumerable: true,
  3356. configurable: true
  3357. });
  3358. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3359. get: function () {
  3360. return this._cullFace;
  3361. },
  3362. set: function (value) {
  3363. if (this._cullFace === value) {
  3364. return;
  3365. }
  3366. this._cullFace = value;
  3367. this._isCullFaceDirty = true;
  3368. },
  3369. enumerable: true,
  3370. configurable: true
  3371. });
  3372. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3373. get: function () {
  3374. return this._cull;
  3375. },
  3376. set: function (value) {
  3377. if (this._cull === value) {
  3378. return;
  3379. }
  3380. this._cull = value;
  3381. this._isCullDirty = true;
  3382. },
  3383. enumerable: true,
  3384. configurable: true
  3385. });
  3386. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3387. get: function () {
  3388. return this._depthFunc;
  3389. },
  3390. set: function (value) {
  3391. if (this._depthFunc === value) {
  3392. return;
  3393. }
  3394. this._depthFunc = value;
  3395. this._isDepthFuncDirty = true;
  3396. },
  3397. enumerable: true,
  3398. configurable: true
  3399. });
  3400. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3401. get: function () {
  3402. return this._depthMask;
  3403. },
  3404. set: function (value) {
  3405. if (this._depthMask === value) {
  3406. return;
  3407. }
  3408. this._depthMask = value;
  3409. this._isDepthMaskDirty = true;
  3410. },
  3411. enumerable: true,
  3412. configurable: true
  3413. });
  3414. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3415. get: function () {
  3416. return this._depthTest;
  3417. },
  3418. set: function (value) {
  3419. if (this._depthTest === value) {
  3420. return;
  3421. }
  3422. this._depthTest = value;
  3423. this._isDepthTestDirty = true;
  3424. },
  3425. enumerable: true,
  3426. configurable: true
  3427. });
  3428. _DepthCullingState.prototype.reset = function () {
  3429. this._depthMask = true;
  3430. this._depthTest = true;
  3431. this._depthFunc = null;
  3432. this._cull = null;
  3433. this._cullFace = null;
  3434. this._isDepthTestDirty = true;
  3435. this._isDepthMaskDirty = true;
  3436. this._isDepthFuncDirty = false;
  3437. this._isCullFaceDirty = false;
  3438. this._isCullDirty = false;
  3439. };
  3440. _DepthCullingState.prototype.apply = function (gl) {
  3441. if (!this.isDirty) {
  3442. return;
  3443. }
  3444. // Cull
  3445. if (this._isCullDirty) {
  3446. if (this.cull) {
  3447. gl.enable(gl.CULL_FACE);
  3448. }
  3449. else {
  3450. gl.disable(gl.CULL_FACE);
  3451. }
  3452. this._isCullDirty = false;
  3453. }
  3454. // Cull face
  3455. if (this._isCullFaceDirty) {
  3456. gl.cullFace(this.cullFace);
  3457. this._isCullFaceDirty = false;
  3458. }
  3459. // Depth mask
  3460. if (this._isDepthMaskDirty) {
  3461. gl.depthMask(this.depthMask);
  3462. this._isDepthMaskDirty = false;
  3463. }
  3464. // Depth test
  3465. if (this._isDepthTestDirty) {
  3466. if (this.depthTest) {
  3467. gl.enable(gl.DEPTH_TEST);
  3468. }
  3469. else {
  3470. gl.disable(gl.DEPTH_TEST);
  3471. }
  3472. this._isDepthTestDirty = false;
  3473. }
  3474. // Depth func
  3475. if (this._isDepthFuncDirty) {
  3476. gl.depthFunc(this.depthFunc);
  3477. this._isDepthFuncDirty = false;
  3478. }
  3479. };
  3480. return _DepthCullingState;
  3481. })();
  3482. BABYLON._DepthCullingState = _DepthCullingState;
  3483. var _AlphaState = (function () {
  3484. function _AlphaState() {
  3485. this._isAlphaBlendDirty = false;
  3486. this._isBlendFunctionParametersDirty = false;
  3487. this._alphaBlend = false;
  3488. this._blendFunctionParameters = new Array(4);
  3489. }
  3490. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3491. get: function () {
  3492. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3493. },
  3494. enumerable: true,
  3495. configurable: true
  3496. });
  3497. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3498. get: function () {
  3499. return this._alphaBlend;
  3500. },
  3501. set: function (value) {
  3502. if (this._alphaBlend === value) {
  3503. return;
  3504. }
  3505. this._alphaBlend = value;
  3506. this._isAlphaBlendDirty = true;
  3507. },
  3508. enumerable: true,
  3509. configurable: true
  3510. });
  3511. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3512. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3513. return;
  3514. }
  3515. this._blendFunctionParameters[0] = value0;
  3516. this._blendFunctionParameters[1] = value1;
  3517. this._blendFunctionParameters[2] = value2;
  3518. this._blendFunctionParameters[3] = value3;
  3519. this._isBlendFunctionParametersDirty = true;
  3520. };
  3521. _AlphaState.prototype.reset = function () {
  3522. this._alphaBlend = false;
  3523. this._blendFunctionParameters[0] = null;
  3524. this._blendFunctionParameters[1] = null;
  3525. this._blendFunctionParameters[2] = null;
  3526. this._blendFunctionParameters[3] = null;
  3527. this._isAlphaBlendDirty = true;
  3528. this._isBlendFunctionParametersDirty = false;
  3529. };
  3530. _AlphaState.prototype.apply = function (gl) {
  3531. if (!this.isDirty) {
  3532. return;
  3533. }
  3534. // Alpha blend
  3535. if (this._isAlphaBlendDirty) {
  3536. if (this._alphaBlend) {
  3537. gl.enable(gl.BLEND);
  3538. }
  3539. else {
  3540. gl.disable(gl.BLEND);
  3541. }
  3542. this._isAlphaBlendDirty = false;
  3543. }
  3544. // Alpha function
  3545. if (this._isBlendFunctionParametersDirty) {
  3546. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3547. this._isBlendFunctionParametersDirty = false;
  3548. }
  3549. };
  3550. return _AlphaState;
  3551. })();
  3552. BABYLON._AlphaState = _AlphaState;
  3553. var compileShader = function (gl, source, type, defines) {
  3554. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3555. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3556. gl.compileShader(shader);
  3557. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3558. throw new Error(gl.getShaderInfoLog(shader));
  3559. }
  3560. return shader;
  3561. };
  3562. var getWebGLTextureType = function (gl, type) {
  3563. var textureType = gl.UNSIGNED_BYTE;
  3564. if (type === Engine.TEXTURETYPE_FLOAT)
  3565. textureType = gl.FLOAT;
  3566. return textureType;
  3567. };
  3568. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3569. var magFilter = gl.NEAREST;
  3570. var minFilter = gl.NEAREST;
  3571. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3572. magFilter = gl.LINEAR;
  3573. if (generateMipMaps) {
  3574. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3575. }
  3576. else {
  3577. minFilter = gl.LINEAR;
  3578. }
  3579. }
  3580. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3581. magFilter = gl.LINEAR;
  3582. if (generateMipMaps) {
  3583. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3584. }
  3585. else {
  3586. minFilter = gl.LINEAR;
  3587. }
  3588. }
  3589. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3590. magFilter = gl.NEAREST;
  3591. if (generateMipMaps) {
  3592. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3593. }
  3594. else {
  3595. minFilter = gl.NEAREST;
  3596. }
  3597. }
  3598. return {
  3599. min: minFilter,
  3600. mag: magFilter
  3601. };
  3602. };
  3603. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3605. var engine = scene.getEngine();
  3606. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3607. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3608. gl.bindTexture(gl.TEXTURE_2D, texture);
  3609. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3610. processFunction(potWidth, potHeight);
  3611. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3613. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3614. if (!noMipmap && !isCompressed) {
  3615. gl.generateMipmap(gl.TEXTURE_2D);
  3616. }
  3617. gl.bindTexture(gl.TEXTURE_2D, null);
  3618. engine._activeTexturesCache = [];
  3619. texture._baseWidth = width;
  3620. texture._baseHeight = height;
  3621. texture._width = potWidth;
  3622. texture._height = potHeight;
  3623. texture.isReady = true;
  3624. texture.samplingMode = samplingMode;
  3625. scene._removePendingData(texture);
  3626. };
  3627. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3628. var onload = function () {
  3629. loadedImages[index] = img;
  3630. loadedImages._internalCount++;
  3631. scene._removePendingData(img);
  3632. if (loadedImages._internalCount === 6) {
  3633. onfinish(loadedImages);
  3634. }
  3635. };
  3636. var onerror = function () {
  3637. scene._removePendingData(img);
  3638. };
  3639. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3640. scene._addPendingData(img);
  3641. };
  3642. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3643. var loadedImages = [];
  3644. loadedImages._internalCount = 0;
  3645. for (var index = 0; index < 6; index++) {
  3646. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3647. }
  3648. };
  3649. var EngineCapabilities = (function () {
  3650. function EngineCapabilities() {
  3651. }
  3652. return EngineCapabilities;
  3653. })();
  3654. BABYLON.EngineCapabilities = EngineCapabilities;
  3655. /**
  3656. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3657. */
  3658. var Engine = (function () {
  3659. /**
  3660. * @constructor
  3661. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3662. * @param {boolean} [antialias] - enable antialias
  3663. * @param options - further options to be sent to the getContext function
  3664. */
  3665. function Engine(canvas, antialias, options) {
  3666. var _this = this;
  3667. // Public members
  3668. this.isFullscreen = false;
  3669. this.isPointerLock = false;
  3670. this.cullBackFaces = true;
  3671. this.renderEvenInBackground = true;
  3672. this.scenes = new Array();
  3673. this._windowIsBackground = false;
  3674. this._loadingDivBackgroundColor = "black";
  3675. this._drawCalls = 0;
  3676. this._renderingQueueLaunched = false;
  3677. this._activeRenderLoops = [];
  3678. // FPS
  3679. this.fpsRange = 60;
  3680. this.previousFramesDuration = [];
  3681. this.fps = 60;
  3682. this.deltaTime = 0;
  3683. // States
  3684. this._depthCullingState = new _DepthCullingState();
  3685. this._alphaState = new _AlphaState();
  3686. this._alphaMode = Engine.ALPHA_DISABLE;
  3687. // Cache
  3688. this._loadedTexturesCache = new Array();
  3689. this._activeTexturesCache = new Array();
  3690. this._compiledEffects = {};
  3691. this._uintIndicesCurrentlySet = false;
  3692. this._renderingCanvas = canvas;
  3693. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3694. options = options || {};
  3695. options.antialias = antialias;
  3696. try {
  3697. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3698. }
  3699. catch (e) {
  3700. throw new Error("WebGL not supported");
  3701. }
  3702. if (!this._gl) {
  3703. throw new Error("WebGL not supported");
  3704. }
  3705. this._onBlur = function () {
  3706. _this._windowIsBackground = true;
  3707. };
  3708. this._onFocus = function () {
  3709. _this._windowIsBackground = false;
  3710. };
  3711. window.addEventListener("blur", this._onBlur);
  3712. window.addEventListener("focus", this._onFocus);
  3713. // Textures
  3714. this._workingCanvas = document.createElement("canvas");
  3715. this._workingContext = this._workingCanvas.getContext("2d");
  3716. // Viewport
  3717. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3718. this.resize();
  3719. // Caps
  3720. this._caps = new EngineCapabilities();
  3721. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3722. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3723. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3724. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3725. // Infos
  3726. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3727. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3728. if (rendererInfo != null) {
  3729. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3730. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3731. }
  3732. if (!this._glVendor) {
  3733. this._glVendor = "Unknown vendor";
  3734. }
  3735. if (!this._glRenderer) {
  3736. this._glRenderer = "Unknown renderer";
  3737. }
  3738. // Extensions
  3739. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3740. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3741. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3742. 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');
  3743. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3744. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3745. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3746. // Depth buffer
  3747. this.setDepthBuffer(true);
  3748. this.setDepthFunctionToLessOrEqual();
  3749. this.setDepthWrite(true);
  3750. // Fullscreen
  3751. this._onFullscreenChange = function () {
  3752. if (document.fullscreen !== undefined) {
  3753. _this.isFullscreen = document.fullscreen;
  3754. }
  3755. else if (document.mozFullScreen !== undefined) {
  3756. _this.isFullscreen = document.mozFullScreen;
  3757. }
  3758. else if (document.webkitIsFullScreen !== undefined) {
  3759. _this.isFullscreen = document.webkitIsFullScreen;
  3760. }
  3761. else if (document.msIsFullScreen !== undefined) {
  3762. _this.isFullscreen = document.msIsFullScreen;
  3763. }
  3764. // Pointer lock
  3765. if (_this.isFullscreen && _this._pointerLockRequested) {
  3766. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3767. if (canvas.requestPointerLock) {
  3768. canvas.requestPointerLock();
  3769. }
  3770. }
  3771. };
  3772. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3773. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3774. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3775. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3776. // Pointer lock
  3777. this._onPointerLockChange = function () {
  3778. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3779. };
  3780. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3781. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3782. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3783. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3784. if (!Engine.audioEngine) {
  3785. Engine.audioEngine = new BABYLON.AudioEngine();
  3786. }
  3787. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3788. }
  3789. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3790. get: function () {
  3791. return Engine._ALPHA_DISABLE;
  3792. },
  3793. enumerable: true,
  3794. configurable: true
  3795. });
  3796. Object.defineProperty(Engine, "ALPHA_ADD", {
  3797. get: function () {
  3798. return Engine._ALPHA_ADD;
  3799. },
  3800. enumerable: true,
  3801. configurable: true
  3802. });
  3803. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3804. get: function () {
  3805. return Engine._ALPHA_COMBINE;
  3806. },
  3807. enumerable: true,
  3808. configurable: true
  3809. });
  3810. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3811. get: function () {
  3812. return Engine._DELAYLOADSTATE_NONE;
  3813. },
  3814. enumerable: true,
  3815. configurable: true
  3816. });
  3817. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3818. get: function () {
  3819. return Engine._DELAYLOADSTATE_LOADED;
  3820. },
  3821. enumerable: true,
  3822. configurable: true
  3823. });
  3824. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3825. get: function () {
  3826. return Engine._DELAYLOADSTATE_LOADING;
  3827. },
  3828. enumerable: true,
  3829. configurable: true
  3830. });
  3831. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3832. get: function () {
  3833. return Engine._DELAYLOADSTATE_NOTLOADED;
  3834. },
  3835. enumerable: true,
  3836. configurable: true
  3837. });
  3838. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3839. get: function () {
  3840. return Engine._TEXTUREFORMAT_ALPHA;
  3841. },
  3842. enumerable: true,
  3843. configurable: true
  3844. });
  3845. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3846. get: function () {
  3847. return Engine._TEXTUREFORMAT_LUMINANCE;
  3848. },
  3849. enumerable: true,
  3850. configurable: true
  3851. });
  3852. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3853. get: function () {
  3854. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3855. },
  3856. enumerable: true,
  3857. configurable: true
  3858. });
  3859. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3860. get: function () {
  3861. return Engine._TEXTUREFORMAT_RGB;
  3862. },
  3863. enumerable: true,
  3864. configurable: true
  3865. });
  3866. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3867. get: function () {
  3868. return Engine._TEXTUREFORMAT_RGBA;
  3869. },
  3870. enumerable: true,
  3871. configurable: true
  3872. });
  3873. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3874. get: function () {
  3875. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3876. },
  3877. enumerable: true,
  3878. configurable: true
  3879. });
  3880. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3881. get: function () {
  3882. return Engine._TEXTURETYPE_FLOAT;
  3883. },
  3884. enumerable: true,
  3885. configurable: true
  3886. });
  3887. Object.defineProperty(Engine, "Version", {
  3888. get: function () {
  3889. return "2.1.0 alpha";
  3890. },
  3891. enumerable: true,
  3892. configurable: true
  3893. });
  3894. Engine.prototype.getGlInfo = function () {
  3895. return {
  3896. vendor: this._glVendor,
  3897. renderer: this._glRenderer,
  3898. version: this._glVersion
  3899. };
  3900. };
  3901. Engine.prototype.getAspectRatio = function (camera) {
  3902. var viewport = camera.viewport;
  3903. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3904. };
  3905. Engine.prototype.getRenderWidth = function () {
  3906. if (this._currentRenderTarget) {
  3907. return this._currentRenderTarget._width;
  3908. }
  3909. return this._renderingCanvas.width;
  3910. };
  3911. Engine.prototype.getRenderHeight = function () {
  3912. if (this._currentRenderTarget) {
  3913. return this._currentRenderTarget._height;
  3914. }
  3915. return this._renderingCanvas.height;
  3916. };
  3917. Engine.prototype.getRenderingCanvas = function () {
  3918. return this._renderingCanvas;
  3919. };
  3920. Engine.prototype.getRenderingCanvasClientRect = function () {
  3921. return this._renderingCanvas.getBoundingClientRect();
  3922. };
  3923. Engine.prototype.setHardwareScalingLevel = function (level) {
  3924. this._hardwareScalingLevel = level;
  3925. this.resize();
  3926. };
  3927. Engine.prototype.getHardwareScalingLevel = function () {
  3928. return this._hardwareScalingLevel;
  3929. };
  3930. Engine.prototype.getLoadedTexturesCache = function () {
  3931. return this._loadedTexturesCache;
  3932. };
  3933. Engine.prototype.getCaps = function () {
  3934. return this._caps;
  3935. };
  3936. Object.defineProperty(Engine.prototype, "drawCalls", {
  3937. get: function () {
  3938. return this._drawCalls;
  3939. },
  3940. enumerable: true,
  3941. configurable: true
  3942. });
  3943. // Methods
  3944. Engine.prototype.resetDrawCalls = function () {
  3945. this._drawCalls = 0;
  3946. };
  3947. Engine.prototype.setDepthFunctionToGreater = function () {
  3948. this._depthCullingState.depthFunc = this._gl.GREATER;
  3949. };
  3950. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3951. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3952. };
  3953. Engine.prototype.setDepthFunctionToLess = function () {
  3954. this._depthCullingState.depthFunc = this._gl.LESS;
  3955. };
  3956. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3957. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3958. };
  3959. /**
  3960. * stop executing a render loop function and remove it from the execution array
  3961. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3962. */
  3963. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3964. if (!renderFunction) {
  3965. this._activeRenderLoops = [];
  3966. return;
  3967. }
  3968. var index = this._activeRenderLoops.indexOf(renderFunction);
  3969. if (index >= 0) {
  3970. this._activeRenderLoops.splice(index, 1);
  3971. }
  3972. };
  3973. Engine.prototype._renderLoop = function () {
  3974. var _this = this;
  3975. var shouldRender = true;
  3976. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3977. shouldRender = false;
  3978. }
  3979. if (shouldRender) {
  3980. // Start new frame
  3981. this.beginFrame();
  3982. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3983. var renderFunction = this._activeRenderLoops[index];
  3984. renderFunction();
  3985. }
  3986. // Present
  3987. this.endFrame();
  3988. }
  3989. if (this._activeRenderLoops.length > 0) {
  3990. // Register new frame
  3991. BABYLON.Tools.QueueNewFrame(function () {
  3992. _this._renderLoop();
  3993. });
  3994. }
  3995. else {
  3996. this._renderingQueueLaunched = false;
  3997. }
  3998. };
  3999. /**
  4000. * Register and execute a render loop. The engine can have more than one render function.
  4001. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4002. * @example
  4003. * engine.runRenderLoop(function () {
  4004. * scene.render()
  4005. * })
  4006. */
  4007. Engine.prototype.runRenderLoop = function (renderFunction) {
  4008. var _this = this;
  4009. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4010. return;
  4011. }
  4012. this._activeRenderLoops.push(renderFunction);
  4013. if (!this._renderingQueueLaunched) {
  4014. this._renderingQueueLaunched = true;
  4015. BABYLON.Tools.QueueNewFrame(function () {
  4016. _this._renderLoop();
  4017. });
  4018. }
  4019. };
  4020. /**
  4021. * Toggle full screen mode.
  4022. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4023. */
  4024. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4025. if (this.isFullscreen) {
  4026. BABYLON.Tools.ExitFullscreen();
  4027. }
  4028. else {
  4029. this._pointerLockRequested = requestPointerLock;
  4030. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4031. }
  4032. };
  4033. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4034. this.applyStates();
  4035. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4036. if (this._depthCullingState.depthMask) {
  4037. this._gl.clearDepth(1.0);
  4038. }
  4039. var mode = 0;
  4040. if (backBuffer)
  4041. mode |= this._gl.COLOR_BUFFER_BIT;
  4042. if (depthStencil && this._depthCullingState.depthMask)
  4043. mode |= this._gl.DEPTH_BUFFER_BIT;
  4044. this._gl.clear(mode);
  4045. };
  4046. /**
  4047. * Set the WebGL's viewport
  4048. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4049. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4050. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4051. */
  4052. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4053. var width = requiredWidth || this._renderingCanvas.width;
  4054. var height = requiredHeight || this._renderingCanvas.height;
  4055. var x = viewport.x || 0;
  4056. var y = viewport.y || 0;
  4057. this._cachedViewport = viewport;
  4058. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4059. };
  4060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4061. this._cachedViewport = null;
  4062. this._gl.viewport(x, y, width, height);
  4063. };
  4064. Engine.prototype.beginFrame = function () {
  4065. this._measureFps();
  4066. };
  4067. Engine.prototype.endFrame = function () {
  4068. //this.flushFramebuffer();
  4069. };
  4070. /**
  4071. * resize the view according to the canvas' size.
  4072. * @example
  4073. * window.addEventListener("resize", function () {
  4074. * engine.resize();
  4075. * });
  4076. */
  4077. Engine.prototype.resize = function () {
  4078. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4079. };
  4080. /**
  4081. * force a specific size of the canvas
  4082. * @param {number} width - the new canvas' width
  4083. * @param {number} height - the new canvas' height
  4084. */
  4085. Engine.prototype.setSize = function (width, height) {
  4086. this._renderingCanvas.width = width;
  4087. this._renderingCanvas.height = height;
  4088. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4089. };
  4090. Engine.prototype.bindFramebuffer = function (texture) {
  4091. this._currentRenderTarget = texture;
  4092. var gl = this._gl;
  4093. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4094. this._gl.viewport(0, 0, texture._width, texture._height);
  4095. this.wipeCaches();
  4096. };
  4097. Engine.prototype.unBindFramebuffer = function (texture) {
  4098. this._currentRenderTarget = null;
  4099. if (texture.generateMipMaps) {
  4100. var gl = this._gl;
  4101. gl.bindTexture(gl.TEXTURE_2D, texture);
  4102. gl.generateMipmap(gl.TEXTURE_2D);
  4103. gl.bindTexture(gl.TEXTURE_2D, null);
  4104. }
  4105. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4106. };
  4107. Engine.prototype.flushFramebuffer = function () {
  4108. this._gl.flush();
  4109. };
  4110. Engine.prototype.restoreDefaultFramebuffer = function () {
  4111. this._currentRenderTarget = null;
  4112. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4113. this.setViewport(this._cachedViewport);
  4114. this.wipeCaches();
  4115. };
  4116. // VBOs
  4117. Engine.prototype._resetVertexBufferBinding = function () {
  4118. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4119. this._cachedVertexBuffers = null;
  4120. };
  4121. Engine.prototype.createVertexBuffer = function (vertices) {
  4122. var vbo = this._gl.createBuffer();
  4123. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4124. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4125. this._resetVertexBufferBinding();
  4126. vbo.references = 1;
  4127. return vbo;
  4128. };
  4129. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4130. var vbo = this._gl.createBuffer();
  4131. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4132. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4133. this._resetVertexBufferBinding();
  4134. vbo.references = 1;
  4135. return vbo;
  4136. };
  4137. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4138. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4139. if (offset === undefined) {
  4140. offset = 0;
  4141. }
  4142. if (vertices instanceof Float32Array) {
  4143. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4144. }
  4145. else {
  4146. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4147. }
  4148. this._resetVertexBufferBinding();
  4149. };
  4150. Engine.prototype._resetIndexBufferBinding = function () {
  4151. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4152. this._cachedIndexBuffer = null;
  4153. };
  4154. Engine.prototype.createIndexBuffer = function (indices) {
  4155. var vbo = this._gl.createBuffer();
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4157. // Check for 32 bits indices
  4158. var arrayBuffer;
  4159. var need32Bits = false;
  4160. if (this._caps.uintIndices) {
  4161. for (var index = 0; index < indices.length; index++) {
  4162. if (indices[index] > 65535) {
  4163. need32Bits = true;
  4164. break;
  4165. }
  4166. }
  4167. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4168. }
  4169. else {
  4170. arrayBuffer = new Uint16Array(indices);
  4171. }
  4172. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4173. this._resetIndexBufferBinding();
  4174. vbo.references = 1;
  4175. vbo.is32Bits = need32Bits;
  4176. return vbo;
  4177. };
  4178. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4179. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4180. this._cachedVertexBuffers = vertexBuffer;
  4181. this._cachedEffectForVertexBuffers = effect;
  4182. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4183. var offset = 0;
  4184. for (var index = 0; index < vertexDeclaration.length; index++) {
  4185. var order = effect.getAttributeLocation(index);
  4186. if (order >= 0) {
  4187. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4188. }
  4189. offset += vertexDeclaration[index] * 4;
  4190. }
  4191. }
  4192. if (this._cachedIndexBuffer !== indexBuffer) {
  4193. this._cachedIndexBuffer = indexBuffer;
  4194. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4195. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4196. }
  4197. };
  4198. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4199. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4200. this._cachedVertexBuffers = vertexBuffers;
  4201. this._cachedEffectForVertexBuffers = effect;
  4202. var attributes = effect.getAttributesNames();
  4203. for (var index = 0; index < attributes.length; index++) {
  4204. var order = effect.getAttributeLocation(index);
  4205. if (order >= 0) {
  4206. var vertexBuffer = vertexBuffers[attributes[index]];
  4207. if (!vertexBuffer) {
  4208. continue;
  4209. }
  4210. var stride = vertexBuffer.getStrideSize();
  4211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4212. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4213. }
  4214. }
  4215. }
  4216. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4217. this._cachedIndexBuffer = indexBuffer;
  4218. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4219. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4220. }
  4221. };
  4222. Engine.prototype._releaseBuffer = function (buffer) {
  4223. buffer.references--;
  4224. if (buffer.references === 0) {
  4225. this._gl.deleteBuffer(buffer);
  4226. return true;
  4227. }
  4228. return false;
  4229. };
  4230. Engine.prototype.createInstancesBuffer = function (capacity) {
  4231. var buffer = this._gl.createBuffer();
  4232. buffer.capacity = capacity;
  4233. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4234. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4235. return buffer;
  4236. };
  4237. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4238. this._gl.deleteBuffer(buffer);
  4239. };
  4240. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4241. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4242. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4243. for (var index = 0; index < 4; index++) {
  4244. var offsetLocation = offsetLocations[index];
  4245. this._gl.enableVertexAttribArray(offsetLocation);
  4246. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4247. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4248. }
  4249. };
  4250. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4251. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4252. for (var index = 0; index < 4; index++) {
  4253. var offsetLocation = offsetLocations[index];
  4254. this._gl.disableVertexAttribArray(offsetLocation);
  4255. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4256. }
  4257. };
  4258. Engine.prototype.applyStates = function () {
  4259. this._depthCullingState.apply(this._gl);
  4260. this._alphaState.apply(this._gl);
  4261. };
  4262. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4263. // Apply states
  4264. this.applyStates();
  4265. this._drawCalls++;
  4266. // Render
  4267. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4268. if (instancesCount) {
  4269. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4270. return;
  4271. }
  4272. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4273. };
  4274. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4275. // Apply states
  4276. this.applyStates();
  4277. this._drawCalls++;
  4278. if (instancesCount) {
  4279. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4280. return;
  4281. }
  4282. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4283. };
  4284. // Shaders
  4285. Engine.prototype._releaseEffect = function (effect) {
  4286. if (this._compiledEffects[effect._key]) {
  4287. delete this._compiledEffects[effect._key];
  4288. if (effect.getProgram()) {
  4289. this._gl.deleteProgram(effect.getProgram());
  4290. }
  4291. }
  4292. };
  4293. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4294. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4295. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4296. var name = vertex + "+" + fragment + "@" + defines;
  4297. if (this._compiledEffects[name]) {
  4298. return this._compiledEffects[name];
  4299. }
  4300. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4301. effect._key = name;
  4302. this._compiledEffects[name] = effect;
  4303. return effect;
  4304. };
  4305. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4306. if (uniformsNames === void 0) { uniformsNames = []; }
  4307. if (samplers === void 0) { samplers = []; }
  4308. if (defines === void 0) { defines = ""; }
  4309. return this.createEffect({
  4310. vertex: "particles",
  4311. fragmentElement: fragmentName
  4312. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4313. };
  4314. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4315. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4316. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4317. var shaderProgram = this._gl.createProgram();
  4318. this._gl.attachShader(shaderProgram, vertexShader);
  4319. this._gl.attachShader(shaderProgram, fragmentShader);
  4320. this._gl.linkProgram(shaderProgram);
  4321. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4322. if (!linked) {
  4323. var error = this._gl.getProgramInfoLog(shaderProgram);
  4324. if (error) {
  4325. throw new Error(error);
  4326. }
  4327. }
  4328. this._gl.deleteShader(vertexShader);
  4329. this._gl.deleteShader(fragmentShader);
  4330. return shaderProgram;
  4331. };
  4332. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4333. var results = [];
  4334. for (var index = 0; index < uniformsNames.length; index++) {
  4335. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4336. }
  4337. return results;
  4338. };
  4339. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4340. var results = [];
  4341. for (var index = 0; index < attributesNames.length; index++) {
  4342. try {
  4343. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4344. }
  4345. catch (e) {
  4346. results.push(-1);
  4347. }
  4348. }
  4349. return results;
  4350. };
  4351. Engine.prototype.enableEffect = function (effect) {
  4352. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4353. if (effect && effect.onBind) {
  4354. effect.onBind(effect);
  4355. }
  4356. return;
  4357. }
  4358. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4359. // Use program
  4360. this._gl.useProgram(effect.getProgram());
  4361. for (var i in this._vertexAttribArrays) {
  4362. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4363. continue;
  4364. }
  4365. this._vertexAttribArrays[i] = false;
  4366. this._gl.disableVertexAttribArray(i);
  4367. }
  4368. var attributesCount = effect.getAttributesCount();
  4369. for (var index = 0; index < attributesCount; index++) {
  4370. // Attributes
  4371. var order = effect.getAttributeLocation(index);
  4372. if (order >= 0) {
  4373. this._vertexAttribArrays[order] = true;
  4374. this._gl.enableVertexAttribArray(order);
  4375. }
  4376. }
  4377. this._currentEffect = effect;
  4378. if (effect.onBind) {
  4379. effect.onBind(effect);
  4380. }
  4381. };
  4382. Engine.prototype.setArray = function (uniform, array) {
  4383. if (!uniform)
  4384. return;
  4385. this._gl.uniform1fv(uniform, array);
  4386. };
  4387. Engine.prototype.setArray2 = function (uniform, array) {
  4388. if (!uniform || array.length % 2 !== 0)
  4389. return;
  4390. this._gl.uniform2fv(uniform, array);
  4391. };
  4392. Engine.prototype.setArray3 = function (uniform, array) {
  4393. if (!uniform || array.length % 3 !== 0)
  4394. return;
  4395. this._gl.uniform3fv(uniform, array);
  4396. };
  4397. Engine.prototype.setArray4 = function (uniform, array) {
  4398. if (!uniform || array.length % 4 !== 0)
  4399. return;
  4400. this._gl.uniform4fv(uniform, array);
  4401. };
  4402. Engine.prototype.setMatrices = function (uniform, matrices) {
  4403. if (!uniform)
  4404. return;
  4405. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4406. };
  4407. Engine.prototype.setMatrix = function (uniform, matrix) {
  4408. if (!uniform)
  4409. return;
  4410. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4411. };
  4412. Engine.prototype.setFloat = function (uniform, value) {
  4413. if (!uniform)
  4414. return;
  4415. this._gl.uniform1f(uniform, value);
  4416. };
  4417. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4418. if (!uniform)
  4419. return;
  4420. this._gl.uniform2f(uniform, x, y);
  4421. };
  4422. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4423. if (!uniform)
  4424. return;
  4425. this._gl.uniform3f(uniform, x, y, z);
  4426. };
  4427. Engine.prototype.setBool = function (uniform, bool) {
  4428. if (!uniform)
  4429. return;
  4430. this._gl.uniform1i(uniform, bool);
  4431. };
  4432. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4433. if (!uniform)
  4434. return;
  4435. this._gl.uniform4f(uniform, x, y, z, w);
  4436. };
  4437. Engine.prototype.setColor3 = function (uniform, color3) {
  4438. if (!uniform)
  4439. return;
  4440. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4441. };
  4442. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4443. if (!uniform)
  4444. return;
  4445. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4446. };
  4447. // States
  4448. Engine.prototype.setState = function (culling, force) {
  4449. // Culling
  4450. if (this._depthCullingState.cull !== culling || force) {
  4451. if (culling) {
  4452. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4453. this._depthCullingState.cull = true;
  4454. }
  4455. else {
  4456. this._depthCullingState.cull = false;
  4457. }
  4458. }
  4459. };
  4460. Engine.prototype.setDepthBuffer = function (enable) {
  4461. this._depthCullingState.depthTest = enable;
  4462. };
  4463. Engine.prototype.getDepthWrite = function () {
  4464. return this._depthCullingState.depthMask;
  4465. };
  4466. Engine.prototype.setDepthWrite = function (enable) {
  4467. this._depthCullingState.depthMask = enable;
  4468. };
  4469. Engine.prototype.setColorWrite = function (enable) {
  4470. this._gl.colorMask(enable, enable, enable, enable);
  4471. };
  4472. Engine.prototype.setAlphaMode = function (mode) {
  4473. switch (mode) {
  4474. case Engine.ALPHA_DISABLE:
  4475. this.setDepthWrite(true);
  4476. this._alphaState.alphaBlend = false;
  4477. break;
  4478. case Engine.ALPHA_COMBINE:
  4479. this.setDepthWrite(false);
  4480. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4481. this._alphaState.alphaBlend = true;
  4482. break;
  4483. case Engine.ALPHA_ADD:
  4484. this.setDepthWrite(false);
  4485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4486. this._alphaState.alphaBlend = true;
  4487. break;
  4488. }
  4489. this._alphaMode = mode;
  4490. };
  4491. Engine.prototype.getAlphaMode = function () {
  4492. return this._alphaMode;
  4493. };
  4494. Engine.prototype.setAlphaTesting = function (enable) {
  4495. this._alphaTest = enable;
  4496. };
  4497. Engine.prototype.getAlphaTesting = function () {
  4498. return this._alphaTest;
  4499. };
  4500. // Textures
  4501. Engine.prototype.wipeCaches = function () {
  4502. this._activeTexturesCache = [];
  4503. this._currentEffect = null;
  4504. this._depthCullingState.reset();
  4505. this._alphaState.reset();
  4506. this._cachedVertexBuffers = null;
  4507. this._cachedIndexBuffer = null;
  4508. this._cachedEffectForVertexBuffers = null;
  4509. };
  4510. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4511. var gl = this._gl;
  4512. gl.bindTexture(gl.TEXTURE_2D, texture);
  4513. var magFilter = gl.NEAREST;
  4514. var minFilter = gl.NEAREST;
  4515. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4516. magFilter = gl.LINEAR;
  4517. minFilter = gl.LINEAR;
  4518. }
  4519. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4520. magFilter = gl.LINEAR;
  4521. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4522. }
  4523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4525. gl.bindTexture(gl.TEXTURE_2D, null);
  4526. texture.samplingMode = samplingMode;
  4527. };
  4528. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4529. var _this = this;
  4530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4531. if (onLoad === void 0) { onLoad = null; }
  4532. if (onError === void 0) { onError = null; }
  4533. if (buffer === void 0) { buffer = null; }
  4534. var texture = this._gl.createTexture();
  4535. var extension;
  4536. var fromData = false;
  4537. if (url.substr(0, 5) === "data:") {
  4538. fromData = true;
  4539. }
  4540. if (!fromData)
  4541. extension = url.substr(url.length - 4, 4).toLowerCase();
  4542. else {
  4543. var oldUrl = url;
  4544. fromData = oldUrl.split(':');
  4545. url = oldUrl;
  4546. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4547. }
  4548. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4549. var isTGA = (extension === ".tga");
  4550. scene._addPendingData(texture);
  4551. texture.url = url;
  4552. texture.noMipmap = noMipmap;
  4553. texture.references = 1;
  4554. this._loadedTexturesCache.push(texture);
  4555. var onerror = function () {
  4556. scene._removePendingData(texture);
  4557. if (onError) {
  4558. onError();
  4559. }
  4560. };
  4561. if (isTGA) {
  4562. var callback = function (arrayBuffer) {
  4563. var data = new Uint8Array(arrayBuffer);
  4564. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4565. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4566. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4567. if (onLoad) {
  4568. onLoad();
  4569. }
  4570. }, samplingMode);
  4571. };
  4572. if (!(fromData instanceof Array))
  4573. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4574. callback(arrayBuffer);
  4575. }, onerror, scene.database, true);
  4576. else
  4577. callback(buffer);
  4578. }
  4579. else if (isDDS) {
  4580. callback = function (data) {
  4581. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4582. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4583. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4584. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4585. if (onLoad) {
  4586. onLoad();
  4587. }
  4588. }, samplingMode);
  4589. };
  4590. if (!(fromData instanceof Array))
  4591. BABYLON.Tools.LoadFile(url, function (data) {
  4592. callback(data);
  4593. }, onerror, scene.database, true);
  4594. else
  4595. callback(buffer);
  4596. }
  4597. else {
  4598. var onload = function (img) {
  4599. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4600. var isPot = (img.width === potWidth && img.height === potHeight);
  4601. if (!isPot) {
  4602. _this._workingCanvas.width = potWidth;
  4603. _this._workingCanvas.height = potHeight;
  4604. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4605. _this._workingContext.imageSmoothingEnabled = false;
  4606. _this._workingContext.mozImageSmoothingEnabled = false;
  4607. _this._workingContext.oImageSmoothingEnabled = false;
  4608. _this._workingContext.webkitImageSmoothingEnabled = false;
  4609. _this._workingContext.msImageSmoothingEnabled = false;
  4610. }
  4611. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4612. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4613. _this._workingContext.imageSmoothingEnabled = true;
  4614. _this._workingContext.mozImageSmoothingEnabled = true;
  4615. _this._workingContext.oImageSmoothingEnabled = true;
  4616. _this._workingContext.webkitImageSmoothingEnabled = true;
  4617. _this._workingContext.msImageSmoothingEnabled = true;
  4618. }
  4619. }
  4620. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4621. if (onLoad) {
  4622. onLoad();
  4623. }
  4624. }, samplingMode);
  4625. };
  4626. if (!(fromData instanceof Array))
  4627. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4628. else
  4629. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4630. }
  4631. return texture;
  4632. };
  4633. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4634. var texture = this._gl.createTexture();
  4635. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4636. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4637. // Format
  4638. var internalFormat = this._gl.RGBA;
  4639. switch (format) {
  4640. case Engine.TEXTUREFORMAT_ALPHA:
  4641. internalFormat = this._gl.ALPHA;
  4642. break;
  4643. case Engine.TEXTUREFORMAT_LUMINANCE:
  4644. internalFormat = this._gl.LUMINANCE;
  4645. break;
  4646. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4647. internalFormat = this._gl.LUMINANCE_ALPHA;
  4648. break;
  4649. case Engine.TEXTUREFORMAT_RGB:
  4650. internalFormat = this._gl.RGB;
  4651. break;
  4652. case Engine.TEXTUREFORMAT_RGBA:
  4653. internalFormat = this._gl.RGBA;
  4654. break;
  4655. }
  4656. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4657. if (generateMipMaps) {
  4658. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4659. }
  4660. // Filters
  4661. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4664. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4665. this._activeTexturesCache = [];
  4666. texture._baseWidth = width;
  4667. texture._baseHeight = height;
  4668. texture._width = width;
  4669. texture._height = height;
  4670. texture.isReady = true;
  4671. texture.references = 1;
  4672. texture.samplingMode = samplingMode;
  4673. this._loadedTexturesCache.push(texture);
  4674. return texture;
  4675. };
  4676. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4677. var texture = this._gl.createTexture();
  4678. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4679. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4680. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4681. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4683. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4684. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4685. this._activeTexturesCache = [];
  4686. texture._baseWidth = width;
  4687. texture._baseHeight = height;
  4688. texture._width = width;
  4689. texture._height = height;
  4690. texture.isReady = false;
  4691. texture.generateMipMaps = generateMipMaps;
  4692. texture.references = 1;
  4693. texture.samplingMode = samplingMode;
  4694. this._loadedTexturesCache.push(texture);
  4695. return texture;
  4696. };
  4697. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4698. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4699. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4700. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4701. if (texture.generateMipMaps) {
  4702. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4703. }
  4704. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4705. this._activeTexturesCache = [];
  4706. texture.isReady = true;
  4707. };
  4708. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4709. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4710. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4711. // Scale the video if it is a NPOT using the current working canvas
  4712. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4713. if (!texture._workingCanvas) {
  4714. texture._workingCanvas = document.createElement("canvas");
  4715. texture._workingContext = texture._workingCanvas.getContext("2d");
  4716. texture._workingCanvas.width = texture._width;
  4717. texture._workingCanvas.height = texture._height;
  4718. }
  4719. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4720. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4721. }
  4722. else {
  4723. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4724. }
  4725. if (texture.generateMipMaps) {
  4726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4727. }
  4728. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4729. this._activeTexturesCache = [];
  4730. texture.isReady = true;
  4731. };
  4732. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4733. // old version had a "generateMipMaps" arg instead of options.
  4734. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4735. // in the same way, generateDepthBuffer is defaulted to true
  4736. var generateMipMaps = false;
  4737. var generateDepthBuffer = true;
  4738. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4739. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4740. if (options !== undefined) {
  4741. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4742. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4743. type = options.type === undefined ? type : options.type;
  4744. if (options.samplingMode !== undefined) {
  4745. samplingMode = options.samplingMode;
  4746. }
  4747. if (type === Engine.TEXTURETYPE_FLOAT) {
  4748. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4749. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4750. }
  4751. }
  4752. var gl = this._gl;
  4753. var texture = gl.createTexture();
  4754. gl.bindTexture(gl.TEXTURE_2D, texture);
  4755. var width = size.width || size;
  4756. var height = size.height || size;
  4757. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4758. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4759. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4760. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4761. }
  4762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4766. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4767. var depthBuffer;
  4768. // Create the depth buffer
  4769. if (generateDepthBuffer) {
  4770. depthBuffer = gl.createRenderbuffer();
  4771. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4772. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4773. }
  4774. // Create the framebuffer
  4775. var framebuffer = gl.createFramebuffer();
  4776. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4777. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4778. if (generateDepthBuffer) {
  4779. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4780. }
  4781. // Unbind
  4782. gl.bindTexture(gl.TEXTURE_2D, null);
  4783. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4784. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4785. texture._framebuffer = framebuffer;
  4786. if (generateDepthBuffer) {
  4787. texture._depthBuffer = depthBuffer;
  4788. }
  4789. texture._width = width;
  4790. texture._height = height;
  4791. texture.isReady = true;
  4792. texture.generateMipMaps = generateMipMaps;
  4793. texture.references = 1;
  4794. texture.samplingMode = samplingMode;
  4795. this._activeTexturesCache = [];
  4796. this._loadedTexturesCache.push(texture);
  4797. return texture;
  4798. };
  4799. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4800. var _this = this;
  4801. var gl = this._gl;
  4802. var texture = gl.createTexture();
  4803. texture.isCube = true;
  4804. texture.url = rootUrl;
  4805. texture.references = 1;
  4806. this._loadedTexturesCache.push(texture);
  4807. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4808. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4809. if (isDDS) {
  4810. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4811. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4812. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4813. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4814. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4815. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4816. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4817. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4818. }
  4819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4823. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4824. _this._activeTexturesCache = [];
  4825. texture._width = info.width;
  4826. texture._height = info.height;
  4827. texture.isReady = true;
  4828. }, null, null, true);
  4829. }
  4830. else {
  4831. cascadeLoad(rootUrl, scene, function (imgs) {
  4832. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4833. var height = width;
  4834. _this._workingCanvas.width = width;
  4835. _this._workingCanvas.height = height;
  4836. var faces = [
  4837. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4838. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4839. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4840. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4841. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4842. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4843. ];
  4844. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4845. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4846. for (var index = 0; index < faces.length; index++) {
  4847. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4848. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4849. }
  4850. if (!noMipmap) {
  4851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4852. }
  4853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4857. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4858. _this._activeTexturesCache = [];
  4859. texture._width = width;
  4860. texture._height = height;
  4861. texture.isReady = true;
  4862. }, extensions);
  4863. }
  4864. return texture;
  4865. };
  4866. Engine.prototype._releaseTexture = function (texture) {
  4867. var gl = this._gl;
  4868. if (texture._framebuffer) {
  4869. gl.deleteFramebuffer(texture._framebuffer);
  4870. }
  4871. if (texture._depthBuffer) {
  4872. gl.deleteRenderbuffer(texture._depthBuffer);
  4873. }
  4874. gl.deleteTexture(texture);
  4875. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4876. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4877. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4878. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4879. this._activeTexturesCache[channel] = null;
  4880. }
  4881. var index = this._loadedTexturesCache.indexOf(texture);
  4882. if (index !== -1) {
  4883. this._loadedTexturesCache.splice(index, 1);
  4884. }
  4885. };
  4886. Engine.prototype.bindSamplers = function (effect) {
  4887. this._gl.useProgram(effect.getProgram());
  4888. var samplers = effect.getSamplers();
  4889. for (var index = 0; index < samplers.length; index++) {
  4890. var uniform = effect.getUniform(samplers[index]);
  4891. this._gl.uniform1i(uniform, index);
  4892. }
  4893. this._currentEffect = null;
  4894. };
  4895. Engine.prototype._bindTexture = function (channel, texture) {
  4896. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4897. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4898. this._activeTexturesCache[channel] = null;
  4899. };
  4900. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4901. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4902. };
  4903. Engine.prototype.setTexture = function (channel, texture) {
  4904. if (channel < 0) {
  4905. return;
  4906. }
  4907. // Not ready?
  4908. if (!texture || !texture.isReady()) {
  4909. if (this._activeTexturesCache[channel] != null) {
  4910. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4911. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4912. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4913. this._activeTexturesCache[channel] = null;
  4914. }
  4915. return;
  4916. }
  4917. // Video
  4918. if (texture instanceof BABYLON.VideoTexture) {
  4919. if (texture.update()) {
  4920. this._activeTexturesCache[channel] = null;
  4921. }
  4922. }
  4923. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4924. texture.delayLoad();
  4925. return;
  4926. }
  4927. if (this._activeTexturesCache[channel] === texture) {
  4928. return;
  4929. }
  4930. this._activeTexturesCache[channel] = texture;
  4931. var internalTexture = texture.getInternalTexture();
  4932. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4933. if (internalTexture.isCube) {
  4934. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4935. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4936. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4937. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4938. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4939. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4940. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4941. }
  4942. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4943. }
  4944. else {
  4945. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4946. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4947. internalTexture._cachedWrapU = texture.wrapU;
  4948. switch (texture.wrapU) {
  4949. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4950. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4951. break;
  4952. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4953. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4954. break;
  4955. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4956. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4957. break;
  4958. }
  4959. }
  4960. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4961. internalTexture._cachedWrapV = texture.wrapV;
  4962. switch (texture.wrapV) {
  4963. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4964. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4965. break;
  4966. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4967. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4968. break;
  4969. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4970. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4971. break;
  4972. }
  4973. }
  4974. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4975. }
  4976. };
  4977. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4978. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4979. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4980. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4981. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4982. }
  4983. };
  4984. Engine.prototype.readPixels = function (x, y, width, height) {
  4985. var data = new Uint8Array(height * width * 4);
  4986. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4987. return data;
  4988. };
  4989. // Dispose
  4990. Engine.prototype.dispose = function () {
  4991. this.hideLoadingUI();
  4992. this.stopRenderLoop();
  4993. while (this.scenes.length) {
  4994. this.scenes[0].dispose();
  4995. }
  4996. // Release audio engine
  4997. Engine.audioEngine.dispose();
  4998. for (var name in this._compiledEffects) {
  4999. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5000. }
  5001. for (var i in this._vertexAttribArrays) {
  5002. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5003. continue;
  5004. }
  5005. this._gl.disableVertexAttribArray(i);
  5006. }
  5007. // Events
  5008. window.removeEventListener("blur", this._onBlur);
  5009. window.removeEventListener("focus", this._onFocus);
  5010. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5011. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5012. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5013. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5014. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5015. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5016. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5017. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5018. };
  5019. // Loading screen
  5020. Engine.prototype.displayLoadingUI = function () {
  5021. var _this = this;
  5022. this._loadingDiv = document.createElement("div");
  5023. this._loadingDiv.style.opacity = "0";
  5024. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5025. // Loading text
  5026. this._loadingTextDiv = document.createElement("div");
  5027. this._loadingTextDiv.style.position = "absolute";
  5028. this._loadingTextDiv.style.left = "0";
  5029. this._loadingTextDiv.style.top = "50%";
  5030. this._loadingTextDiv.style.marginTop = "80px";
  5031. this._loadingTextDiv.style.width = "100%";
  5032. this._loadingTextDiv.style.height = "20px";
  5033. this._loadingTextDiv.style.fontFamily = "Arial";
  5034. this._loadingTextDiv.style.fontSize = "14px";
  5035. this._loadingTextDiv.style.color = "white";
  5036. this._loadingTextDiv.style.textAlign = "center";
  5037. this._loadingTextDiv.innerHTML = "Loading";
  5038. this._loadingDiv.appendChild(this._loadingTextDiv);
  5039. // Loading img
  5040. var imgBack = new Image();
  5041. 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==";
  5042. imgBack.style.position = "absolute";
  5043. imgBack.style.left = "50%";
  5044. imgBack.style.top = "50%";
  5045. imgBack.style.marginLeft = "-50px";
  5046. imgBack.style.marginTop = "-50px";
  5047. imgBack.style.transition = "transform 1.0s ease";
  5048. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5049. var deg = 360;
  5050. var onTransitionEnd = function () {
  5051. deg += 360;
  5052. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5053. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5054. };
  5055. imgBack.addEventListener("transitionend", onTransitionEnd);
  5056. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5057. this._loadingDiv.appendChild(imgBack);
  5058. // front image
  5059. var imgFront = new Image();
  5060. 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=";
  5061. imgFront.style.position = "absolute";
  5062. imgFront.style.left = "50%";
  5063. imgFront.style.top = "50%";
  5064. imgFront.style.marginLeft = "-50px";
  5065. imgFront.style.marginTop = "-50px";
  5066. this._loadingDiv.appendChild(imgFront);
  5067. // Resize
  5068. this._resizeLoadingUI = function () {
  5069. var canvasRect = _this.getRenderingCanvasClientRect();
  5070. _this._loadingDiv.style.position = "absolute";
  5071. _this._loadingDiv.style.left = canvasRect.left + "px";
  5072. _this._loadingDiv.style.top = canvasRect.top + "px";
  5073. _this._loadingDiv.style.width = canvasRect.width + "px";
  5074. _this._loadingDiv.style.height = canvasRect.height + "px";
  5075. };
  5076. this._resizeLoadingUI();
  5077. window.addEventListener("resize", this._resizeLoadingUI);
  5078. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5079. document.body.appendChild(this._loadingDiv);
  5080. setTimeout(function () {
  5081. _this._loadingDiv.style.opacity = "1";
  5082. imgBack.style.transform = "rotateZ(360deg)";
  5083. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5084. }, 0);
  5085. };
  5086. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5087. set: function (text) {
  5088. if (!this._loadingDiv) {
  5089. return;
  5090. }
  5091. this._loadingTextDiv.innerHTML = text;
  5092. },
  5093. enumerable: true,
  5094. configurable: true
  5095. });
  5096. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5097. get: function () {
  5098. return this._loadingDivBackgroundColor;
  5099. },
  5100. set: function (color) {
  5101. this._loadingDivBackgroundColor = color;
  5102. if (!this._loadingDiv) {
  5103. return;
  5104. }
  5105. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5106. },
  5107. enumerable: true,
  5108. configurable: true
  5109. });
  5110. Engine.prototype.hideLoadingUI = function () {
  5111. var _this = this;
  5112. if (!this._loadingDiv) {
  5113. return;
  5114. }
  5115. var onTransitionEnd = function () {
  5116. if (!_this._loadingDiv) {
  5117. return;
  5118. }
  5119. document.body.removeChild(_this._loadingDiv);
  5120. window.removeEventListener("resize", _this._resizeLoadingUI);
  5121. _this._loadingDiv = null;
  5122. };
  5123. this._loadingDiv.style.opacity = "0";
  5124. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5125. };
  5126. // FPS
  5127. Engine.prototype.getFps = function () {
  5128. return this.fps;
  5129. };
  5130. Engine.prototype.getDeltaTime = function () {
  5131. return this.deltaTime;
  5132. };
  5133. Engine.prototype._measureFps = function () {
  5134. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5135. var length = this.previousFramesDuration.length;
  5136. if (length >= 2) {
  5137. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5138. }
  5139. if (length >= this.fpsRange) {
  5140. if (length > this.fpsRange) {
  5141. this.previousFramesDuration.splice(0, 1);
  5142. length = this.previousFramesDuration.length;
  5143. }
  5144. var sum = 0;
  5145. for (var id = 0; id < length - 1; id++) {
  5146. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5147. }
  5148. this.fps = 1000.0 / (sum / (length - 1));
  5149. }
  5150. };
  5151. // Statics
  5152. Engine.isSupported = function () {
  5153. try {
  5154. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5155. if (navigator.isCocoonJS) {
  5156. return true;
  5157. }
  5158. var tempcanvas = document.createElement("canvas");
  5159. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5160. return gl != null && !!window.WebGLRenderingContext;
  5161. }
  5162. catch (e) {
  5163. return false;
  5164. }
  5165. };
  5166. // Const statics
  5167. Engine._ALPHA_DISABLE = 0;
  5168. Engine._ALPHA_ADD = 1;
  5169. Engine._ALPHA_COMBINE = 2;
  5170. Engine._DELAYLOADSTATE_NONE = 0;
  5171. Engine._DELAYLOADSTATE_LOADED = 1;
  5172. Engine._DELAYLOADSTATE_LOADING = 2;
  5173. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5174. Engine._TEXTUREFORMAT_ALPHA = 0;
  5175. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5176. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5177. Engine._TEXTUREFORMAT_RGB = 4;
  5178. Engine._TEXTUREFORMAT_RGBA = 4;
  5179. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5180. Engine._TEXTURETYPE_FLOAT = 1;
  5181. // Updatable statics so stick with vars here
  5182. Engine.Epsilon = 0.001;
  5183. Engine.CollisionsEpsilon = 0.001;
  5184. Engine.ShadersRepository = "Babylon/Shaders/";
  5185. return Engine;
  5186. })();
  5187. BABYLON.Engine = Engine;
  5188. })(BABYLON || (BABYLON = {}));
  5189. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5190. (function (BABYLON) {
  5191. /**
  5192. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5193. */
  5194. var Node = (function () {
  5195. /**
  5196. * @constructor
  5197. * @param {string} name - the name and id to be given to this node
  5198. * @param {BABYLON.Scene} the scene this node will be added to
  5199. */
  5200. function Node(name, scene) {
  5201. this.state = "";
  5202. this.animations = new Array();
  5203. this._childrenFlag = -1;
  5204. this._isEnabled = true;
  5205. this._isReady = true;
  5206. this._currentRenderId = -1;
  5207. this.name = name;
  5208. this.id = name;
  5209. this._scene = scene;
  5210. this._initCache();
  5211. }
  5212. Node.prototype.getScene = function () {
  5213. return this._scene;
  5214. };
  5215. Node.prototype.getEngine = function () {
  5216. return this._scene.getEngine();
  5217. };
  5218. // override it in derived class
  5219. Node.prototype.getWorldMatrix = function () {
  5220. return BABYLON.Matrix.Identity();
  5221. };
  5222. // override it in derived class if you add new variables to the cache
  5223. // and call the parent class method
  5224. Node.prototype._initCache = function () {
  5225. this._cache = {};
  5226. this._cache.parent = undefined;
  5227. };
  5228. Node.prototype.updateCache = function (force) {
  5229. if (!force && this.isSynchronized())
  5230. return;
  5231. this._cache.parent = this.parent;
  5232. this._updateCache();
  5233. };
  5234. // override it in derived class if you add new variables to the cache
  5235. // and call the parent class method if !ignoreParentClass
  5236. Node.prototype._updateCache = function (ignoreParentClass) {
  5237. };
  5238. // override it in derived class if you add new variables to the cache
  5239. Node.prototype._isSynchronized = function () {
  5240. return true;
  5241. };
  5242. Node.prototype.isSynchronizedWithParent = function () {
  5243. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5244. };
  5245. Node.prototype.isSynchronized = function (updateCache) {
  5246. var check = this.hasNewParent();
  5247. check = check || !this.isSynchronizedWithParent();
  5248. check = check || !this._isSynchronized();
  5249. if (updateCache)
  5250. this.updateCache(true);
  5251. return !check;
  5252. };
  5253. Node.prototype.hasNewParent = function (update) {
  5254. if (this._cache.parent === this.parent)
  5255. return false;
  5256. if (update)
  5257. this._cache.parent = this.parent;
  5258. return true;
  5259. };
  5260. /**
  5261. * Is this node ready to be used/rendered
  5262. * @return {boolean} is it ready
  5263. */
  5264. Node.prototype.isReady = function () {
  5265. return this._isReady;
  5266. };
  5267. /**
  5268. * Is this node enabled.
  5269. * If the node has a parent and is enabled, the parent will be inspected as well.
  5270. * @return {boolean} whether this node (and its parent) is enabled.
  5271. * @see setEnabled
  5272. */
  5273. Node.prototype.isEnabled = function () {
  5274. if (!this._isEnabled) {
  5275. return false;
  5276. }
  5277. if (this.parent) {
  5278. return this.parent.isEnabled();
  5279. }
  5280. return true;
  5281. };
  5282. /**
  5283. * Set the enabled state of this node.
  5284. * @param {boolean} value - the new enabled state
  5285. * @see isEnabled
  5286. */
  5287. Node.prototype.setEnabled = function (value) {
  5288. this._isEnabled = value;
  5289. };
  5290. /**
  5291. * Is this node a descendant of the given node.
  5292. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5293. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5294. * @see parent
  5295. */
  5296. Node.prototype.isDescendantOf = function (ancestor) {
  5297. if (this.parent) {
  5298. if (this.parent === ancestor) {
  5299. return true;
  5300. }
  5301. return this.parent.isDescendantOf(ancestor);
  5302. }
  5303. return false;
  5304. };
  5305. Node.prototype._getDescendants = function (list, results) {
  5306. for (var index = 0; index < list.length; index++) {
  5307. var item = list[index];
  5308. if (item.isDescendantOf(this)) {
  5309. results.push(item);
  5310. }
  5311. }
  5312. };
  5313. /**
  5314. * Will return all nodes that have this node as parent.
  5315. * @return {BABYLON.Node[]} all children nodes of all types.
  5316. */
  5317. Node.prototype.getDescendants = function () {
  5318. var results = [];
  5319. this._getDescendants(this._scene.meshes, results);
  5320. this._getDescendants(this._scene.lights, results);
  5321. this._getDescendants(this._scene.cameras, results);
  5322. return results;
  5323. };
  5324. Node.prototype._setReady = function (state) {
  5325. if (state == this._isReady) {
  5326. return;
  5327. }
  5328. if (!state) {
  5329. this._isReady = false;
  5330. return;
  5331. }
  5332. this._isReady = true;
  5333. if (this.onReady) {
  5334. this.onReady(this);
  5335. }
  5336. };
  5337. return Node;
  5338. })();
  5339. BABYLON.Node = Node;
  5340. })(BABYLON || (BABYLON = {}));
  5341. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5342. (function (BABYLON) {
  5343. var BoundingSphere = (function () {
  5344. function BoundingSphere(minimum, maximum) {
  5345. this.minimum = minimum;
  5346. this.maximum = maximum;
  5347. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5348. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5349. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5350. this.radius = distance * 0.5;
  5351. this.centerWorld = BABYLON.Vector3.Zero();
  5352. this._update(BABYLON.Matrix.Identity());
  5353. }
  5354. // Methods
  5355. BoundingSphere.prototype._update = function (world) {
  5356. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5357. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5358. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5359. };
  5360. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5361. for (var i = 0; i < 6; i++) {
  5362. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5363. return false;
  5364. }
  5365. return true;
  5366. };
  5367. BoundingSphere.prototype.intersectsPoint = function (point) {
  5368. var x = this.centerWorld.x - point.x;
  5369. var y = this.centerWorld.y - point.y;
  5370. var z = this.centerWorld.z - point.z;
  5371. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5372. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5373. return false;
  5374. return true;
  5375. };
  5376. // Statics
  5377. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5378. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5379. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5380. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5381. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5382. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5383. return false;
  5384. return true;
  5385. };
  5386. return BoundingSphere;
  5387. })();
  5388. BABYLON.BoundingSphere = BoundingSphere;
  5389. })(BABYLON || (BABYLON = {}));
  5390. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5391. (function (BABYLON) {
  5392. var BoundingBox = (function () {
  5393. function BoundingBox(minimum, maximum) {
  5394. this.minimum = minimum;
  5395. this.maximum = maximum;
  5396. this.vectors = new Array();
  5397. this.vectorsWorld = new Array();
  5398. // Bounding vectors
  5399. this.vectors.push(this.minimum.clone());
  5400. this.vectors.push(this.maximum.clone());
  5401. this.vectors.push(this.minimum.clone());
  5402. this.vectors[2].x = this.maximum.x;
  5403. this.vectors.push(this.minimum.clone());
  5404. this.vectors[3].y = this.maximum.y;
  5405. this.vectors.push(this.minimum.clone());
  5406. this.vectors[4].z = this.maximum.z;
  5407. this.vectors.push(this.maximum.clone());
  5408. this.vectors[5].z = this.minimum.z;
  5409. this.vectors.push(this.maximum.clone());
  5410. this.vectors[6].x = this.minimum.x;
  5411. this.vectors.push(this.maximum.clone());
  5412. this.vectors[7].y = this.minimum.y;
  5413. // OBB
  5414. this.center = this.maximum.add(this.minimum).scale(0.5);
  5415. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5416. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5417. for (var index = 0; index < this.vectors.length; index++) {
  5418. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5419. }
  5420. this.minimumWorld = BABYLON.Vector3.Zero();
  5421. this.maximumWorld = BABYLON.Vector3.Zero();
  5422. this._update(BABYLON.Matrix.Identity());
  5423. }
  5424. // Methods
  5425. BoundingBox.prototype.getWorldMatrix = function () {
  5426. return this._worldMatrix;
  5427. };
  5428. BoundingBox.prototype._update = function (world) {
  5429. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5430. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5431. for (var index = 0; index < this.vectors.length; index++) {
  5432. var v = this.vectorsWorld[index];
  5433. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5434. if (v.x < this.minimumWorld.x)
  5435. this.minimumWorld.x = v.x;
  5436. if (v.y < this.minimumWorld.y)
  5437. this.minimumWorld.y = v.y;
  5438. if (v.z < this.minimumWorld.z)
  5439. this.minimumWorld.z = v.z;
  5440. if (v.x > this.maximumWorld.x)
  5441. this.maximumWorld.x = v.x;
  5442. if (v.y > this.maximumWorld.y)
  5443. this.maximumWorld.y = v.y;
  5444. if (v.z > this.maximumWorld.z)
  5445. this.maximumWorld.z = v.z;
  5446. }
  5447. // OBB
  5448. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5449. this.center.scaleInPlace(0.5);
  5450. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5451. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5452. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5453. this._worldMatrix = world;
  5454. };
  5455. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5456. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5457. };
  5458. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5459. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5460. };
  5461. BoundingBox.prototype.intersectsPoint = function (point) {
  5462. var delta = BABYLON.Engine.Epsilon;
  5463. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5464. return false;
  5465. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5466. return false;
  5467. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5468. return false;
  5469. return true;
  5470. };
  5471. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5472. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5473. };
  5474. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5475. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5476. return false;
  5477. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5478. return false;
  5479. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5480. return false;
  5481. return true;
  5482. };
  5483. // Statics
  5484. BoundingBox.Intersects = function (box0, box1) {
  5485. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5486. return false;
  5487. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5488. return false;
  5489. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5490. return false;
  5491. return true;
  5492. };
  5493. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5494. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5495. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5496. return (num <= (sphereRadius * sphereRadius));
  5497. };
  5498. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5499. for (var p = 0; p < 6; p++) {
  5500. for (var i = 0; i < 8; i++) {
  5501. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5502. return false;
  5503. }
  5504. }
  5505. }
  5506. return true;
  5507. };
  5508. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5509. for (var p = 0; p < 6; p++) {
  5510. var inCount = 8;
  5511. for (var i = 0; i < 8; i++) {
  5512. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5513. --inCount;
  5514. }
  5515. else {
  5516. break;
  5517. }
  5518. }
  5519. if (inCount === 0)
  5520. return false;
  5521. }
  5522. return true;
  5523. };
  5524. return BoundingBox;
  5525. })();
  5526. BABYLON.BoundingBox = BoundingBox;
  5527. })(BABYLON || (BABYLON = {}));
  5528. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5529. (function (BABYLON) {
  5530. var computeBoxExtents = function (axis, box) {
  5531. var p = BABYLON.Vector3.Dot(box.center, axis);
  5532. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5533. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5534. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5535. var r = r0 + r1 + r2;
  5536. return {
  5537. min: p - r,
  5538. max: p + r
  5539. };
  5540. };
  5541. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5542. var axisOverlap = function (axis, box0, box1) {
  5543. var result0 = computeBoxExtents(axis, box0);
  5544. var result1 = computeBoxExtents(axis, box1);
  5545. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5546. };
  5547. var BoundingInfo = (function () {
  5548. function BoundingInfo(minimum, maximum) {
  5549. this.minimum = minimum;
  5550. this.maximum = maximum;
  5551. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5552. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5553. }
  5554. // Methods
  5555. BoundingInfo.prototype._update = function (world) {
  5556. this.boundingBox._update(world);
  5557. this.boundingSphere._update(world);
  5558. };
  5559. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5560. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5561. return false;
  5562. return this.boundingBox.isInFrustum(frustumPlanes);
  5563. };
  5564. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5565. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5566. };
  5567. BoundingInfo.prototype._checkCollision = function (collider) {
  5568. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5569. };
  5570. BoundingInfo.prototype.intersectsPoint = function (point) {
  5571. if (!this.boundingSphere.centerWorld) {
  5572. return false;
  5573. }
  5574. if (!this.boundingSphere.intersectsPoint(point)) {
  5575. return false;
  5576. }
  5577. if (!this.boundingBox.intersectsPoint(point)) {
  5578. return false;
  5579. }
  5580. return true;
  5581. };
  5582. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5583. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5584. return false;
  5585. }
  5586. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5587. return false;
  5588. }
  5589. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5590. return false;
  5591. }
  5592. if (!precise) {
  5593. return true;
  5594. }
  5595. var box0 = this.boundingBox;
  5596. var box1 = boundingInfo.boundingBox;
  5597. if (!axisOverlap(box0.directions[0], box0, box1))
  5598. return false;
  5599. if (!axisOverlap(box0.directions[1], box0, box1))
  5600. return false;
  5601. if (!axisOverlap(box0.directions[2], box0, box1))
  5602. return false;
  5603. if (!axisOverlap(box1.directions[0], box0, box1))
  5604. return false;
  5605. if (!axisOverlap(box1.directions[1], box0, box1))
  5606. return false;
  5607. if (!axisOverlap(box1.directions[2], box0, box1))
  5608. return false;
  5609. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5610. return false;
  5611. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5612. return false;
  5613. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5614. return false;
  5615. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5616. return false;
  5617. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5618. return false;
  5619. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5620. return false;
  5621. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5622. return false;
  5623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5624. return false;
  5625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5626. return false;
  5627. return true;
  5628. };
  5629. return BoundingInfo;
  5630. })();
  5631. BABYLON.BoundingInfo = BoundingInfo;
  5632. })(BABYLON || (BABYLON = {}));
  5633. //# sourceMappingURL=babylon.boundingInfo.js.map
  5634. var BABYLON;
  5635. (function (BABYLON) {
  5636. var Light = (function (_super) {
  5637. __extends(Light, _super);
  5638. function Light(name, scene) {
  5639. _super.call(this, name, scene);
  5640. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5641. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5642. this.intensity = 1.0;
  5643. this.range = Number.MAX_VALUE;
  5644. this.includedOnlyMeshes = new Array();
  5645. this.excludedMeshes = new Array();
  5646. this._excludedMeshesIds = new Array();
  5647. this._includedOnlyMeshesIds = new Array();
  5648. scene.lights.push(this);
  5649. }
  5650. Light.prototype.getShadowGenerator = function () {
  5651. return this._shadowGenerator;
  5652. };
  5653. Light.prototype.getAbsolutePosition = function () {
  5654. return BABYLON.Vector3.Zero();
  5655. };
  5656. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5657. };
  5658. Light.prototype._getWorldMatrix = function () {
  5659. return BABYLON.Matrix.Identity();
  5660. };
  5661. Light.prototype.canAffectMesh = function (mesh) {
  5662. if (!mesh) {
  5663. return true;
  5664. }
  5665. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5666. return false;
  5667. }
  5668. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5669. return false;
  5670. }
  5671. return true;
  5672. };
  5673. Light.prototype.getWorldMatrix = function () {
  5674. this._currentRenderId = this.getScene().getRenderId();
  5675. var worldMatrix = this._getWorldMatrix();
  5676. if (this.parent && this.parent.getWorldMatrix) {
  5677. if (!this._parentedWorldMatrix) {
  5678. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5679. }
  5680. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5681. return this._parentedWorldMatrix;
  5682. }
  5683. return worldMatrix;
  5684. };
  5685. Light.prototype.dispose = function () {
  5686. if (this._shadowGenerator) {
  5687. this._shadowGenerator.dispose();
  5688. this._shadowGenerator = null;
  5689. }
  5690. // Remove from scene
  5691. var index = this.getScene().lights.indexOf(this);
  5692. this.getScene().lights.splice(index, 1);
  5693. };
  5694. return Light;
  5695. })(BABYLON.Node);
  5696. BABYLON.Light = Light;
  5697. })(BABYLON || (BABYLON = {}));
  5698. //# sourceMappingURL=babylon.light.js.map
  5699. var BABYLON;
  5700. (function (BABYLON) {
  5701. var PointLight = (function (_super) {
  5702. __extends(PointLight, _super);
  5703. function PointLight(name, position, scene) {
  5704. _super.call(this, name, scene);
  5705. this.position = position;
  5706. }
  5707. PointLight.prototype.getAbsolutePosition = function () {
  5708. return this._transformedPosition ? this._transformedPosition : this.position;
  5709. };
  5710. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5711. if (this.parent && this.parent.getWorldMatrix) {
  5712. if (!this._transformedPosition) {
  5713. this._transformedPosition = BABYLON.Vector3.Zero();
  5714. }
  5715. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5716. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5717. return;
  5718. }
  5719. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5720. };
  5721. PointLight.prototype.getShadowGenerator = function () {
  5722. return null;
  5723. };
  5724. PointLight.prototype._getWorldMatrix = function () {
  5725. if (!this._worldMatrix) {
  5726. this._worldMatrix = BABYLON.Matrix.Identity();
  5727. }
  5728. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5729. return this._worldMatrix;
  5730. };
  5731. return PointLight;
  5732. })(BABYLON.Light);
  5733. BABYLON.PointLight = PointLight;
  5734. })(BABYLON || (BABYLON = {}));
  5735. //# sourceMappingURL=babylon.pointLight.js.map
  5736. var BABYLON;
  5737. (function (BABYLON) {
  5738. var SpotLight = (function (_super) {
  5739. __extends(SpotLight, _super);
  5740. function SpotLight(name, position, direction, angle, exponent, scene) {
  5741. _super.call(this, name, scene);
  5742. this.position = position;
  5743. this.direction = direction;
  5744. this.angle = angle;
  5745. this.exponent = exponent;
  5746. }
  5747. SpotLight.prototype.getAbsolutePosition = function () {
  5748. return this.transformedPosition ? this.transformedPosition : this.position;
  5749. };
  5750. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5751. var activeCamera = this.getScene().activeCamera;
  5752. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5753. };
  5754. SpotLight.prototype.supportsVSM = function () {
  5755. return true;
  5756. };
  5757. SpotLight.prototype.needRefreshPerFrame = function () {
  5758. return false;
  5759. };
  5760. SpotLight.prototype.setDirectionToTarget = function (target) {
  5761. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5762. return this.direction;
  5763. };
  5764. SpotLight.prototype.computeTransformedPosition = function () {
  5765. if (this.parent && this.parent.getWorldMatrix) {
  5766. if (!this.transformedPosition) {
  5767. this.transformedPosition = BABYLON.Vector3.Zero();
  5768. }
  5769. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5770. return true;
  5771. }
  5772. return false;
  5773. };
  5774. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5775. var normalizeDirection;
  5776. if (this.parent && this.parent.getWorldMatrix) {
  5777. if (!this._transformedDirection) {
  5778. this._transformedDirection = BABYLON.Vector3.Zero();
  5779. }
  5780. this.computeTransformedPosition();
  5781. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5782. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5783. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5784. }
  5785. else {
  5786. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5787. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5788. }
  5789. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5790. };
  5791. SpotLight.prototype._getWorldMatrix = function () {
  5792. if (!this._worldMatrix) {
  5793. this._worldMatrix = BABYLON.Matrix.Identity();
  5794. }
  5795. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5796. return this._worldMatrix;
  5797. };
  5798. return SpotLight;
  5799. })(BABYLON.Light);
  5800. BABYLON.SpotLight = SpotLight;
  5801. })(BABYLON || (BABYLON = {}));
  5802. //# sourceMappingURL=babylon.spotLight.js.map
  5803. var BABYLON;
  5804. (function (BABYLON) {
  5805. var DirectionalLight = (function (_super) {
  5806. __extends(DirectionalLight, _super);
  5807. function DirectionalLight(name, direction, scene) {
  5808. _super.call(this, name, scene);
  5809. this.direction = direction;
  5810. this.shadowOrthoScale = 0.1;
  5811. this.position = direction.scale(-1);
  5812. }
  5813. DirectionalLight.prototype.getAbsolutePosition = function () {
  5814. return this.transformedPosition ? this.transformedPosition : this.position;
  5815. };
  5816. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5817. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5818. return this.direction;
  5819. };
  5820. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5821. var orthoLeft = Number.MAX_VALUE;
  5822. var orthoRight = Number.MIN_VALUE;
  5823. var orthoTop = Number.MIN_VALUE;
  5824. var orthoBottom = Number.MAX_VALUE;
  5825. var tempVector3 = BABYLON.Vector3.Zero();
  5826. var activeCamera = this.getScene().activeCamera;
  5827. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5828. var mesh = renderList[meshIndex];
  5829. if (!mesh) {
  5830. continue;
  5831. }
  5832. var boundingInfo = mesh.getBoundingInfo();
  5833. if (!boundingInfo) {
  5834. continue;
  5835. }
  5836. var boundingBox = boundingInfo.boundingBox;
  5837. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5838. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5839. if (tempVector3.x < orthoLeft)
  5840. orthoLeft = tempVector3.x;
  5841. if (tempVector3.y < orthoBottom)
  5842. orthoBottom = tempVector3.y;
  5843. if (tempVector3.x > orthoRight)
  5844. orthoRight = tempVector3.x;
  5845. if (tempVector3.y > orthoTop)
  5846. orthoTop = tempVector3.y;
  5847. }
  5848. }
  5849. var xOffset = orthoRight - orthoLeft;
  5850. var yOffset = orthoTop - orthoBottom;
  5851. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5852. };
  5853. DirectionalLight.prototype.supportsVSM = function () {
  5854. return true;
  5855. };
  5856. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5857. return true;
  5858. };
  5859. DirectionalLight.prototype.computeTransformedPosition = function () {
  5860. if (this.parent && this.parent.getWorldMatrix) {
  5861. if (!this.transformedPosition) {
  5862. this.transformedPosition = BABYLON.Vector3.Zero();
  5863. }
  5864. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5865. return true;
  5866. }
  5867. return false;
  5868. };
  5869. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5870. if (this.parent && this.parent.getWorldMatrix) {
  5871. if (!this._transformedDirection) {
  5872. this._transformedDirection = BABYLON.Vector3.Zero();
  5873. }
  5874. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5875. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5876. return;
  5877. }
  5878. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5879. };
  5880. DirectionalLight.prototype._getWorldMatrix = function () {
  5881. if (!this._worldMatrix) {
  5882. this._worldMatrix = BABYLON.Matrix.Identity();
  5883. }
  5884. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5885. return this._worldMatrix;
  5886. };
  5887. return DirectionalLight;
  5888. })(BABYLON.Light);
  5889. BABYLON.DirectionalLight = DirectionalLight;
  5890. })(BABYLON || (BABYLON = {}));
  5891. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5892. (function (BABYLON) {
  5893. var ShadowGenerator = (function () {
  5894. function ShadowGenerator(mapSize, light) {
  5895. var _this = this;
  5896. // Members
  5897. this.filter = ShadowGenerator.FILTER_NONE;
  5898. this.blurScale = 2;
  5899. this._blurBoxOffset = 0;
  5900. this._bias = 0.00005;
  5901. this._darkness = 0;
  5902. this._transparencyShadow = false;
  5903. this._viewMatrix = BABYLON.Matrix.Zero();
  5904. this._projectionMatrix = BABYLON.Matrix.Zero();
  5905. this._transformMatrix = BABYLON.Matrix.Zero();
  5906. this._worldViewProjection = BABYLON.Matrix.Zero();
  5907. this._light = light;
  5908. this._scene = light.getScene();
  5909. this._mapSize = mapSize;
  5910. light._shadowGenerator = this;
  5911. // Render target
  5912. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5913. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5914. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5915. this._shadowMap.renderParticles = false;
  5916. this._shadowMap.onAfterUnbind = function () {
  5917. if (!_this.useBlurVarianceShadowMap) {
  5918. return;
  5919. }
  5920. if (!_this._shadowMap2) {
  5921. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5922. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5923. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5924. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5925. _this._downSamplePostprocess.onApply = function (effect) {
  5926. effect.setTexture("textureSampler", _this._shadowMap);
  5927. };
  5928. _this.blurBoxOffset = 1;
  5929. }
  5930. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5931. };
  5932. // Custom render function
  5933. var renderSubMesh = function (subMesh) {
  5934. var mesh = subMesh.getRenderingMesh();
  5935. var scene = _this._scene;
  5936. var engine = scene.getEngine();
  5937. // Culling
  5938. engine.setState(subMesh.getMaterial().backFaceCulling);
  5939. // Managing instances
  5940. var batch = mesh._getInstancesRenderList(subMesh._id);
  5941. if (batch.mustReturn) {
  5942. return;
  5943. }
  5944. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5945. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5946. engine.enableEffect(_this._effect);
  5947. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5948. var material = subMesh.getMaterial();
  5949. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5950. // Alpha test
  5951. if (material && material.needAlphaTesting()) {
  5952. var alphaTexture = material.getAlphaTestTexture();
  5953. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5954. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5955. }
  5956. // Bones
  5957. if (mesh.useBones) {
  5958. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5959. }
  5960. // Draw
  5961. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5962. }
  5963. else {
  5964. // Need to reset refresh rate of the shadowMap
  5965. _this._shadowMap.resetRefreshCounter();
  5966. }
  5967. };
  5968. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5969. var index;
  5970. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5971. renderSubMesh(opaqueSubMeshes.data[index]);
  5972. }
  5973. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5974. renderSubMesh(alphaTestSubMeshes.data[index]);
  5975. }
  5976. if (_this._transparencyShadow) {
  5977. for (index = 0; index < transparentSubMeshes.length; index++) {
  5978. renderSubMesh(transparentSubMeshes.data[index]);
  5979. }
  5980. }
  5981. };
  5982. this._shadowMap.onClear = function (engine) {
  5983. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  5984. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  5985. }
  5986. else {
  5987. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  5988. }
  5989. };
  5990. }
  5991. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5992. // Static
  5993. get: function () {
  5994. return ShadowGenerator._FILTER_NONE;
  5995. },
  5996. enumerable: true,
  5997. configurable: true
  5998. });
  5999. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6000. get: function () {
  6001. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6002. },
  6003. enumerable: true,
  6004. configurable: true
  6005. });
  6006. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6007. get: function () {
  6008. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6009. },
  6010. enumerable: true,
  6011. configurable: true
  6012. });
  6013. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6014. get: function () {
  6015. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6016. },
  6017. enumerable: true,
  6018. configurable: true
  6019. });
  6020. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6021. get: function () {
  6022. return this._bias;
  6023. },
  6024. set: function (bias) {
  6025. this._bias = bias;
  6026. },
  6027. enumerable: true,
  6028. configurable: true
  6029. });
  6030. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6031. get: function () {
  6032. return this._blurBoxOffset;
  6033. },
  6034. set: function (value) {
  6035. var _this = this;
  6036. if (this._blurBoxOffset === value) {
  6037. return;
  6038. }
  6039. this._blurBoxOffset = value;
  6040. if (this._boxBlurPostprocess) {
  6041. this._boxBlurPostprocess.dispose();
  6042. }
  6043. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6044. this._boxBlurPostprocess.onApply = function (effect) {
  6045. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6046. };
  6047. },
  6048. enumerable: true,
  6049. configurable: true
  6050. });
  6051. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6052. get: function () {
  6053. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6054. },
  6055. set: function (value) {
  6056. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6062. get: function () {
  6063. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6064. },
  6065. set: function (value) {
  6066. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6067. },
  6068. enumerable: true,
  6069. configurable: true
  6070. });
  6071. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6072. get: function () {
  6073. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6074. },
  6075. set: function (value) {
  6076. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6077. },
  6078. enumerable: true,
  6079. configurable: true
  6080. });
  6081. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6082. var defines = [];
  6083. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6084. defines.push("#define VSM");
  6085. }
  6086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6087. var mesh = subMesh.getMesh();
  6088. var material = subMesh.getMaterial();
  6089. // Alpha test
  6090. if (material && material.needAlphaTesting()) {
  6091. defines.push("#define ALPHATEST");
  6092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6093. attribs.push(BABYLON.VertexBuffer.UVKind);
  6094. defines.push("#define UV1");
  6095. }
  6096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6098. defines.push("#define UV2");
  6099. }
  6100. }
  6101. // Bones
  6102. if (mesh.useBones) {
  6103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6105. defines.push("#define BONES");
  6106. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6107. }
  6108. // Instances
  6109. if (useInstances) {
  6110. defines.push("#define INSTANCES");
  6111. attribs.push("world0");
  6112. attribs.push("world1");
  6113. attribs.push("world2");
  6114. attribs.push("world3");
  6115. }
  6116. // Get correct effect
  6117. var join = defines.join("\n");
  6118. if (this._cachedDefines !== join) {
  6119. this._cachedDefines = join;
  6120. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6121. }
  6122. return this._effect.isReady();
  6123. };
  6124. ShadowGenerator.prototype.getShadowMap = function () {
  6125. return this._shadowMap;
  6126. };
  6127. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6128. if (this._shadowMap2) {
  6129. return this._shadowMap2;
  6130. }
  6131. return this._shadowMap;
  6132. };
  6133. ShadowGenerator.prototype.getLight = function () {
  6134. return this._light;
  6135. };
  6136. // Methods
  6137. ShadowGenerator.prototype.getTransformMatrix = function () {
  6138. var scene = this._scene;
  6139. if (this._currentRenderID === scene.getRenderId()) {
  6140. return this._transformMatrix;
  6141. }
  6142. this._currentRenderID = scene.getRenderId();
  6143. var lightPosition = this._light.position;
  6144. var lightDirection = this._light.direction;
  6145. if (this._light.computeTransformedPosition()) {
  6146. lightPosition = this._light.transformedPosition;
  6147. }
  6148. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6149. this._cachedPosition = lightPosition.clone();
  6150. this._cachedDirection = lightDirection.clone();
  6151. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6152. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6153. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6154. }
  6155. return this._transformMatrix;
  6156. };
  6157. ShadowGenerator.prototype.getDarkness = function () {
  6158. return this._darkness;
  6159. };
  6160. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6161. if (darkness >= 1.0)
  6162. this._darkness = 1.0;
  6163. else if (darkness <= 0.0)
  6164. this._darkness = 0.0;
  6165. else
  6166. this._darkness = darkness;
  6167. };
  6168. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6169. this._transparencyShadow = hasShadow;
  6170. };
  6171. ShadowGenerator.prototype._packHalf = function (depth) {
  6172. var scale = depth * 255.0;
  6173. var fract = scale - Math.floor(scale);
  6174. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6175. };
  6176. ShadowGenerator.prototype.dispose = function () {
  6177. this._shadowMap.dispose();
  6178. if (this._shadowMap2) {
  6179. this._shadowMap2.dispose();
  6180. }
  6181. if (this._downSamplePostprocess) {
  6182. this._downSamplePostprocess.dispose();
  6183. }
  6184. if (this._boxBlurPostprocess) {
  6185. this._boxBlurPostprocess.dispose();
  6186. }
  6187. };
  6188. ShadowGenerator._FILTER_NONE = 0;
  6189. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6190. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6191. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6192. return ShadowGenerator;
  6193. })();
  6194. BABYLON.ShadowGenerator = ShadowGenerator;
  6195. })(BABYLON || (BABYLON = {}));
  6196. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6197. var BABYLON;
  6198. (function (BABYLON) {
  6199. var HemisphericLight = (function (_super) {
  6200. __extends(HemisphericLight, _super);
  6201. function HemisphericLight(name, direction, scene) {
  6202. _super.call(this, name, scene);
  6203. this.direction = direction;
  6204. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6205. }
  6206. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6207. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6208. return this.direction;
  6209. };
  6210. HemisphericLight.prototype.getShadowGenerator = function () {
  6211. return null;
  6212. };
  6213. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6214. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6215. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6216. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6217. };
  6218. HemisphericLight.prototype._getWorldMatrix = function () {
  6219. if (!this._worldMatrix) {
  6220. this._worldMatrix = BABYLON.Matrix.Identity();
  6221. }
  6222. return this._worldMatrix;
  6223. };
  6224. return HemisphericLight;
  6225. })(BABYLON.Light);
  6226. BABYLON.HemisphericLight = HemisphericLight;
  6227. })(BABYLON || (BABYLON = {}));
  6228. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6229. (function (BABYLON) {
  6230. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6231. if (boxMin.x > sphereCenter.x + sphereRadius)
  6232. return false;
  6233. if (sphereCenter.x - sphereRadius > boxMax.x)
  6234. return false;
  6235. if (boxMin.y > sphereCenter.y + sphereRadius)
  6236. return false;
  6237. if (sphereCenter.y - sphereRadius > boxMax.y)
  6238. return false;
  6239. if (boxMin.z > sphereCenter.z + sphereRadius)
  6240. return false;
  6241. if (sphereCenter.z - sphereRadius > boxMax.z)
  6242. return false;
  6243. return true;
  6244. };
  6245. var getLowestRoot = function (a, b, c, maxR) {
  6246. var determinant = b * b - 4.0 * a * c;
  6247. var result = { root: 0, found: false };
  6248. if (determinant < 0)
  6249. return result;
  6250. var sqrtD = Math.sqrt(determinant);
  6251. var r1 = (-b - sqrtD) / (2.0 * a);
  6252. var r2 = (-b + sqrtD) / (2.0 * a);
  6253. if (r1 > r2) {
  6254. var temp = r2;
  6255. r2 = r1;
  6256. r1 = temp;
  6257. }
  6258. if (r1 > 0 && r1 < maxR) {
  6259. result.root = r1;
  6260. result.found = true;
  6261. return result;
  6262. }
  6263. if (r2 > 0 && r2 < maxR) {
  6264. result.root = r2;
  6265. result.found = true;
  6266. return result;
  6267. }
  6268. return result;
  6269. };
  6270. var Collider = (function () {
  6271. function Collider() {
  6272. this.radius = new BABYLON.Vector3(1, 1, 1);
  6273. this.retry = 0;
  6274. this.basePointWorld = BABYLON.Vector3.Zero();
  6275. this.velocityWorld = BABYLON.Vector3.Zero();
  6276. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6277. this._collisionPoint = BABYLON.Vector3.Zero();
  6278. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6279. this._tempVector = BABYLON.Vector3.Zero();
  6280. this._tempVector2 = BABYLON.Vector3.Zero();
  6281. this._tempVector3 = BABYLON.Vector3.Zero();
  6282. this._tempVector4 = BABYLON.Vector3.Zero();
  6283. this._edge = BABYLON.Vector3.Zero();
  6284. this._baseToVertex = BABYLON.Vector3.Zero();
  6285. this._destinationPoint = BABYLON.Vector3.Zero();
  6286. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6287. this._displacementVector = BABYLON.Vector3.Zero();
  6288. }
  6289. // Methods
  6290. Collider.prototype._initialize = function (source, dir, e) {
  6291. this.velocity = dir;
  6292. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6293. this.basePoint = source;
  6294. source.multiplyToRef(this.radius, this.basePointWorld);
  6295. dir.multiplyToRef(this.radius, this.velocityWorld);
  6296. this.velocityWorldLength = this.velocityWorld.length();
  6297. this.epsilon = e;
  6298. this.collisionFound = false;
  6299. };
  6300. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6301. pa.subtractToRef(point, this._tempVector);
  6302. pb.subtractToRef(point, this._tempVector2);
  6303. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6304. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6305. if (d < 0)
  6306. return false;
  6307. pc.subtractToRef(point, this._tempVector3);
  6308. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6309. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6310. if (d < 0)
  6311. return false;
  6312. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6313. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6314. return d >= 0;
  6315. };
  6316. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6317. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6318. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6319. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6320. return false;
  6321. }
  6322. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6323. return false;
  6324. return true;
  6325. };
  6326. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6327. var t0;
  6328. var embeddedInPlane = false;
  6329. if (!subMesh._trianglePlanes) {
  6330. subMesh._trianglePlanes = [];
  6331. }
  6332. if (!subMesh._trianglePlanes[faceIndex]) {
  6333. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6334. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6335. }
  6336. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6337. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6338. return;
  6339. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6340. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6341. if (normalDotVelocity == 0) {
  6342. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6343. return;
  6344. embeddedInPlane = true;
  6345. t0 = 0;
  6346. }
  6347. else {
  6348. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6349. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6350. if (t0 > t1) {
  6351. var temp = t1;
  6352. t1 = t0;
  6353. t0 = temp;
  6354. }
  6355. if (t0 > 1.0 || t1 < 0.0)
  6356. return;
  6357. if (t0 < 0)
  6358. t0 = 0;
  6359. if (t0 > 1.0)
  6360. t0 = 1.0;
  6361. }
  6362. this._collisionPoint.copyFromFloats(0, 0, 0);
  6363. var found = false;
  6364. var t = 1.0;
  6365. if (!embeddedInPlane) {
  6366. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6367. this.velocity.scaleToRef(t0, this._tempVector);
  6368. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6369. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6370. found = true;
  6371. t = t0;
  6372. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6373. }
  6374. }
  6375. if (!found) {
  6376. var velocitySquaredLength = this.velocity.lengthSquared();
  6377. var a = velocitySquaredLength;
  6378. this.basePoint.subtractToRef(p1, this._tempVector);
  6379. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6380. var c = this._tempVector.lengthSquared() - 1.0;
  6381. var lowestRoot = getLowestRoot(a, b, c, t);
  6382. if (lowestRoot.found) {
  6383. t = lowestRoot.root;
  6384. found = true;
  6385. this._collisionPoint.copyFrom(p1);
  6386. }
  6387. this.basePoint.subtractToRef(p2, this._tempVector);
  6388. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6389. c = this._tempVector.lengthSquared() - 1.0;
  6390. lowestRoot = getLowestRoot(a, b, c, t);
  6391. if (lowestRoot.found) {
  6392. t = lowestRoot.root;
  6393. found = true;
  6394. this._collisionPoint.copyFrom(p2);
  6395. }
  6396. this.basePoint.subtractToRef(p3, this._tempVector);
  6397. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6398. c = this._tempVector.lengthSquared() - 1.0;
  6399. lowestRoot = getLowestRoot(a, b, c, t);
  6400. if (lowestRoot.found) {
  6401. t = lowestRoot.root;
  6402. found = true;
  6403. this._collisionPoint.copyFrom(p3);
  6404. }
  6405. p2.subtractToRef(p1, this._edge);
  6406. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6407. var edgeSquaredLength = this._edge.lengthSquared();
  6408. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6409. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6410. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6411. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6412. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6413. lowestRoot = getLowestRoot(a, b, c, t);
  6414. if (lowestRoot.found) {
  6415. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6416. if (f >= 0.0 && f <= 1.0) {
  6417. t = lowestRoot.root;
  6418. found = true;
  6419. this._edge.scaleInPlace(f);
  6420. p1.addToRef(this._edge, this._collisionPoint);
  6421. }
  6422. }
  6423. p3.subtractToRef(p2, this._edge);
  6424. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6425. edgeSquaredLength = this._edge.lengthSquared();
  6426. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6427. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6428. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6429. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6430. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6431. lowestRoot = getLowestRoot(a, b, c, t);
  6432. if (lowestRoot.found) {
  6433. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6434. if (f >= 0.0 && f <= 1.0) {
  6435. t = lowestRoot.root;
  6436. found = true;
  6437. this._edge.scaleInPlace(f);
  6438. p2.addToRef(this._edge, this._collisionPoint);
  6439. }
  6440. }
  6441. p1.subtractToRef(p3, this._edge);
  6442. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6443. edgeSquaredLength = this._edge.lengthSquared();
  6444. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6445. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6446. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6447. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6448. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6449. lowestRoot = getLowestRoot(a, b, c, t);
  6450. if (lowestRoot.found) {
  6451. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6452. if (f >= 0.0 && f <= 1.0) {
  6453. t = lowestRoot.root;
  6454. found = true;
  6455. this._edge.scaleInPlace(f);
  6456. p3.addToRef(this._edge, this._collisionPoint);
  6457. }
  6458. }
  6459. }
  6460. if (found) {
  6461. var distToCollision = t * this.velocity.length();
  6462. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6463. if (!this.intersectionPoint) {
  6464. this.intersectionPoint = this._collisionPoint.clone();
  6465. }
  6466. else {
  6467. this.intersectionPoint.copyFrom(this._collisionPoint);
  6468. }
  6469. this.nearestDistance = distToCollision;
  6470. this.collisionFound = true;
  6471. this.collidedMesh = subMesh.getMesh();
  6472. }
  6473. }
  6474. };
  6475. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6476. for (var i = indexStart; i < indexEnd; i += 3) {
  6477. var p1 = pts[indices[i] - decal];
  6478. var p2 = pts[indices[i + 1] - decal];
  6479. var p3 = pts[indices[i + 2] - decal];
  6480. this._testTriangle(i, subMesh, p3, p2, p1);
  6481. }
  6482. };
  6483. Collider.prototype._getResponse = function (pos, vel) {
  6484. pos.addToRef(vel, this._destinationPoint);
  6485. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6486. this.basePoint.addToRef(vel, pos);
  6487. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6488. this._slidePlaneNormal.normalize();
  6489. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6490. pos.addInPlace(this._displacementVector);
  6491. this.intersectionPoint.addInPlace(this._displacementVector);
  6492. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6493. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6494. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6495. };
  6496. return Collider;
  6497. })();
  6498. BABYLON.Collider = Collider;
  6499. })(BABYLON || (BABYLON = {}));
  6500. //# sourceMappingURL=babylon.collider.js.map
  6501. var BABYLON;
  6502. (function (BABYLON) {
  6503. var Camera = (function (_super) {
  6504. __extends(Camera, _super);
  6505. function Camera(name, position, scene) {
  6506. _super.call(this, name, scene);
  6507. this.position = position;
  6508. // Members
  6509. this.upVector = BABYLON.Vector3.Up();
  6510. this.orthoLeft = null;
  6511. this.orthoRight = null;
  6512. this.orthoBottom = null;
  6513. this.orthoTop = null;
  6514. this.fov = 0.8;
  6515. this.minZ = 1.0;
  6516. this.maxZ = 10000.0;
  6517. this.inertia = 0.9;
  6518. this.mode = Camera.PERSPECTIVE_CAMERA;
  6519. this.isIntermediate = false;
  6520. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6521. this.subCameras = [];
  6522. this.layerMask = 0xFFFFFFFF;
  6523. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6524. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6525. this._projectionMatrix = new BABYLON.Matrix();
  6526. this._postProcesses = new Array();
  6527. this._postProcessesTakenIndices = [];
  6528. this._activeMeshes = new BABYLON.SmartArray(256);
  6529. scene.cameras.push(this);
  6530. if (!scene.activeCamera) {
  6531. scene.activeCamera = this;
  6532. }
  6533. }
  6534. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6535. get: function () {
  6536. return Camera._PERSPECTIVE_CAMERA;
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6542. get: function () {
  6543. return Camera._ORTHOGRAPHIC_CAMERA;
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6549. get: function () {
  6550. return Camera._FOVMODE_VERTICAL_FIXED;
  6551. },
  6552. enumerable: true,
  6553. configurable: true
  6554. });
  6555. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6556. get: function () {
  6557. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6558. },
  6559. enumerable: true,
  6560. configurable: true
  6561. });
  6562. Camera.prototype.getActiveMeshes = function () {
  6563. return this._activeMeshes;
  6564. };
  6565. Camera.prototype.isActiveMesh = function (mesh) {
  6566. return (this._activeMeshes.indexOf(mesh) !== -1);
  6567. };
  6568. //Cache
  6569. Camera.prototype._initCache = function () {
  6570. _super.prototype._initCache.call(this);
  6571. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6572. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6573. this._cache.mode = undefined;
  6574. this._cache.minZ = undefined;
  6575. this._cache.maxZ = undefined;
  6576. this._cache.fov = undefined;
  6577. this._cache.aspectRatio = undefined;
  6578. this._cache.orthoLeft = undefined;
  6579. this._cache.orthoRight = undefined;
  6580. this._cache.orthoBottom = undefined;
  6581. this._cache.orthoTop = undefined;
  6582. this._cache.renderWidth = undefined;
  6583. this._cache.renderHeight = undefined;
  6584. };
  6585. Camera.prototype._updateCache = function (ignoreParentClass) {
  6586. if (!ignoreParentClass) {
  6587. _super.prototype._updateCache.call(this);
  6588. }
  6589. var engine = this.getEngine();
  6590. this._cache.position.copyFrom(this.position);
  6591. this._cache.upVector.copyFrom(this.upVector);
  6592. this._cache.mode = this.mode;
  6593. this._cache.minZ = this.minZ;
  6594. this._cache.maxZ = this.maxZ;
  6595. this._cache.fov = this.fov;
  6596. this._cache.aspectRatio = engine.getAspectRatio(this);
  6597. this._cache.orthoLeft = this.orthoLeft;
  6598. this._cache.orthoRight = this.orthoRight;
  6599. this._cache.orthoBottom = this.orthoBottom;
  6600. this._cache.orthoTop = this.orthoTop;
  6601. this._cache.renderWidth = engine.getRenderWidth();
  6602. this._cache.renderHeight = engine.getRenderHeight();
  6603. };
  6604. Camera.prototype._updateFromScene = function () {
  6605. this.updateCache();
  6606. this._update();
  6607. };
  6608. // Synchronized
  6609. Camera.prototype._isSynchronized = function () {
  6610. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6611. };
  6612. Camera.prototype._isSynchronizedViewMatrix = function () {
  6613. if (!_super.prototype._isSynchronized.call(this))
  6614. return false;
  6615. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6616. };
  6617. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6618. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6619. if (!check) {
  6620. return false;
  6621. }
  6622. var engine = this.getEngine();
  6623. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6624. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6625. }
  6626. else {
  6627. 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();
  6628. }
  6629. return check;
  6630. };
  6631. // Controls
  6632. Camera.prototype.attachControl = function (element) {
  6633. };
  6634. Camera.prototype.detachControl = function (element) {
  6635. };
  6636. Camera.prototype._update = function () {
  6637. };
  6638. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6639. if (insertAt === void 0) { insertAt = null; }
  6640. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6641. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6642. return 0;
  6643. }
  6644. if (insertAt == null || insertAt < 0) {
  6645. this._postProcesses.push(postProcess);
  6646. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6647. return this._postProcesses.length - 1;
  6648. }
  6649. var add = 0;
  6650. if (this._postProcesses[insertAt]) {
  6651. var start = this._postProcesses.length - 1;
  6652. for (var i = start; i >= insertAt + 1; --i) {
  6653. this._postProcesses[i + 1] = this._postProcesses[i];
  6654. }
  6655. add = 1;
  6656. }
  6657. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6658. if (this._postProcessesTakenIndices[i] < insertAt) {
  6659. continue;
  6660. }
  6661. start = this._postProcessesTakenIndices.length - 1;
  6662. for (var j = start; j >= i; --j) {
  6663. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6664. }
  6665. this._postProcessesTakenIndices[i] = insertAt;
  6666. break;
  6667. }
  6668. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6669. this._postProcessesTakenIndices.push(insertAt);
  6670. }
  6671. var result = insertAt + add;
  6672. this._postProcesses[result] = postProcess;
  6673. return result;
  6674. };
  6675. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6676. if (atIndices === void 0) { atIndices = null; }
  6677. var result = [];
  6678. if (!atIndices) {
  6679. var length = this._postProcesses.length;
  6680. for (var i = 0; i < length; i++) {
  6681. if (this._postProcesses[i] !== postProcess) {
  6682. continue;
  6683. }
  6684. delete this._postProcesses[i];
  6685. var index = this._postProcessesTakenIndices.indexOf(i);
  6686. this._postProcessesTakenIndices.splice(index, 1);
  6687. }
  6688. }
  6689. else {
  6690. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6691. for (i = 0; i < atIndices.length; i++) {
  6692. var foundPostProcess = this._postProcesses[atIndices[i]];
  6693. if (foundPostProcess !== postProcess) {
  6694. result.push(i);
  6695. continue;
  6696. }
  6697. delete this._postProcesses[atIndices[i]];
  6698. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6699. this._postProcessesTakenIndices.splice(index, 1);
  6700. }
  6701. }
  6702. return result;
  6703. };
  6704. Camera.prototype.getWorldMatrix = function () {
  6705. if (!this._worldMatrix) {
  6706. this._worldMatrix = BABYLON.Matrix.Identity();
  6707. }
  6708. var viewMatrix = this.getViewMatrix();
  6709. viewMatrix.invertToRef(this._worldMatrix);
  6710. return this._worldMatrix;
  6711. };
  6712. Camera.prototype._getViewMatrix = function () {
  6713. return BABYLON.Matrix.Identity();
  6714. };
  6715. Camera.prototype.getViewMatrix = function () {
  6716. this._computedViewMatrix = this._computeViewMatrix();
  6717. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6718. return this._computedViewMatrix;
  6719. }
  6720. if (!this._worldMatrix) {
  6721. this._worldMatrix = BABYLON.Matrix.Identity();
  6722. }
  6723. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6724. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6725. this._computedViewMatrix.invert();
  6726. this._currentRenderId = this.getScene().getRenderId();
  6727. return this._computedViewMatrix;
  6728. };
  6729. Camera.prototype._computeViewMatrix = function (force) {
  6730. if (!force && this._isSynchronizedViewMatrix()) {
  6731. return this._computedViewMatrix;
  6732. }
  6733. this._computedViewMatrix = this._getViewMatrix();
  6734. if (!this.parent || !this.parent.getWorldMatrix) {
  6735. this._currentRenderId = this.getScene().getRenderId();
  6736. }
  6737. return this._computedViewMatrix;
  6738. };
  6739. Camera.prototype.getProjectionMatrix = function (force) {
  6740. if (!force && this._isSynchronizedProjectionMatrix()) {
  6741. return this._projectionMatrix;
  6742. }
  6743. var engine = this.getEngine();
  6744. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6745. if (this.minZ <= 0) {
  6746. this.minZ = 0.1;
  6747. }
  6748. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6749. return this._projectionMatrix;
  6750. }
  6751. var halfWidth = engine.getRenderWidth() / 2.0;
  6752. var halfHeight = engine.getRenderHeight() / 2.0;
  6753. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6754. return this._projectionMatrix;
  6755. };
  6756. Camera.prototype.dispose = function () {
  6757. // Remove from scene
  6758. var index = this.getScene().cameras.indexOf(this);
  6759. this.getScene().cameras.splice(index, 1);
  6760. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6761. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6762. }
  6763. };
  6764. // Statics
  6765. Camera._PERSPECTIVE_CAMERA = 0;
  6766. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6767. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6768. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6769. return Camera;
  6770. })(BABYLON.Node);
  6771. BABYLON.Camera = Camera;
  6772. })(BABYLON || (BABYLON = {}));
  6773. //# sourceMappingURL=babylon.camera.js.map
  6774. var BABYLON;
  6775. (function (BABYLON) {
  6776. var TargetCamera = (function (_super) {
  6777. __extends(TargetCamera, _super);
  6778. function TargetCamera(name, position, scene) {
  6779. _super.call(this, name, position, scene);
  6780. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6781. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6782. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6783. this.speed = 2.0;
  6784. this.noRotationConstraint = false;
  6785. this.lockedTarget = null;
  6786. this._currentTarget = BABYLON.Vector3.Zero();
  6787. this._viewMatrix = BABYLON.Matrix.Zero();
  6788. this._camMatrix = BABYLON.Matrix.Zero();
  6789. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6790. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6791. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6792. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6793. this._lookAtTemp = BABYLON.Matrix.Zero();
  6794. this._tempMatrix = BABYLON.Matrix.Zero();
  6795. }
  6796. TargetCamera.prototype._getLockedTargetPosition = function () {
  6797. if (!this.lockedTarget) {
  6798. return null;
  6799. }
  6800. return this.lockedTarget.position || this.lockedTarget;
  6801. };
  6802. // Cache
  6803. TargetCamera.prototype._initCache = function () {
  6804. _super.prototype._initCache.call(this);
  6805. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6806. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6807. };
  6808. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6809. if (!ignoreParentClass) {
  6810. _super.prototype._updateCache.call(this);
  6811. }
  6812. var lockedTargetPosition = this._getLockedTargetPosition();
  6813. if (!lockedTargetPosition) {
  6814. this._cache.lockedTarget = null;
  6815. }
  6816. else {
  6817. if (!this._cache.lockedTarget) {
  6818. this._cache.lockedTarget = lockedTargetPosition.clone();
  6819. }
  6820. else {
  6821. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6822. }
  6823. }
  6824. this._cache.rotation.copyFrom(this.rotation);
  6825. };
  6826. // Synchronized
  6827. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6828. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6829. return false;
  6830. }
  6831. var lockedTargetPosition = this._getLockedTargetPosition();
  6832. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6833. };
  6834. // Methods
  6835. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6836. var engine = this.getEngine();
  6837. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6838. };
  6839. // Target
  6840. TargetCamera.prototype.setTarget = function (target) {
  6841. this.upVector.normalize();
  6842. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6843. this._camMatrix.invert();
  6844. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6845. var vDir = target.subtract(this.position);
  6846. if (vDir.x >= 0.0) {
  6847. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6848. }
  6849. else {
  6850. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6851. }
  6852. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6853. if (isNaN(this.rotation.x)) {
  6854. this.rotation.x = 0;
  6855. }
  6856. if (isNaN(this.rotation.y)) {
  6857. this.rotation.y = 0;
  6858. }
  6859. if (isNaN(this.rotation.z)) {
  6860. this.rotation.z = 0;
  6861. }
  6862. };
  6863. TargetCamera.prototype.getTarget = function () {
  6864. return this._currentTarget;
  6865. };
  6866. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6867. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6868. };
  6869. TargetCamera.prototype._updatePosition = function () {
  6870. this.position.addInPlace(this.cameraDirection);
  6871. };
  6872. TargetCamera.prototype._update = function () {
  6873. var needToMove = this._decideIfNeedsToMove();
  6874. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6875. // Move
  6876. if (needToMove) {
  6877. this._updatePosition();
  6878. }
  6879. // Rotate
  6880. if (needToRotate) {
  6881. this.rotation.x += this.cameraRotation.x;
  6882. this.rotation.y += this.cameraRotation.y;
  6883. if (!this.noRotationConstraint) {
  6884. var limit = (Math.PI / 2) * 0.95;
  6885. if (this.rotation.x > limit)
  6886. this.rotation.x = limit;
  6887. if (this.rotation.x < -limit)
  6888. this.rotation.x = -limit;
  6889. }
  6890. }
  6891. // Inertia
  6892. if (needToMove) {
  6893. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6894. this.cameraDirection.x = 0;
  6895. }
  6896. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6897. this.cameraDirection.y = 0;
  6898. }
  6899. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6900. this.cameraDirection.z = 0;
  6901. }
  6902. this.cameraDirection.scaleInPlace(this.inertia);
  6903. }
  6904. if (needToRotate) {
  6905. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6906. this.cameraRotation.x = 0;
  6907. }
  6908. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6909. this.cameraRotation.y = 0;
  6910. }
  6911. this.cameraRotation.scaleInPlace(this.inertia);
  6912. }
  6913. };
  6914. TargetCamera.prototype._getViewMatrix = function () {
  6915. if (!this.lockedTarget) {
  6916. // Compute
  6917. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6918. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6919. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6920. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6921. this._lookAtTemp.invert();
  6922. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6923. }
  6924. else {
  6925. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6926. }
  6927. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6928. // Computing target and final matrix
  6929. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6930. }
  6931. else {
  6932. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6933. }
  6934. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6935. return this._viewMatrix;
  6936. };
  6937. return TargetCamera;
  6938. })(BABYLON.Camera);
  6939. BABYLON.TargetCamera = TargetCamera;
  6940. })(BABYLON || (BABYLON = {}));
  6941. //# sourceMappingURL=babylon.targetCamera.js.map
  6942. var BABYLON;
  6943. (function (BABYLON) {
  6944. var FollowCamera = (function (_super) {
  6945. __extends(FollowCamera, _super);
  6946. function FollowCamera(name, position, scene) {
  6947. _super.call(this, name, position, scene);
  6948. this.radius = 12;
  6949. this.rotationOffset = 0;
  6950. this.heightOffset = 4;
  6951. this.cameraAcceleration = 0.05;
  6952. this.maxCameraSpeed = 20;
  6953. }
  6954. FollowCamera.prototype.getRadians = function (degrees) {
  6955. return degrees * Math.PI / 180;
  6956. };
  6957. FollowCamera.prototype.follow = function (cameraTarget) {
  6958. if (!cameraTarget)
  6959. return;
  6960. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6961. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6962. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6963. var dx = targetX - this.position.x;
  6964. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6965. var dz = (targetZ) - this.position.z;
  6966. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6967. var vy = dy * this.cameraAcceleration;
  6968. var vz = dz * this.cameraAcceleration * 2;
  6969. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6970. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6971. }
  6972. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6973. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6974. }
  6975. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6976. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6977. }
  6978. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6979. this.setTarget(cameraTarget.position);
  6980. };
  6981. FollowCamera.prototype._update = function () {
  6982. _super.prototype._update.call(this);
  6983. this.follow(this.target);
  6984. };
  6985. return FollowCamera;
  6986. })(BABYLON.TargetCamera);
  6987. BABYLON.FollowCamera = FollowCamera;
  6988. })(BABYLON || (BABYLON = {}));
  6989. //# sourceMappingURL=babylon.followCamera.js.map
  6990. var BABYLON;
  6991. (function (BABYLON) {
  6992. var FreeCamera = (function (_super) {
  6993. __extends(FreeCamera, _super);
  6994. function FreeCamera(name, position, scene) {
  6995. _super.call(this, name, position, scene);
  6996. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6997. this.keysUp = [38];
  6998. this.keysDown = [40];
  6999. this.keysLeft = [37];
  7000. this.keysRight = [39];
  7001. this.checkCollisions = false;
  7002. this.applyGravity = false;
  7003. this.angularSensibility = 2000.0;
  7004. this._keys = [];
  7005. this._collider = new BABYLON.Collider();
  7006. this._needMoveForGravity = true;
  7007. this._oldPosition = BABYLON.Vector3.Zero();
  7008. this._diffPosition = BABYLON.Vector3.Zero();
  7009. this._newPosition = BABYLON.Vector3.Zero();
  7010. }
  7011. // Controls
  7012. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7013. var _this = this;
  7014. var previousPosition;
  7015. var engine = this.getEngine();
  7016. if (this._attachedElement) {
  7017. return;
  7018. }
  7019. this._attachedElement = element;
  7020. if (this._onMouseDown === undefined) {
  7021. this._onMouseDown = function (evt) {
  7022. previousPosition = {
  7023. x: evt.clientX,
  7024. y: evt.clientY
  7025. };
  7026. if (!noPreventDefault) {
  7027. evt.preventDefault();
  7028. }
  7029. };
  7030. this._onMouseUp = function (evt) {
  7031. previousPosition = null;
  7032. if (!noPreventDefault) {
  7033. evt.preventDefault();
  7034. }
  7035. };
  7036. this._onMouseOut = function (evt) {
  7037. previousPosition = null;
  7038. _this._keys = [];
  7039. if (!noPreventDefault) {
  7040. evt.preventDefault();
  7041. }
  7042. };
  7043. this._onMouseMove = function (evt) {
  7044. if (!previousPosition && !engine.isPointerLock) {
  7045. return;
  7046. }
  7047. var offsetX;
  7048. var offsetY;
  7049. if (!engine.isPointerLock) {
  7050. offsetX = evt.clientX - previousPosition.x;
  7051. offsetY = evt.clientY - previousPosition.y;
  7052. }
  7053. else {
  7054. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7055. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7056. }
  7057. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7058. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7059. previousPosition = {
  7060. x: evt.clientX,
  7061. y: evt.clientY
  7062. };
  7063. if (!noPreventDefault) {
  7064. evt.preventDefault();
  7065. }
  7066. };
  7067. this._onKeyDown = function (evt) {
  7068. 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) {
  7069. var index = _this._keys.indexOf(evt.keyCode);
  7070. if (index === -1) {
  7071. _this._keys.push(evt.keyCode);
  7072. }
  7073. if (!noPreventDefault) {
  7074. evt.preventDefault();
  7075. }
  7076. }
  7077. };
  7078. this._onKeyUp = function (evt) {
  7079. 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) {
  7080. var index = _this._keys.indexOf(evt.keyCode);
  7081. if (index >= 0) {
  7082. _this._keys.splice(index, 1);
  7083. }
  7084. if (!noPreventDefault) {
  7085. evt.preventDefault();
  7086. }
  7087. }
  7088. };
  7089. this._onLostFocus = function () {
  7090. _this._keys = [];
  7091. };
  7092. this._reset = function () {
  7093. _this._keys = [];
  7094. previousPosition = null;
  7095. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7096. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7097. };
  7098. }
  7099. element.addEventListener("mousedown", this._onMouseDown, false);
  7100. element.addEventListener("mouseup", this._onMouseUp, false);
  7101. element.addEventListener("mouseout", this._onMouseOut, false);
  7102. element.addEventListener("mousemove", this._onMouseMove, false);
  7103. BABYLON.Tools.RegisterTopRootEvents([
  7104. { name: "keydown", handler: this._onKeyDown },
  7105. { name: "keyup", handler: this._onKeyUp },
  7106. { name: "blur", handler: this._onLostFocus }
  7107. ]);
  7108. };
  7109. FreeCamera.prototype.detachControl = function (element) {
  7110. if (this._attachedElement != element) {
  7111. return;
  7112. }
  7113. element.removeEventListener("mousedown", this._onMouseDown);
  7114. element.removeEventListener("mouseup", this._onMouseUp);
  7115. element.removeEventListener("mouseout", this._onMouseOut);
  7116. element.removeEventListener("mousemove", this._onMouseMove);
  7117. BABYLON.Tools.UnregisterTopRootEvents([
  7118. { name: "keydown", handler: this._onKeyDown },
  7119. { name: "keyup", handler: this._onKeyUp },
  7120. { name: "blur", handler: this._onLostFocus }
  7121. ]);
  7122. this._attachedElement = null;
  7123. if (this._reset) {
  7124. this._reset();
  7125. }
  7126. };
  7127. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7128. var globalPosition;
  7129. if (this.parent) {
  7130. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7131. }
  7132. else {
  7133. globalPosition = this.position;
  7134. }
  7135. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7136. this._collider.radius = this.ellipsoid;
  7137. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7138. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7139. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7140. this.position.addInPlace(this._diffPosition);
  7141. if (this.onCollide) {
  7142. this.onCollide(this._collider.collidedMesh);
  7143. }
  7144. }
  7145. };
  7146. FreeCamera.prototype._checkInputs = function () {
  7147. if (!this._localDirection) {
  7148. this._localDirection = BABYLON.Vector3.Zero();
  7149. this._transformedDirection = BABYLON.Vector3.Zero();
  7150. }
  7151. for (var index = 0; index < this._keys.length; index++) {
  7152. var keyCode = this._keys[index];
  7153. var speed = this._computeLocalCameraSpeed();
  7154. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7155. this._localDirection.copyFromFloats(-speed, 0, 0);
  7156. }
  7157. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7158. this._localDirection.copyFromFloats(0, 0, speed);
  7159. }
  7160. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7161. this._localDirection.copyFromFloats(speed, 0, 0);
  7162. }
  7163. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7164. this._localDirection.copyFromFloats(0, 0, -speed);
  7165. }
  7166. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7167. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7168. this.cameraDirection.addInPlace(this._transformedDirection);
  7169. }
  7170. };
  7171. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7172. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7173. };
  7174. FreeCamera.prototype._updatePosition = function () {
  7175. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7176. this._collideWithWorld(this.cameraDirection);
  7177. if (this.applyGravity) {
  7178. var oldPosition = this.position;
  7179. this._collideWithWorld(this.getScene().gravity);
  7180. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7181. }
  7182. }
  7183. else {
  7184. this.position.addInPlace(this.cameraDirection);
  7185. }
  7186. };
  7187. FreeCamera.prototype._update = function () {
  7188. this._checkInputs();
  7189. _super.prototype._update.call(this);
  7190. };
  7191. return FreeCamera;
  7192. })(BABYLON.TargetCamera);
  7193. BABYLON.FreeCamera = FreeCamera;
  7194. })(BABYLON || (BABYLON = {}));
  7195. //# sourceMappingURL=babylon.freeCamera.js.map
  7196. var BABYLON;
  7197. (function (BABYLON) {
  7198. // We're mainly based on the logic defined into the FreeCamera code
  7199. var TouchCamera = (function (_super) {
  7200. __extends(TouchCamera, _super);
  7201. function TouchCamera(name, position, scene) {
  7202. _super.call(this, name, position, scene);
  7203. this._offsetX = null;
  7204. this._offsetY = null;
  7205. this._pointerCount = 0;
  7206. this._pointerPressed = [];
  7207. this.angularSensibility = 200000.0;
  7208. this.moveSensibility = 500.0;
  7209. }
  7210. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7211. var _this = this;
  7212. var previousPosition;
  7213. if (this._attachedCanvas) {
  7214. return;
  7215. }
  7216. this._attachedCanvas = canvas;
  7217. if (this._onPointerDown === undefined) {
  7218. this._onPointerDown = function (evt) {
  7219. if (!noPreventDefault) {
  7220. evt.preventDefault();
  7221. }
  7222. _this._pointerPressed.push(evt.pointerId);
  7223. if (_this._pointerPressed.length !== 1) {
  7224. return;
  7225. }
  7226. previousPosition = {
  7227. x: evt.clientX,
  7228. y: evt.clientY
  7229. };
  7230. };
  7231. this._onPointerUp = function (evt) {
  7232. if (!noPreventDefault) {
  7233. evt.preventDefault();
  7234. }
  7235. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7236. if (index === -1) {
  7237. return;
  7238. }
  7239. _this._pointerPressed.splice(index, 1);
  7240. if (index != 0) {
  7241. return;
  7242. }
  7243. previousPosition = null;
  7244. _this._offsetX = null;
  7245. _this._offsetY = null;
  7246. };
  7247. this._onPointerMove = function (evt) {
  7248. if (!noPreventDefault) {
  7249. evt.preventDefault();
  7250. }
  7251. if (!previousPosition) {
  7252. return;
  7253. }
  7254. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7255. if (index != 0) {
  7256. return;
  7257. }
  7258. _this._offsetX = evt.clientX - previousPosition.x;
  7259. _this._offsetY = -(evt.clientY - previousPosition.y);
  7260. };
  7261. this._onLostFocus = function () {
  7262. _this._offsetX = null;
  7263. _this._offsetY = null;
  7264. };
  7265. }
  7266. canvas.addEventListener("pointerdown", this._onPointerDown);
  7267. canvas.addEventListener("pointerup", this._onPointerUp);
  7268. canvas.addEventListener("pointerout", this._onPointerUp);
  7269. canvas.addEventListener("pointermove", this._onPointerMove);
  7270. BABYLON.Tools.RegisterTopRootEvents([
  7271. { name: "blur", handler: this._onLostFocus }
  7272. ]);
  7273. };
  7274. TouchCamera.prototype.detachControl = function (canvas) {
  7275. if (this._attachedCanvas != canvas) {
  7276. return;
  7277. }
  7278. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7279. canvas.removeEventListener("pointerup", this._onPointerUp);
  7280. canvas.removeEventListener("pointerout", this._onPointerUp);
  7281. canvas.removeEventListener("pointermove", this._onPointerMove);
  7282. BABYLON.Tools.UnregisterTopRootEvents([
  7283. { name: "blur", handler: this._onLostFocus }
  7284. ]);
  7285. this._attachedCanvas = null;
  7286. };
  7287. TouchCamera.prototype._checkInputs = function () {
  7288. if (!this._offsetX) {
  7289. return;
  7290. }
  7291. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7292. if (this._pointerPressed.length > 1) {
  7293. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7294. }
  7295. else {
  7296. var speed = this._computeLocalCameraSpeed();
  7297. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7298. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7299. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7300. }
  7301. };
  7302. return TouchCamera;
  7303. })(BABYLON.FreeCamera);
  7304. BABYLON.TouchCamera = TouchCamera;
  7305. })(BABYLON || (BABYLON = {}));
  7306. //# sourceMappingURL=babylon.touchCamera.js.map
  7307. var BABYLON;
  7308. (function (BABYLON) {
  7309. // We're mainly based on the logic defined into the FreeCamera code
  7310. var DeviceOrientationCamera = (function (_super) {
  7311. __extends(DeviceOrientationCamera, _super);
  7312. function DeviceOrientationCamera(name, position, scene) {
  7313. var _this = this;
  7314. _super.call(this, name, position, scene);
  7315. this._offsetX = null;
  7316. this._offsetY = null;
  7317. this._orientationGamma = 0;
  7318. this._orientationBeta = 0;
  7319. this._initialOrientationGamma = 0;
  7320. this._initialOrientationBeta = 0;
  7321. this.angularSensibility = 10000.0;
  7322. this.moveSensibility = 50.0;
  7323. window.addEventListener("resize", function () {
  7324. _this._initialOrientationGamma = null;
  7325. }, false);
  7326. }
  7327. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7328. var _this = this;
  7329. if (this._attachedCanvas) {
  7330. return;
  7331. }
  7332. this._attachedCanvas = canvas;
  7333. if (!this._orientationChanged) {
  7334. this._orientationChanged = function (evt) {
  7335. if (!_this._initialOrientationGamma) {
  7336. _this._initialOrientationGamma = evt.gamma;
  7337. _this._initialOrientationBeta = evt.beta;
  7338. }
  7339. _this._orientationGamma = evt.gamma;
  7340. _this._orientationBeta = evt.beta;
  7341. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7342. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7343. };
  7344. }
  7345. window.addEventListener("deviceorientation", this._orientationChanged);
  7346. };
  7347. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7348. if (this._attachedCanvas != canvas) {
  7349. return;
  7350. }
  7351. window.removeEventListener("deviceorientation", this._orientationChanged);
  7352. this._attachedCanvas = null;
  7353. this._orientationGamma = 0;
  7354. this._orientationBeta = 0;
  7355. this._initialOrientationGamma = 0;
  7356. this._initialOrientationBeta = 0;
  7357. };
  7358. DeviceOrientationCamera.prototype._checkInputs = function () {
  7359. if (!this._offsetX) {
  7360. return;
  7361. }
  7362. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7363. var speed = this._computeLocalCameraSpeed();
  7364. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7365. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7366. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7367. };
  7368. return DeviceOrientationCamera;
  7369. })(BABYLON.FreeCamera);
  7370. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7371. })(BABYLON || (BABYLON = {}));
  7372. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7373. var BABYLON;
  7374. (function (BABYLON) {
  7375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7376. var ArcRotateCamera = (function (_super) {
  7377. __extends(ArcRotateCamera, _super);
  7378. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7379. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7380. this.alpha = alpha;
  7381. this.beta = beta;
  7382. this.radius = radius;
  7383. this.target = target;
  7384. this.inertialAlphaOffset = 0;
  7385. this.inertialBetaOffset = 0;
  7386. this.inertialRadiusOffset = 0;
  7387. this.lowerAlphaLimit = null;
  7388. this.upperAlphaLimit = null;
  7389. this.lowerBetaLimit = 0.01;
  7390. this.upperBetaLimit = Math.PI;
  7391. this.lowerRadiusLimit = null;
  7392. this.upperRadiusLimit = null;
  7393. this.angularSensibility = 1000.0;
  7394. this.wheelPrecision = 3.0;
  7395. this.keysUp = [38];
  7396. this.keysDown = [40];
  7397. this.keysLeft = [37];
  7398. this.keysRight = [39];
  7399. this.zoomOnFactor = 1;
  7400. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7401. this._keys = [];
  7402. this._viewMatrix = new BABYLON.Matrix();
  7403. this.checkCollisions = false;
  7404. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7405. this._collider = new BABYLON.Collider();
  7406. this._previousPosition = BABYLON.Vector3.Zero();
  7407. this._collisionVelocity = BABYLON.Vector3.Zero();
  7408. this._newPosition = BABYLON.Vector3.Zero();
  7409. // Pinch
  7410. // value for pinch step scaling
  7411. // set to 20 by default
  7412. this.pinchPrecision = 20;
  7413. this.getViewMatrix();
  7414. }
  7415. ArcRotateCamera.prototype._getTargetPosition = function () {
  7416. return this.target.position || this.target;
  7417. };
  7418. // Cache
  7419. ArcRotateCamera.prototype._initCache = function () {
  7420. _super.prototype._initCache.call(this);
  7421. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7422. this._cache.alpha = undefined;
  7423. this._cache.beta = undefined;
  7424. this._cache.radius = undefined;
  7425. this._cache.targetScreenOffset = undefined;
  7426. };
  7427. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7428. if (!ignoreParentClass) {
  7429. _super.prototype._updateCache.call(this);
  7430. }
  7431. this._cache.target.copyFrom(this._getTargetPosition());
  7432. this._cache.alpha = this.alpha;
  7433. this._cache.beta = this.beta;
  7434. this._cache.radius = this.radius;
  7435. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7436. };
  7437. // Synchronized
  7438. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7439. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7440. return false;
  7441. 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);
  7442. };
  7443. // Methods
  7444. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7445. var _this = this;
  7446. var previousPosition;
  7447. var pointerId;
  7448. // to know if pinch started
  7449. var pinchStarted = false;
  7450. // two pinch point on X
  7451. // that will use for find if user action is pinch open or pinch close
  7452. var pinchPointX1, pinchPointX2;
  7453. if (this._attachedElement) {
  7454. return;
  7455. }
  7456. this._attachedElement = element;
  7457. var engine = this.getEngine();
  7458. if (this._onPointerDown === undefined) {
  7459. this._onPointerDown = function (evt) {
  7460. if (pointerId) {
  7461. return;
  7462. }
  7463. pointerId = evt.pointerId;
  7464. previousPosition = {
  7465. x: evt.clientX,
  7466. y: evt.clientY
  7467. };
  7468. if (!noPreventDefault) {
  7469. evt.preventDefault();
  7470. }
  7471. };
  7472. this._onPointerUp = function (evt) {
  7473. previousPosition = null;
  7474. pointerId = null;
  7475. if (!noPreventDefault) {
  7476. evt.preventDefault();
  7477. }
  7478. };
  7479. this._onPointerMove = function (evt) {
  7480. if (!previousPosition) {
  7481. return;
  7482. }
  7483. if (pointerId !== evt.pointerId) {
  7484. return;
  7485. }
  7486. // return pinch is started
  7487. if (pinchStarted) {
  7488. return;
  7489. }
  7490. var offsetX = evt.clientX - previousPosition.x;
  7491. var offsetY = evt.clientY - previousPosition.y;
  7492. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7493. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7494. previousPosition = {
  7495. x: evt.clientX,
  7496. y: evt.clientY
  7497. };
  7498. if (!noPreventDefault) {
  7499. evt.preventDefault();
  7500. }
  7501. };
  7502. this._onMouseMove = function (evt) {
  7503. if (!engine.isPointerLock) {
  7504. return;
  7505. }
  7506. // return pinch is started
  7507. if (pinchStarted) {
  7508. return;
  7509. }
  7510. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7511. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7512. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7513. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7514. if (!noPreventDefault) {
  7515. evt.preventDefault();
  7516. }
  7517. };
  7518. this._wheel = function (event) {
  7519. var delta = 0;
  7520. if (event.wheelDelta) {
  7521. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7522. }
  7523. else if (event.detail) {
  7524. delta = -event.detail / _this.wheelPrecision;
  7525. }
  7526. if (delta)
  7527. _this.inertialRadiusOffset += delta;
  7528. if (event.preventDefault) {
  7529. if (!noPreventDefault) {
  7530. event.preventDefault();
  7531. }
  7532. }
  7533. };
  7534. this._onKeyDown = function (evt) {
  7535. 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) {
  7536. var index = _this._keys.indexOf(evt.keyCode);
  7537. if (index === -1) {
  7538. _this._keys.push(evt.keyCode);
  7539. }
  7540. if (evt.preventDefault) {
  7541. if (!noPreventDefault) {
  7542. evt.preventDefault();
  7543. }
  7544. }
  7545. }
  7546. };
  7547. this._onKeyUp = function (evt) {
  7548. 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) {
  7549. var index = _this._keys.indexOf(evt.keyCode);
  7550. if (index >= 0) {
  7551. _this._keys.splice(index, 1);
  7552. }
  7553. if (evt.preventDefault) {
  7554. if (!noPreventDefault) {
  7555. evt.preventDefault();
  7556. }
  7557. }
  7558. }
  7559. };
  7560. this._onLostFocus = function () {
  7561. _this._keys = [];
  7562. pointerId = null;
  7563. };
  7564. this._onGestureStart = function (e) {
  7565. if (window.MSGesture === undefined) {
  7566. return;
  7567. }
  7568. if (!_this._MSGestureHandler) {
  7569. _this._MSGestureHandler = new MSGesture();
  7570. _this._MSGestureHandler.target = element;
  7571. }
  7572. _this._MSGestureHandler.addPointer(e.pointerId);
  7573. };
  7574. this._onGesture = function (e) {
  7575. _this.radius *= e.scale;
  7576. if (e.preventDefault) {
  7577. if (!noPreventDefault) {
  7578. e.stopPropagation();
  7579. e.preventDefault();
  7580. }
  7581. }
  7582. };
  7583. this._reset = function () {
  7584. _this._keys = [];
  7585. _this.inertialAlphaOffset = 0;
  7586. _this.inertialBetaOffset = 0;
  7587. _this.inertialRadiusOffset = 0;
  7588. previousPosition = null;
  7589. pointerId = null;
  7590. };
  7591. this._touchStart = function (event) {
  7592. if (event.touches.length === 2) {
  7593. //-- start pinch if two fingers on the screen
  7594. pinchStarted = true;
  7595. _this._pinchStart(event);
  7596. }
  7597. };
  7598. this._touchMove = function (event) {
  7599. if (pinchStarted) {
  7600. //-- make scaling
  7601. _this._pinchMove(event);
  7602. }
  7603. };
  7604. this._touchEnd = function (event) {
  7605. if (pinchStarted) {
  7606. //-- end of pinch
  7607. _this._pinchEnd(event);
  7608. }
  7609. };
  7610. this._pinchStart = function (event) {
  7611. // save origin touch point
  7612. pinchPointX1 = event.touches[0].clientX;
  7613. pinchPointX2 = event.touches[1].clientX;
  7614. // block the camera
  7615. // if not it rotate around target during pinch
  7616. pinchStarted = true;
  7617. };
  7618. this._pinchMove = function (event) {
  7619. // variable for new camera's radius
  7620. var delta = 0;
  7621. // variables to know if pinch open or pinch close
  7622. var direction = 1;
  7623. var distanceXOrigine, distanceXNow;
  7624. if (event.touches.length !== 2)
  7625. return;
  7626. // calculate absolute distances of the two fingers
  7627. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7628. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7629. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7630. if (distanceXNow < distanceXOrigine) {
  7631. direction = -1;
  7632. }
  7633. // calculate new radius
  7634. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7635. // set new radius
  7636. _this.inertialRadiusOffset -= delta;
  7637. // save origin touch point
  7638. pinchPointX1 = event.touches[0].clientX;
  7639. pinchPointX2 = event.touches[1].clientX;
  7640. };
  7641. this._pinchEnd = function (event) {
  7642. // cancel pinch and deblock camera rotation
  7643. pinchStarted = false;
  7644. };
  7645. }
  7646. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7647. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7648. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7649. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7650. element.addEventListener("mousemove", this._onMouseMove, false);
  7651. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7652. element.addEventListener("MSGestureChange", this._onGesture, false);
  7653. element.addEventListener('mousewheel', this._wheel, false);
  7654. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7655. // pinch
  7656. element.addEventListener('touchstart', this._touchStart, false);
  7657. element.addEventListener('touchmove', this._touchMove, false);
  7658. element.addEventListener('touchend', this._touchEnd, false);
  7659. BABYLON.Tools.RegisterTopRootEvents([
  7660. { name: "keydown", handler: this._onKeyDown },
  7661. { name: "keyup", handler: this._onKeyUp },
  7662. { name: "blur", handler: this._onLostFocus }
  7663. ]);
  7664. };
  7665. ArcRotateCamera.prototype.detachControl = function (element) {
  7666. if (this._attachedElement != element) {
  7667. return;
  7668. }
  7669. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7670. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7671. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7672. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7673. element.removeEventListener("mousemove", this._onMouseMove);
  7674. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7675. element.removeEventListener("MSGestureChange", this._onGesture);
  7676. element.removeEventListener('mousewheel', this._wheel);
  7677. element.removeEventListener('DOMMouseScroll', this._wheel);
  7678. // pinch
  7679. element.removeEventListener('touchstart', this._touchStart);
  7680. element.removeEventListener('touchmove', this._touchMove);
  7681. element.removeEventListener('touchend', this._touchEnd);
  7682. BABYLON.Tools.UnregisterTopRootEvents([
  7683. { name: "keydown", handler: this._onKeyDown },
  7684. { name: "keyup", handler: this._onKeyUp },
  7685. { name: "blur", handler: this._onLostFocus }
  7686. ]);
  7687. this._MSGestureHandler = null;
  7688. this._attachedElement = null;
  7689. if (this._reset) {
  7690. this._reset();
  7691. }
  7692. };
  7693. ArcRotateCamera.prototype._update = function () {
  7694. for (var index = 0; index < this._keys.length; index++) {
  7695. var keyCode = this._keys[index];
  7696. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7697. this.inertialAlphaOffset -= 0.01;
  7698. }
  7699. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7700. this.inertialBetaOffset -= 0.01;
  7701. }
  7702. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7703. this.inertialAlphaOffset += 0.01;
  7704. }
  7705. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7706. this.inertialBetaOffset += 0.01;
  7707. }
  7708. }
  7709. // Inertia
  7710. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7711. this.alpha += this.inertialAlphaOffset;
  7712. this.beta += this.inertialBetaOffset;
  7713. this.radius -= this.inertialRadiusOffset;
  7714. this.inertialAlphaOffset *= this.inertia;
  7715. this.inertialBetaOffset *= this.inertia;
  7716. this.inertialRadiusOffset *= this.inertia;
  7717. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7718. this.inertialAlphaOffset = 0;
  7719. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7720. this.inertialBetaOffset = 0;
  7721. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7722. this.inertialRadiusOffset = 0;
  7723. }
  7724. // Limits
  7725. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7726. this.alpha = this.lowerAlphaLimit;
  7727. }
  7728. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7729. this.alpha = this.upperAlphaLimit;
  7730. }
  7731. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7732. this.beta = this.lowerBetaLimit;
  7733. }
  7734. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7735. this.beta = this.upperBetaLimit;
  7736. }
  7737. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7738. this.radius = this.lowerRadiusLimit;
  7739. }
  7740. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7741. this.radius = this.upperRadiusLimit;
  7742. }
  7743. };
  7744. ArcRotateCamera.prototype.setPosition = function (position) {
  7745. var radiusv3 = position.subtract(this._getTargetPosition());
  7746. this.radius = radiusv3.length();
  7747. // Alpha
  7748. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7749. if (radiusv3.z < 0) {
  7750. this.alpha = 2 * Math.PI - this.alpha;
  7751. }
  7752. // Beta
  7753. this.beta = Math.acos(radiusv3.y / this.radius);
  7754. };
  7755. ArcRotateCamera.prototype._getViewMatrix = function () {
  7756. // Compute
  7757. var cosa = Math.cos(this.alpha);
  7758. var sina = Math.sin(this.alpha);
  7759. var cosb = Math.cos(this.beta);
  7760. var sinb = Math.sin(this.beta);
  7761. var target = this._getTargetPosition();
  7762. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7763. if (this.checkCollisions) {
  7764. this._collider.radius = this.collisionRadius;
  7765. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7766. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7767. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7768. this.position.copyFrom(this._previousPosition);
  7769. this.alpha = this._previousAlpha;
  7770. this.beta = this._previousBeta;
  7771. this.radius = this._previousRadius;
  7772. if (this.onCollide) {
  7773. this.onCollide(this._collider.collidedMesh);
  7774. }
  7775. }
  7776. }
  7777. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7778. this._previousAlpha = this.alpha;
  7779. this._previousBeta = this.beta;
  7780. this._previousRadius = this.radius;
  7781. this._previousPosition.copyFrom(this.position);
  7782. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7783. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7784. return this._viewMatrix;
  7785. };
  7786. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7787. meshes = meshes || this.getScene().meshes;
  7788. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7789. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7790. this.radius = distance * this.zoomOnFactor;
  7791. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7792. };
  7793. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7794. var meshesOrMinMaxVector;
  7795. var distance;
  7796. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7797. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7798. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7799. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7800. }
  7801. else {
  7802. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7803. distance = meshesOrMinMaxVectorAndDistance.distance;
  7804. }
  7805. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7806. this.maxZ = distance * 2;
  7807. };
  7808. return ArcRotateCamera;
  7809. })(BABYLON.Camera);
  7810. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7811. })(BABYLON || (BABYLON = {}));
  7812. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7813. (function (BABYLON) {
  7814. /**
  7815. * Represents a scene to be rendered by the engine.
  7816. * @see http://doc.babylonjs.com/page.php?p=21911
  7817. */
  7818. var Scene = (function () {
  7819. /**
  7820. * @constructor
  7821. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7822. */
  7823. function Scene(engine) {
  7824. // Members
  7825. this.autoClear = true;
  7826. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7827. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7828. this.forceWireframe = false;
  7829. this.forcePointsCloud = false;
  7830. this.forceShowBoundingBoxes = false;
  7831. this.animationsEnabled = true;
  7832. 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
  7833. // Fog
  7834. /**
  7835. * is fog enabled on this scene.
  7836. * @type {boolean}
  7837. */
  7838. this.fogEnabled = true;
  7839. this.fogMode = Scene.FOGMODE_NONE;
  7840. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7841. this.fogDensity = 0.1;
  7842. this.fogStart = 0;
  7843. this.fogEnd = 1000.0;
  7844. // Lights
  7845. /**
  7846. * is shadow enabled on this scene.
  7847. * @type {boolean}
  7848. */
  7849. this.shadowsEnabled = true;
  7850. /**
  7851. * is light enabled on this scene.
  7852. * @type {boolean}
  7853. */
  7854. this.lightsEnabled = true;
  7855. /**
  7856. * All of the lights added to this scene.
  7857. * @see BABYLON.Light
  7858. * @type {BABYLON.Light[]}
  7859. */
  7860. this.lights = new Array();
  7861. // Cameras
  7862. /**
  7863. * All of the cameras added to this scene.
  7864. * @see BABYLON.Camera
  7865. * @type {BABYLON.Camera[]}
  7866. */
  7867. this.cameras = new Array();
  7868. this.activeCameras = new Array();
  7869. // Meshes
  7870. /**
  7871. * All of the (abstract) meshes added to this scene.
  7872. * @see BABYLON.AbstractMesh
  7873. * @type {BABYLON.AbstractMesh[]}
  7874. */
  7875. this.meshes = new Array();
  7876. // Geometries
  7877. this._geometries = new Array();
  7878. this.materials = new Array();
  7879. this.multiMaterials = new Array();
  7880. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7881. // Textures
  7882. this.texturesEnabled = true;
  7883. this.textures = new Array();
  7884. // Particles
  7885. this.particlesEnabled = true;
  7886. this.particleSystems = new Array();
  7887. // Sprites
  7888. this.spritesEnabled = true;
  7889. this.spriteManagers = new Array();
  7890. // Layers
  7891. this.layers = new Array();
  7892. // Skeletons
  7893. this.skeletonsEnabled = true;
  7894. this.skeletons = new Array();
  7895. // Lens flares
  7896. this.lensFlaresEnabled = true;
  7897. this.lensFlareSystems = new Array();
  7898. // Collisions
  7899. this.collisionsEnabled = true;
  7900. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7901. // Postprocesses
  7902. this.postProcessesEnabled = true;
  7903. // Customs render targets
  7904. this.renderTargetsEnabled = true;
  7905. this.dumpNextRenderTargets = false;
  7906. this.customRenderTargets = new Array();
  7907. // Imported meshes
  7908. this.importedMeshesFiles = new Array();
  7909. this._actionManagers = new Array();
  7910. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7911. // Procedural textures
  7912. this.proceduralTexturesEnabled = true;
  7913. this._proceduralTextures = new Array();
  7914. this.soundTracks = new Array();
  7915. this._audioEnabled = true;
  7916. this._headphone = false;
  7917. this._totalVertices = 0;
  7918. this._activeVertices = 0;
  7919. this._activeParticles = 0;
  7920. this._lastFrameDuration = 0;
  7921. this._evaluateActiveMeshesDuration = 0;
  7922. this._renderTargetsDuration = 0;
  7923. this._particlesDuration = 0;
  7924. this._renderDuration = 0;
  7925. this._spritesDuration = 0;
  7926. this._animationRatio = 0;
  7927. this._renderId = 0;
  7928. this._executeWhenReadyTimeoutId = -1;
  7929. this._toBeDisposed = new BABYLON.SmartArray(256);
  7930. this._onReadyCallbacks = new Array();
  7931. this._pendingData = []; //ANY
  7932. this._onBeforeRenderCallbacks = new Array();
  7933. this._onAfterRenderCallbacks = new Array();
  7934. this._activeMeshes = new BABYLON.SmartArray(256);
  7935. this._processedMaterials = new BABYLON.SmartArray(256);
  7936. this._renderTargets = new BABYLON.SmartArray(256);
  7937. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7938. this._activeSkeletons = new BABYLON.SmartArray(32);
  7939. this._activeBones = 0;
  7940. this._activeAnimatables = new Array();
  7941. this._transformMatrix = BABYLON.Matrix.Zero();
  7942. this._scaledPosition = BABYLON.Vector3.Zero();
  7943. this._scaledVelocity = BABYLON.Vector3.Zero();
  7944. this._engine = engine;
  7945. engine.scenes.push(this);
  7946. this._renderingManager = new BABYLON.RenderingManager(this);
  7947. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7948. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7949. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7950. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7951. this.attachControl();
  7952. this._debugLayer = new BABYLON.DebugLayer(this);
  7953. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7954. //simplification queue
  7955. this.simplificationQueue = new BABYLON.SimplificationQueue();
  7956. }
  7957. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7958. get: function () {
  7959. return Scene._FOGMODE_NONE;
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7965. get: function () {
  7966. return Scene._FOGMODE_EXP;
  7967. },
  7968. enumerable: true,
  7969. configurable: true
  7970. });
  7971. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7972. get: function () {
  7973. return Scene._FOGMODE_EXP2;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7979. get: function () {
  7980. return Scene._FOGMODE_LINEAR;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Scene.prototype, "debugLayer", {
  7986. // Properties
  7987. get: function () {
  7988. return this._debugLayer;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7994. /**
  7995. * The mesh that is currently under the pointer.
  7996. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7997. */
  7998. get: function () {
  7999. return this._meshUnderPointer;
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Scene.prototype, "pointerX", {
  8005. /**
  8006. * Current on-screen X position of the pointer
  8007. * @return {number} X position of the pointer
  8008. */
  8009. get: function () {
  8010. return this._pointerX;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. Object.defineProperty(Scene.prototype, "pointerY", {
  8016. /**
  8017. * Current on-screen Y position of the pointer
  8018. * @return {number} Y position of the pointer
  8019. */
  8020. get: function () {
  8021. return this._pointerY;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Scene.prototype.getCachedMaterial = function () {
  8027. return this._cachedMaterial;
  8028. };
  8029. Scene.prototype.getBoundingBoxRenderer = function () {
  8030. return this._boundingBoxRenderer;
  8031. };
  8032. Scene.prototype.getOutlineRenderer = function () {
  8033. return this._outlineRenderer;
  8034. };
  8035. Scene.prototype.getEngine = function () {
  8036. return this._engine;
  8037. };
  8038. Scene.prototype.getTotalVertices = function () {
  8039. return this._totalVertices;
  8040. };
  8041. Scene.prototype.getActiveVertices = function () {
  8042. return this._activeVertices;
  8043. };
  8044. Scene.prototype.getActiveParticles = function () {
  8045. return this._activeParticles;
  8046. };
  8047. Scene.prototype.getActiveBones = function () {
  8048. return this._activeBones;
  8049. };
  8050. // Stats
  8051. Scene.prototype.getLastFrameDuration = function () {
  8052. return this._lastFrameDuration;
  8053. };
  8054. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8055. return this._evaluateActiveMeshesDuration;
  8056. };
  8057. Scene.prototype.getActiveMeshes = function () {
  8058. return this._activeMeshes;
  8059. };
  8060. Scene.prototype.getRenderTargetsDuration = function () {
  8061. return this._renderTargetsDuration;
  8062. };
  8063. Scene.prototype.getRenderDuration = function () {
  8064. return this._renderDuration;
  8065. };
  8066. Scene.prototype.getParticlesDuration = function () {
  8067. return this._particlesDuration;
  8068. };
  8069. Scene.prototype.getSpritesDuration = function () {
  8070. return this._spritesDuration;
  8071. };
  8072. Scene.prototype.getAnimationRatio = function () {
  8073. return this._animationRatio;
  8074. };
  8075. Scene.prototype.getRenderId = function () {
  8076. return this._renderId;
  8077. };
  8078. Scene.prototype.incrementRenderId = function () {
  8079. this._renderId++;
  8080. };
  8081. Scene.prototype._updatePointerPosition = function (evt) {
  8082. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8083. this._pointerX = evt.clientX - canvasRect.left;
  8084. this._pointerY = evt.clientY - canvasRect.top;
  8085. if (this.cameraToUseForPointers) {
  8086. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8087. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8088. }
  8089. };
  8090. // Pointers handling
  8091. Scene.prototype.attachControl = function () {
  8092. var _this = this;
  8093. this._onPointerMove = function (evt) {
  8094. var canvas = _this._engine.getRenderingCanvas();
  8095. _this._updatePointerPosition(evt);
  8096. 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);
  8097. if (pickResult.hit) {
  8098. _this._meshUnderPointer = pickResult.pickedMesh;
  8099. _this.setPointerOverMesh(pickResult.pickedMesh);
  8100. canvas.style.cursor = "pointer";
  8101. }
  8102. else {
  8103. _this.setPointerOverMesh(null);
  8104. canvas.style.cursor = "";
  8105. _this._meshUnderPointer = null;
  8106. }
  8107. };
  8108. this._onPointerDown = function (evt) {
  8109. var predicate = null;
  8110. if (!_this.onPointerDown) {
  8111. predicate = function (mesh) {
  8112. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8113. };
  8114. }
  8115. _this._updatePointerPosition(evt);
  8116. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8117. if (pickResult.hit) {
  8118. if (pickResult.pickedMesh.actionManager) {
  8119. switch (evt.button) {
  8120. case 0:
  8121. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8122. break;
  8123. case 1:
  8124. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8125. break;
  8126. case 2:
  8127. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8128. break;
  8129. }
  8130. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8131. }
  8132. }
  8133. if (_this.onPointerDown) {
  8134. _this.onPointerDown(evt, pickResult);
  8135. }
  8136. };
  8137. this._onKeyDown = function (evt) {
  8138. if (_this.actionManager) {
  8139. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8140. }
  8141. };
  8142. this._onKeyUp = function (evt) {
  8143. if (_this.actionManager) {
  8144. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8145. }
  8146. };
  8147. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8148. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8149. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8150. BABYLON.Tools.RegisterTopRootEvents([
  8151. { name: "keydown", handler: this._onKeyDown },
  8152. { name: "keyup", handler: this._onKeyUp }
  8153. ]);
  8154. };
  8155. Scene.prototype.detachControl = function () {
  8156. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8157. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8158. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8159. BABYLON.Tools.UnregisterTopRootEvents([
  8160. { name: "keydown", handler: this._onKeyDown },
  8161. { name: "keyup", handler: this._onKeyUp }
  8162. ]);
  8163. };
  8164. // Ready
  8165. Scene.prototype.isReady = function () {
  8166. if (this._pendingData.length > 0) {
  8167. return false;
  8168. }
  8169. for (var index = 0; index < this._geometries.length; index++) {
  8170. var geometry = this._geometries[index];
  8171. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8172. return false;
  8173. }
  8174. }
  8175. for (index = 0; index < this.meshes.length; index++) {
  8176. var mesh = this.meshes[index];
  8177. if (!mesh.isReady()) {
  8178. return false;
  8179. }
  8180. var mat = mesh.material;
  8181. if (mat) {
  8182. if (!mat.isReady(mesh)) {
  8183. return false;
  8184. }
  8185. }
  8186. }
  8187. return true;
  8188. };
  8189. Scene.prototype.resetCachedMaterial = function () {
  8190. this._cachedMaterial = null;
  8191. };
  8192. Scene.prototype.registerBeforeRender = function (func) {
  8193. this._onBeforeRenderCallbacks.push(func);
  8194. };
  8195. Scene.prototype.unregisterBeforeRender = function (func) {
  8196. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8197. if (index > -1) {
  8198. this._onBeforeRenderCallbacks.splice(index, 1);
  8199. }
  8200. };
  8201. Scene.prototype.registerAfterRender = function (func) {
  8202. this._onAfterRenderCallbacks.push(func);
  8203. };
  8204. Scene.prototype.unregisterAfterRender = function (func) {
  8205. var index = this._onAfterRenderCallbacks.indexOf(func);
  8206. if (index > -1) {
  8207. this._onAfterRenderCallbacks.splice(index, 1);
  8208. }
  8209. };
  8210. Scene.prototype._addPendingData = function (data) {
  8211. this._pendingData.push(data);
  8212. };
  8213. Scene.prototype._removePendingData = function (data) {
  8214. var index = this._pendingData.indexOf(data);
  8215. if (index !== -1) {
  8216. this._pendingData.splice(index, 1);
  8217. }
  8218. };
  8219. Scene.prototype.getWaitingItemsCount = function () {
  8220. return this._pendingData.length;
  8221. };
  8222. /**
  8223. * Registers a function to be executed when the scene is ready.
  8224. * @param {Function} func - the function to be executed.
  8225. */
  8226. Scene.prototype.executeWhenReady = function (func) {
  8227. var _this = this;
  8228. this._onReadyCallbacks.push(func);
  8229. if (this._executeWhenReadyTimeoutId !== -1) {
  8230. return;
  8231. }
  8232. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8233. _this._checkIsReady();
  8234. }, 150);
  8235. };
  8236. Scene.prototype._checkIsReady = function () {
  8237. var _this = this;
  8238. if (this.isReady()) {
  8239. this._onReadyCallbacks.forEach(function (func) {
  8240. func();
  8241. });
  8242. this._onReadyCallbacks = [];
  8243. this._executeWhenReadyTimeoutId = -1;
  8244. return;
  8245. }
  8246. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8247. _this._checkIsReady();
  8248. }, 150);
  8249. };
  8250. // Animations
  8251. /**
  8252. * Will start the animation sequence of a given target
  8253. * @param target - the target
  8254. * @param {number} from - from which frame should animation start
  8255. * @param {number} to - till which frame should animation run.
  8256. * @param {boolean} [loop] - should the animation loop
  8257. * @param {number} [speedRatio] - the speed in which to run the animation
  8258. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8259. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8260. * @return {BABYLON.Animatable} the animatable object created for this animation
  8261. * @see BABYLON.Animatable
  8262. * @see http://doc.babylonjs.com/page.php?p=22081
  8263. */
  8264. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8265. if (speedRatio === undefined) {
  8266. speedRatio = 1.0;
  8267. }
  8268. this.stopAnimation(target);
  8269. if (!animatable) {
  8270. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8271. }
  8272. // Local animations
  8273. if (target.animations) {
  8274. animatable.appendAnimations(target, target.animations);
  8275. }
  8276. // Children animations
  8277. if (target.getAnimatables) {
  8278. var animatables = target.getAnimatables();
  8279. for (var index = 0; index < animatables.length; index++) {
  8280. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8281. }
  8282. }
  8283. return animatable;
  8284. };
  8285. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8286. if (speedRatio === undefined) {
  8287. speedRatio = 1.0;
  8288. }
  8289. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8290. return animatable;
  8291. };
  8292. Scene.prototype.getAnimatableByTarget = function (target) {
  8293. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8294. if (this._activeAnimatables[index].target === target) {
  8295. return this._activeAnimatables[index];
  8296. }
  8297. }
  8298. return null;
  8299. };
  8300. /**
  8301. * Will stop the animation of the given target
  8302. * @param target - the target
  8303. * @see beginAnimation
  8304. */
  8305. Scene.prototype.stopAnimation = function (target) {
  8306. var animatable = this.getAnimatableByTarget(target);
  8307. if (animatable) {
  8308. animatable.stop();
  8309. }
  8310. };
  8311. Scene.prototype._animate = function () {
  8312. if (!this.animationsEnabled) {
  8313. return;
  8314. }
  8315. if (!this._animationStartDate) {
  8316. this._animationStartDate = BABYLON.Tools.Now;
  8317. }
  8318. // Getting time
  8319. var now = BABYLON.Tools.Now;
  8320. var delay = now - this._animationStartDate;
  8321. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8322. if (!this._activeAnimatables[index]._animate(delay)) {
  8323. this._activeAnimatables.splice(index, 1);
  8324. index--;
  8325. }
  8326. }
  8327. };
  8328. // Matrix
  8329. Scene.prototype.getViewMatrix = function () {
  8330. return this._viewMatrix;
  8331. };
  8332. Scene.prototype.getProjectionMatrix = function () {
  8333. return this._projectionMatrix;
  8334. };
  8335. Scene.prototype.getTransformMatrix = function () {
  8336. return this._transformMatrix;
  8337. };
  8338. Scene.prototype.setTransformMatrix = function (view, projection) {
  8339. this._viewMatrix = view;
  8340. this._projectionMatrix = projection;
  8341. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8342. };
  8343. // Methods
  8344. /**
  8345. * sets the active camera of the scene using its ID
  8346. * @param {string} id - the camera's ID
  8347. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8348. * @see activeCamera
  8349. */
  8350. Scene.prototype.setActiveCameraByID = function (id) {
  8351. var camera = this.getCameraByID(id);
  8352. if (camera) {
  8353. this.activeCamera = camera;
  8354. return camera;
  8355. }
  8356. return null;
  8357. };
  8358. /**
  8359. * sets the active camera of the scene using its name
  8360. * @param {string} name - the camera's name
  8361. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8362. * @see activeCamera
  8363. */
  8364. Scene.prototype.setActiveCameraByName = function (name) {
  8365. var camera = this.getCameraByName(name);
  8366. if (camera) {
  8367. this.activeCamera = camera;
  8368. return camera;
  8369. }
  8370. return null;
  8371. };
  8372. /**
  8373. * get a material using its id
  8374. * @param {string} the material's ID
  8375. * @return {BABYLON.Material|null} the material or null if none found.
  8376. */
  8377. Scene.prototype.getMaterialByID = function (id) {
  8378. for (var index = 0; index < this.materials.length; index++) {
  8379. if (this.materials[index].id === id) {
  8380. return this.materials[index];
  8381. }
  8382. }
  8383. return null;
  8384. };
  8385. /**
  8386. * get a material using its name
  8387. * @param {string} the material's name
  8388. * @return {BABYLON.Material|null} the material or null if none found.
  8389. */
  8390. Scene.prototype.getMaterialByName = function (name) {
  8391. for (var index = 0; index < this.materials.length; index++) {
  8392. if (this.materials[index].name === name) {
  8393. return this.materials[index];
  8394. }
  8395. }
  8396. return null;
  8397. };
  8398. Scene.prototype.getCameraByID = function (id) {
  8399. for (var index = 0; index < this.cameras.length; index++) {
  8400. if (this.cameras[index].id === id) {
  8401. return this.cameras[index];
  8402. }
  8403. }
  8404. return null;
  8405. };
  8406. /**
  8407. * get a camera using its name
  8408. * @param {string} the camera's name
  8409. * @return {BABYLON.Camera|null} the camera or null if none found.
  8410. */
  8411. Scene.prototype.getCameraByName = function (name) {
  8412. for (var index = 0; index < this.cameras.length; index++) {
  8413. if (this.cameras[index].name === name) {
  8414. return this.cameras[index];
  8415. }
  8416. }
  8417. return null;
  8418. };
  8419. /**
  8420. * get a light node using its name
  8421. * @param {string} the light's name
  8422. * @return {BABYLON.Light|null} the light or null if none found.
  8423. */
  8424. Scene.prototype.getLightByName = function (name) {
  8425. for (var index = 0; index < this.lights.length; index++) {
  8426. if (this.lights[index].name === name) {
  8427. return this.lights[index];
  8428. }
  8429. }
  8430. return null;
  8431. };
  8432. /**
  8433. * get a light node using its ID
  8434. * @param {string} the light's id
  8435. * @return {BABYLON.Light|null} the light or null if none found.
  8436. */
  8437. Scene.prototype.getLightByID = function (id) {
  8438. for (var index = 0; index < this.lights.length; index++) {
  8439. if (this.lights[index].id === id) {
  8440. return this.lights[index];
  8441. }
  8442. }
  8443. return null;
  8444. };
  8445. /**
  8446. * get a geometry using its ID
  8447. * @param {string} the geometry's id
  8448. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8449. */
  8450. Scene.prototype.getGeometryByID = function (id) {
  8451. for (var index = 0; index < this._geometries.length; index++) {
  8452. if (this._geometries[index].id === id) {
  8453. return this._geometries[index];
  8454. }
  8455. }
  8456. return null;
  8457. };
  8458. /**
  8459. * add a new geometry to this scene.
  8460. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8461. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8462. * @return {boolean} was the geometry added or not
  8463. */
  8464. Scene.prototype.pushGeometry = function (geometry, force) {
  8465. if (!force && this.getGeometryByID(geometry.id)) {
  8466. return false;
  8467. }
  8468. this._geometries.push(geometry);
  8469. return true;
  8470. };
  8471. Scene.prototype.getGeometries = function () {
  8472. return this._geometries;
  8473. };
  8474. /**
  8475. * Get a the first added mesh found of a given ID
  8476. * @param {string} id - the id to search for
  8477. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8478. */
  8479. Scene.prototype.getMeshByID = function (id) {
  8480. for (var index = 0; index < this.meshes.length; index++) {
  8481. if (this.meshes[index].id === id) {
  8482. return this.meshes[index];
  8483. }
  8484. }
  8485. return null;
  8486. };
  8487. /**
  8488. * Get a the last added mesh found of a given ID
  8489. * @param {string} id - the id to search for
  8490. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8491. */
  8492. Scene.prototype.getLastMeshByID = function (id) {
  8493. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8494. if (this.meshes[index].id === id) {
  8495. return this.meshes[index];
  8496. }
  8497. }
  8498. return null;
  8499. };
  8500. /**
  8501. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8502. * @param {string} id - the id to search for
  8503. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8504. */
  8505. Scene.prototype.getLastEntryByID = function (id) {
  8506. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8507. if (this.meshes[index].id === id) {
  8508. return this.meshes[index];
  8509. }
  8510. }
  8511. for (index = this.cameras.length - 1; index >= 0; index--) {
  8512. if (this.cameras[index].id === id) {
  8513. return this.cameras[index];
  8514. }
  8515. }
  8516. for (index = this.lights.length - 1; index >= 0; index--) {
  8517. if (this.lights[index].id === id) {
  8518. return this.lights[index];
  8519. }
  8520. }
  8521. return null;
  8522. };
  8523. Scene.prototype.getNodeByName = function (name) {
  8524. var mesh = this.getMeshByName(name);
  8525. if (mesh) {
  8526. return mesh;
  8527. }
  8528. var light = this.getLightByName(name);
  8529. if (light) {
  8530. return light;
  8531. }
  8532. return this.getCameraByName(name);
  8533. };
  8534. Scene.prototype.getMeshByName = function (name) {
  8535. for (var index = 0; index < this.meshes.length; index++) {
  8536. if (this.meshes[index].name === name) {
  8537. return this.meshes[index];
  8538. }
  8539. }
  8540. return null;
  8541. };
  8542. Scene.prototype.getSoundByName = function (name) {
  8543. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8544. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8545. return this.mainSoundTrack.soundCollection[index];
  8546. }
  8547. }
  8548. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8549. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8550. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8551. return this.soundTracks[sdIndex].soundCollection[index];
  8552. }
  8553. }
  8554. }
  8555. return null;
  8556. };
  8557. Scene.prototype.getLastSkeletonByID = function (id) {
  8558. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8559. if (this.skeletons[index].id === id) {
  8560. return this.skeletons[index];
  8561. }
  8562. }
  8563. return null;
  8564. };
  8565. Scene.prototype.getSkeletonById = function (id) {
  8566. for (var index = 0; index < this.skeletons.length; index++) {
  8567. if (this.skeletons[index].id === id) {
  8568. return this.skeletons[index];
  8569. }
  8570. }
  8571. return null;
  8572. };
  8573. Scene.prototype.getSkeletonByName = function (name) {
  8574. for (var index = 0; index < this.skeletons.length; index++) {
  8575. if (this.skeletons[index].name === name) {
  8576. return this.skeletons[index];
  8577. }
  8578. }
  8579. return null;
  8580. };
  8581. Scene.prototype.isActiveMesh = function (mesh) {
  8582. return (this._activeMeshes.indexOf(mesh) !== -1);
  8583. };
  8584. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8585. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8586. var material = subMesh.getMaterial();
  8587. if (mesh.showSubMeshesBoundingBox) {
  8588. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8589. }
  8590. if (material) {
  8591. // Render targets
  8592. if (material.getRenderTargetTextures) {
  8593. if (this._processedMaterials.indexOf(material) === -1) {
  8594. this._processedMaterials.push(material);
  8595. this._renderTargets.concat(material.getRenderTargetTextures());
  8596. }
  8597. }
  8598. // Dispatch
  8599. this._activeVertices += subMesh.indexCount;
  8600. this._renderingManager.dispatch(subMesh);
  8601. }
  8602. }
  8603. };
  8604. Scene.prototype._evaluateActiveMeshes = function () {
  8605. this.activeCamera._activeMeshes.reset();
  8606. this._activeMeshes.reset();
  8607. this._renderingManager.reset();
  8608. this._processedMaterials.reset();
  8609. this._activeParticleSystems.reset();
  8610. this._activeSkeletons.reset();
  8611. this._boundingBoxRenderer.reset();
  8612. if (!this._frustumPlanes) {
  8613. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8614. }
  8615. else {
  8616. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8617. }
  8618. // Meshes
  8619. var meshes;
  8620. var len;
  8621. if (this._selectionOctree) {
  8622. var selection = this._selectionOctree.select(this._frustumPlanes);
  8623. meshes = selection.data;
  8624. len = selection.length;
  8625. }
  8626. else {
  8627. len = this.meshes.length;
  8628. meshes = this.meshes;
  8629. }
  8630. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8631. var mesh = meshes[meshIndex];
  8632. if (mesh.isBlocked) {
  8633. continue;
  8634. }
  8635. this._totalVertices += mesh.getTotalVertices();
  8636. if (!mesh.isReady()) {
  8637. continue;
  8638. }
  8639. mesh.computeWorldMatrix();
  8640. // Intersections
  8641. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8642. this._meshesForIntersections.pushNoDuplicate(mesh);
  8643. }
  8644. // Switch to current LOD
  8645. var meshLOD = mesh.getLOD(this.activeCamera);
  8646. if (!meshLOD) {
  8647. continue;
  8648. }
  8649. mesh._preActivate();
  8650. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8651. this._activeMeshes.push(mesh);
  8652. this.activeCamera._activeMeshes.push(mesh);
  8653. mesh._activate(this._renderId);
  8654. this._activeMesh(meshLOD);
  8655. }
  8656. }
  8657. // Particle systems
  8658. var beforeParticlesDate = BABYLON.Tools.Now;
  8659. if (this.particlesEnabled) {
  8660. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8661. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8662. var particleSystem = this.particleSystems[particleIndex];
  8663. if (!particleSystem.isStarted()) {
  8664. continue;
  8665. }
  8666. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8667. this._activeParticleSystems.push(particleSystem);
  8668. particleSystem.animate();
  8669. }
  8670. }
  8671. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8672. }
  8673. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8674. };
  8675. Scene.prototype._activeMesh = function (mesh) {
  8676. if (mesh.skeleton && this.skeletonsEnabled) {
  8677. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8678. }
  8679. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8680. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8681. }
  8682. if (mesh && mesh.subMeshes) {
  8683. // Submeshes Octrees
  8684. var len;
  8685. var subMeshes;
  8686. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8687. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8688. len = intersections.length;
  8689. subMeshes = intersections.data;
  8690. }
  8691. else {
  8692. subMeshes = mesh.subMeshes;
  8693. len = subMeshes.length;
  8694. }
  8695. for (var subIndex = 0; subIndex < len; subIndex++) {
  8696. var subMesh = subMeshes[subIndex];
  8697. this._evaluateSubMesh(subMesh, mesh);
  8698. }
  8699. }
  8700. };
  8701. Scene.prototype.updateTransformMatrix = function (force) {
  8702. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8703. };
  8704. Scene.prototype._renderForCamera = function (camera) {
  8705. var engine = this._engine;
  8706. this.activeCamera = camera;
  8707. if (!this.activeCamera)
  8708. throw new Error("Active camera not set");
  8709. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8710. // Viewport
  8711. engine.setViewport(this.activeCamera.viewport);
  8712. // Camera
  8713. this._renderId++;
  8714. this.updateTransformMatrix();
  8715. if (this.beforeCameraRender) {
  8716. this.beforeCameraRender(this.activeCamera);
  8717. }
  8718. // Meshes
  8719. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8720. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8721. this._evaluateActiveMeshes();
  8722. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8723. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8724. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8725. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8726. skeleton.prepare();
  8727. }
  8728. // Render targets
  8729. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8730. if (this.renderTargetsEnabled) {
  8731. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8732. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8733. var renderTarget = this._renderTargets.data[renderIndex];
  8734. if (renderTarget._shouldRender()) {
  8735. this._renderId++;
  8736. renderTarget.render(false, this.dumpNextRenderTargets);
  8737. }
  8738. }
  8739. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8740. this._renderId++;
  8741. }
  8742. if (this._renderTargets.length > 0) {
  8743. engine.restoreDefaultFramebuffer();
  8744. }
  8745. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8746. // Prepare Frame
  8747. this.postProcessManager._prepareFrame();
  8748. var beforeRenderDate = BABYLON.Tools.Now;
  8749. // Backgrounds
  8750. if (this.layers.length) {
  8751. engine.setDepthBuffer(false);
  8752. var layerIndex;
  8753. var layer;
  8754. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8755. layer = this.layers[layerIndex];
  8756. if (layer.isBackground) {
  8757. layer.render();
  8758. }
  8759. }
  8760. engine.setDepthBuffer(true);
  8761. }
  8762. // Render
  8763. BABYLON.Tools.StartPerformanceCounter("Main render");
  8764. this._renderingManager.render(null, null, true, true);
  8765. BABYLON.Tools.EndPerformanceCounter("Main render");
  8766. // Bounding boxes
  8767. this._boundingBoxRenderer.render();
  8768. // Lens flares
  8769. if (this.lensFlaresEnabled) {
  8770. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8771. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8772. this.lensFlareSystems[lensFlareSystemIndex].render();
  8773. }
  8774. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8775. }
  8776. // Foregrounds
  8777. if (this.layers.length) {
  8778. engine.setDepthBuffer(false);
  8779. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8780. layer = this.layers[layerIndex];
  8781. if (!layer.isBackground) {
  8782. layer.render();
  8783. }
  8784. }
  8785. engine.setDepthBuffer(true);
  8786. }
  8787. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8788. // Finalize frame
  8789. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8790. // Update camera
  8791. this.activeCamera._updateFromScene();
  8792. // Reset some special arrays
  8793. this._renderTargets.reset();
  8794. if (this.afterCameraRender) {
  8795. this.afterCameraRender(this.activeCamera);
  8796. }
  8797. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8798. };
  8799. Scene.prototype._processSubCameras = function (camera) {
  8800. if (camera.subCameras.length === 0) {
  8801. this._renderForCamera(camera);
  8802. return;
  8803. }
  8804. for (var index = 0; index < camera.subCameras.length; index++) {
  8805. this._renderForCamera(camera.subCameras[index]);
  8806. }
  8807. this.activeCamera = camera;
  8808. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8809. // Update camera
  8810. this.activeCamera._updateFromScene();
  8811. };
  8812. Scene.prototype._checkIntersections = function () {
  8813. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8814. var sourceMesh = this._meshesForIntersections.data[index];
  8815. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8816. var action = sourceMesh.actionManager.actions[actionIndex];
  8817. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8818. var parameters = action.getTriggerParameter();
  8819. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8820. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8821. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8822. if (areIntersecting && currentIntersectionInProgress === -1) {
  8823. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8824. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8825. sourceMesh._intersectionsInProgress.push(otherMesh);
  8826. }
  8827. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8828. sourceMesh._intersectionsInProgress.push(otherMesh);
  8829. }
  8830. }
  8831. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8832. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8833. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8834. if (indexOfOther > -1) {
  8835. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8836. }
  8837. }
  8838. }
  8839. }
  8840. }
  8841. };
  8842. Scene.prototype.render = function () {
  8843. var startDate = BABYLON.Tools.Now;
  8844. this._particlesDuration = 0;
  8845. this._spritesDuration = 0;
  8846. this._activeParticles = 0;
  8847. this._renderDuration = 0;
  8848. this._renderTargetsDuration = 0;
  8849. this._evaluateActiveMeshesDuration = 0;
  8850. this._totalVertices = 0;
  8851. this._activeVertices = 0;
  8852. this._activeBones = 0;
  8853. this.getEngine().resetDrawCalls();
  8854. this._meshesForIntersections.reset();
  8855. this.resetCachedMaterial();
  8856. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8857. // Actions
  8858. if (this.actionManager) {
  8859. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8860. }
  8861. //Simplification Queue
  8862. if (!this.simplificationQueue.running) {
  8863. this.simplificationQueue.executeNext();
  8864. }
  8865. // Before render
  8866. if (this.beforeRender) {
  8867. this.beforeRender();
  8868. }
  8869. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8870. this._onBeforeRenderCallbacks[callbackIndex]();
  8871. }
  8872. // Animations
  8873. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8874. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8875. this._animate();
  8876. // Physics
  8877. if (this._physicsEngine) {
  8878. BABYLON.Tools.StartPerformanceCounter("Physics");
  8879. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8880. BABYLON.Tools.EndPerformanceCounter("Physics");
  8881. }
  8882. // Customs render targets
  8883. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8884. var engine = this.getEngine();
  8885. var currentActiveCamera = this.activeCamera;
  8886. if (this.renderTargetsEnabled) {
  8887. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8888. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8889. var renderTarget = this.customRenderTargets[customIndex];
  8890. if (renderTarget._shouldRender()) {
  8891. this._renderId++;
  8892. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8893. if (!this.activeCamera)
  8894. throw new Error("Active camera not set");
  8895. // Viewport
  8896. engine.setViewport(this.activeCamera.viewport);
  8897. // Camera
  8898. this.updateTransformMatrix();
  8899. renderTarget.render(false, this.dumpNextRenderTargets);
  8900. }
  8901. }
  8902. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8903. this._renderId++;
  8904. }
  8905. if (this.customRenderTargets.length > 0) {
  8906. engine.restoreDefaultFramebuffer();
  8907. }
  8908. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8909. this.activeCamera = currentActiveCamera;
  8910. // Procedural textures
  8911. if (this.proceduralTexturesEnabled) {
  8912. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8913. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8914. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8915. if (proceduralTexture._shouldRender()) {
  8916. proceduralTexture.render();
  8917. }
  8918. }
  8919. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8920. }
  8921. // Clear
  8922. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8923. // Shadows
  8924. if (this.shadowsEnabled) {
  8925. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8926. var light = this.lights[lightIndex];
  8927. var shadowGenerator = light.getShadowGenerator();
  8928. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8929. this._renderTargets.push(shadowGenerator.getShadowMap());
  8930. }
  8931. }
  8932. }
  8933. // Depth renderer
  8934. if (this._depthRenderer) {
  8935. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8936. }
  8937. // RenderPipeline
  8938. this.postProcessRenderPipelineManager.update();
  8939. // Multi-cameras?
  8940. if (this.activeCameras.length > 0) {
  8941. var currentRenderId = this._renderId;
  8942. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8943. this._renderId = currentRenderId;
  8944. this._processSubCameras(this.activeCameras[cameraIndex]);
  8945. }
  8946. }
  8947. else {
  8948. if (!this.activeCamera) {
  8949. throw new Error("No camera defined");
  8950. }
  8951. this._processSubCameras(this.activeCamera);
  8952. }
  8953. // Intersection checks
  8954. this._checkIntersections();
  8955. // Update the audio listener attached to the camera
  8956. this._updateAudioParameters();
  8957. // After render
  8958. if (this.afterRender) {
  8959. this.afterRender();
  8960. }
  8961. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8962. this._onAfterRenderCallbacks[callbackIndex]();
  8963. }
  8964. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8965. this._toBeDisposed.data[index].dispose();
  8966. this._toBeDisposed[index] = null;
  8967. }
  8968. this._toBeDisposed.reset();
  8969. if (this.dumpNextRenderTargets) {
  8970. this.dumpNextRenderTargets = false;
  8971. }
  8972. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8973. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8974. };
  8975. Scene.prototype._updateAudioParameters = function () {
  8976. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8977. return;
  8978. }
  8979. var listeningCamera;
  8980. var audioEngine = BABYLON.Engine.audioEngine;
  8981. if (this.activeCameras.length > 0) {
  8982. listeningCamera = this.activeCameras[0];
  8983. }
  8984. else {
  8985. listeningCamera = this.activeCamera;
  8986. }
  8987. if (listeningCamera && audioEngine.canUseWebAudio) {
  8988. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8989. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8990. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8991. cameraDirection.normalize();
  8992. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8993. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8994. var sound = this.mainSoundTrack.soundCollection[i];
  8995. if (sound.useCustomAttenuation) {
  8996. sound.updateDistanceFromListener();
  8997. }
  8998. }
  8999. for (i = 0; i < this.soundTracks.length; i++) {
  9000. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9001. sound = this.soundTracks[i].soundCollection[j];
  9002. if (sound.useCustomAttenuation) {
  9003. sound.updateDistanceFromListener();
  9004. }
  9005. }
  9006. }
  9007. }
  9008. };
  9009. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9010. // Audio
  9011. get: function () {
  9012. return this._audioEnabled;
  9013. },
  9014. set: function (value) {
  9015. this._audioEnabled = value;
  9016. if (this._audioEnabled) {
  9017. this._enableAudio();
  9018. }
  9019. else {
  9020. this._disableAudio();
  9021. }
  9022. },
  9023. enumerable: true,
  9024. configurable: true
  9025. });
  9026. Scene.prototype._disableAudio = function () {
  9027. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9028. this.mainSoundTrack.soundCollection[i].pause();
  9029. }
  9030. for (i = 0; i < this.soundTracks.length; i++) {
  9031. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9032. this.soundTracks[i].soundCollection[j].pause();
  9033. }
  9034. }
  9035. };
  9036. Scene.prototype._enableAudio = function () {
  9037. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9038. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9039. this.mainSoundTrack.soundCollection[i].play();
  9040. }
  9041. }
  9042. for (i = 0; i < this.soundTracks.length; i++) {
  9043. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9044. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9045. this.soundTracks[i].soundCollection[j].play();
  9046. }
  9047. }
  9048. }
  9049. };
  9050. Object.defineProperty(Scene.prototype, "headphone", {
  9051. get: function () {
  9052. return this._headphone;
  9053. },
  9054. set: function (value) {
  9055. this._headphone = value;
  9056. if (this._headphone) {
  9057. this._switchAudioModeForHeadphones();
  9058. }
  9059. else {
  9060. this._switchAudioModeForNormalSpeakers();
  9061. }
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. Scene.prototype._switchAudioModeForHeadphones = function () {
  9067. this.mainSoundTrack.switchPanningModelToHRTF();
  9068. for (var i = 0; i < this.soundTracks.length; i++) {
  9069. this.soundTracks[i].switchPanningModelToHRTF();
  9070. }
  9071. };
  9072. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9073. this.mainSoundTrack.switchPanningModelToEqualPower();
  9074. for (var i = 0; i < this.soundTracks.length; i++) {
  9075. this.soundTracks[i].switchPanningModelToEqualPower();
  9076. }
  9077. };
  9078. Scene.prototype.enableDepthRenderer = function () {
  9079. if (this._depthRenderer) {
  9080. return this._depthRenderer;
  9081. }
  9082. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9083. return this._depthRenderer;
  9084. };
  9085. Scene.prototype.disableDepthRenderer = function () {
  9086. if (!this._depthRenderer) {
  9087. return;
  9088. }
  9089. this._depthRenderer.dispose();
  9090. this._depthRenderer = null;
  9091. };
  9092. Scene.prototype.dispose = function () {
  9093. this.beforeRender = null;
  9094. this.afterRender = null;
  9095. this.skeletons = [];
  9096. this._boundingBoxRenderer.dispose();
  9097. if (this._depthRenderer) {
  9098. this._depthRenderer.dispose();
  9099. }
  9100. // Debug layer
  9101. this.debugLayer.hide();
  9102. // Events
  9103. if (this.onDispose) {
  9104. this.onDispose();
  9105. }
  9106. this._onBeforeRenderCallbacks = [];
  9107. this._onAfterRenderCallbacks = [];
  9108. this.detachControl();
  9109. // Release sounds & sounds tracks
  9110. this.disposeSounds();
  9111. // Detach cameras
  9112. var canvas = this._engine.getRenderingCanvas();
  9113. var index;
  9114. for (index = 0; index < this.cameras.length; index++) {
  9115. this.cameras[index].detachControl(canvas);
  9116. }
  9117. while (this.lights.length) {
  9118. this.lights[0].dispose();
  9119. }
  9120. while (this.meshes.length) {
  9121. this.meshes[0].dispose(true);
  9122. }
  9123. while (this.cameras.length) {
  9124. this.cameras[0].dispose();
  9125. }
  9126. while (this.materials.length) {
  9127. this.materials[0].dispose();
  9128. }
  9129. while (this.particleSystems.length) {
  9130. this.particleSystems[0].dispose();
  9131. }
  9132. while (this.spriteManagers.length) {
  9133. this.spriteManagers[0].dispose();
  9134. }
  9135. while (this.layers.length) {
  9136. this.layers[0].dispose();
  9137. }
  9138. while (this.textures.length) {
  9139. this.textures[0].dispose();
  9140. }
  9141. // Post-processes
  9142. this.postProcessManager.dispose();
  9143. // Physics
  9144. if (this._physicsEngine) {
  9145. this.disablePhysicsEngine();
  9146. }
  9147. // Remove from engine
  9148. index = this._engine.scenes.indexOf(this);
  9149. if (index > -1) {
  9150. this._engine.scenes.splice(index, 1);
  9151. }
  9152. this._engine.wipeCaches();
  9153. };
  9154. // Release sounds & sounds tracks
  9155. Scene.prototype.disposeSounds = function () {
  9156. this.mainSoundTrack.dispose();
  9157. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9158. this.soundTracks[scIndex].dispose();
  9159. }
  9160. };
  9161. // Collisions
  9162. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9163. if (excludedMesh === void 0) { excludedMesh = null; }
  9164. position.divideToRef(collider.radius, this._scaledPosition);
  9165. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9166. collider.retry = 0;
  9167. collider.initialVelocity = this._scaledVelocity;
  9168. collider.initialPosition = this._scaledPosition;
  9169. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9170. finalPosition.multiplyInPlace(collider.radius);
  9171. };
  9172. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9173. if (excludedMesh === void 0) { excludedMesh = null; }
  9174. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9175. if (collider.retry >= maximumRetry) {
  9176. finalPosition.copyFrom(position);
  9177. return;
  9178. }
  9179. collider._initialize(position, velocity, closeDistance);
  9180. for (var index = 0; index < this.meshes.length; index++) {
  9181. var mesh = this.meshes[index];
  9182. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9183. mesh._checkCollision(collider);
  9184. }
  9185. }
  9186. if (!collider.collisionFound) {
  9187. position.addToRef(velocity, finalPosition);
  9188. return;
  9189. }
  9190. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9191. collider._getResponse(position, velocity);
  9192. }
  9193. if (velocity.length() <= closeDistance) {
  9194. finalPosition.copyFrom(position);
  9195. return;
  9196. }
  9197. collider.retry++;
  9198. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9199. };
  9200. // Octrees
  9201. Scene.prototype.getWorldExtends = function () {
  9202. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9203. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9204. for (var index = 0; index < this.meshes.length; index++) {
  9205. var mesh = this.meshes[index];
  9206. mesh.computeWorldMatrix(true);
  9207. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9208. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9209. BABYLON.Tools.CheckExtends(minBox, min, max);
  9210. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9211. }
  9212. return {
  9213. min: min,
  9214. max: max
  9215. };
  9216. };
  9217. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9218. if (maxCapacity === void 0) { maxCapacity = 64; }
  9219. if (maxDepth === void 0) { maxDepth = 2; }
  9220. if (!this._selectionOctree) {
  9221. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9222. }
  9223. var worldExtends = this.getWorldExtends();
  9224. // Update octree
  9225. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9226. return this._selectionOctree;
  9227. };
  9228. // Picking
  9229. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9230. var engine = this._engine;
  9231. if (!camera) {
  9232. if (!this.activeCamera)
  9233. throw new Error("Active camera not set");
  9234. camera = this.activeCamera;
  9235. }
  9236. var cameraViewport = camera.viewport;
  9237. var viewport = cameraViewport.toGlobal(engine);
  9238. // Moving coordinates to local viewport world
  9239. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9240. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9241. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9242. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9243. };
  9244. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9245. var pickingInfo = null;
  9246. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9247. var mesh = this.meshes[meshIndex];
  9248. if (predicate) {
  9249. if (!predicate(mesh)) {
  9250. continue;
  9251. }
  9252. }
  9253. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9254. continue;
  9255. }
  9256. var world = mesh.getWorldMatrix();
  9257. var ray = rayFunction(world);
  9258. var result = mesh.intersects(ray, fastCheck);
  9259. if (!result || !result.hit)
  9260. continue;
  9261. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9262. continue;
  9263. pickingInfo = result;
  9264. if (fastCheck) {
  9265. break;
  9266. }
  9267. }
  9268. return pickingInfo || new BABYLON.PickingInfo();
  9269. };
  9270. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9271. var _this = this;
  9272. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9273. /// <param name="x">X position on screen</param>
  9274. /// <param name="y">Y position on screen</param>
  9275. /// <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>
  9276. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9277. /// <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>
  9278. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9279. };
  9280. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9281. var _this = this;
  9282. return this._internalPick(function (world) {
  9283. if (!_this._pickWithRayInverseMatrix) {
  9284. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9285. }
  9286. world.invertToRef(_this._pickWithRayInverseMatrix);
  9287. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9288. }, predicate, fastCheck);
  9289. };
  9290. Scene.prototype.setPointerOverMesh = function (mesh) {
  9291. if (this._pointerOverMesh === mesh) {
  9292. return;
  9293. }
  9294. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9295. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9296. }
  9297. this._pointerOverMesh = mesh;
  9298. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9299. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9300. }
  9301. };
  9302. Scene.prototype.getPointerOverMesh = function () {
  9303. return this._pointerOverMesh;
  9304. };
  9305. // Physics
  9306. Scene.prototype.getPhysicsEngine = function () {
  9307. return this._physicsEngine;
  9308. };
  9309. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9310. if (this._physicsEngine) {
  9311. return true;
  9312. }
  9313. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9314. if (!this._physicsEngine.isSupported()) {
  9315. this._physicsEngine = null;
  9316. return false;
  9317. }
  9318. this._physicsEngine._initialize(gravity);
  9319. return true;
  9320. };
  9321. Scene.prototype.disablePhysicsEngine = function () {
  9322. if (!this._physicsEngine) {
  9323. return;
  9324. }
  9325. this._physicsEngine.dispose();
  9326. this._physicsEngine = undefined;
  9327. };
  9328. Scene.prototype.isPhysicsEnabled = function () {
  9329. return this._physicsEngine !== undefined;
  9330. };
  9331. Scene.prototype.setGravity = function (gravity) {
  9332. if (!this._physicsEngine) {
  9333. return;
  9334. }
  9335. this._physicsEngine._setGravity(gravity);
  9336. };
  9337. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9338. if (parts.parts) {
  9339. options = parts;
  9340. parts = parts.parts;
  9341. }
  9342. if (!this._physicsEngine) {
  9343. return null;
  9344. }
  9345. for (var index = 0; index < parts.length; index++) {
  9346. var mesh = parts[index].mesh;
  9347. mesh._physicImpostor = parts[index].impostor;
  9348. mesh._physicsMass = options.mass / parts.length;
  9349. mesh._physicsFriction = options.friction;
  9350. mesh._physicRestitution = options.restitution;
  9351. }
  9352. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9353. };
  9354. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9355. for (var index = 0; index < compound.parts.length; index++) {
  9356. var mesh = compound.parts[index].mesh;
  9357. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9358. this._physicsEngine._unregisterMesh(mesh);
  9359. }
  9360. };
  9361. // Misc.
  9362. Scene.prototype.createDefaultCameraOrLight = function () {
  9363. // Light
  9364. if (this.lights.length === 0) {
  9365. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9366. }
  9367. // Camera
  9368. if (!this.activeCamera) {
  9369. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9370. // Compute position
  9371. var worldExtends = this.getWorldExtends();
  9372. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9373. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9374. camera.setTarget(worldCenter);
  9375. this.activeCamera = camera;
  9376. }
  9377. };
  9378. // Tags
  9379. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9380. if (tagsQuery === undefined) {
  9381. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9382. return list;
  9383. }
  9384. var listByTags = [];
  9385. forEach = forEach || (function (item) {
  9386. return;
  9387. });
  9388. for (var i in list) {
  9389. var item = list[i];
  9390. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9391. listByTags.push(item);
  9392. forEach(item);
  9393. }
  9394. }
  9395. return listByTags;
  9396. };
  9397. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9398. return this._getByTags(this.meshes, tagsQuery, forEach);
  9399. };
  9400. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9401. return this._getByTags(this.cameras, tagsQuery, forEach);
  9402. };
  9403. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9404. return this._getByTags(this.lights, tagsQuery, forEach);
  9405. };
  9406. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9407. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9408. };
  9409. // Statics
  9410. Scene._FOGMODE_NONE = 0;
  9411. Scene._FOGMODE_EXP = 1;
  9412. Scene._FOGMODE_EXP2 = 2;
  9413. Scene._FOGMODE_LINEAR = 3;
  9414. Scene.MinDeltaTime = 1.0;
  9415. Scene.MaxDeltaTime = 1000.0;
  9416. return Scene;
  9417. })();
  9418. BABYLON.Scene = Scene;
  9419. })(BABYLON || (BABYLON = {}));
  9420. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9421. (function (BABYLON) {
  9422. var VertexBuffer = (function () {
  9423. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9424. if (engine instanceof BABYLON.Mesh) {
  9425. this._engine = engine.getScene().getEngine();
  9426. }
  9427. else {
  9428. this._engine = engine;
  9429. }
  9430. this._updatable = updatable;
  9431. this._data = data;
  9432. if (!postponeInternalCreation) {
  9433. this.create();
  9434. }
  9435. this._kind = kind;
  9436. if (stride) {
  9437. this._strideSize = stride;
  9438. return;
  9439. }
  9440. switch (kind) {
  9441. case VertexBuffer.PositionKind:
  9442. this._strideSize = 3;
  9443. break;
  9444. case VertexBuffer.NormalKind:
  9445. this._strideSize = 3;
  9446. break;
  9447. case VertexBuffer.UVKind:
  9448. this._strideSize = 2;
  9449. break;
  9450. case VertexBuffer.UV2Kind:
  9451. this._strideSize = 2;
  9452. break;
  9453. case VertexBuffer.ColorKind:
  9454. this._strideSize = 4;
  9455. break;
  9456. case VertexBuffer.MatricesIndicesKind:
  9457. this._strideSize = 4;
  9458. break;
  9459. case VertexBuffer.MatricesWeightsKind:
  9460. this._strideSize = 4;
  9461. break;
  9462. }
  9463. }
  9464. // Properties
  9465. VertexBuffer.prototype.isUpdatable = function () {
  9466. return this._updatable;
  9467. };
  9468. VertexBuffer.prototype.getData = function () {
  9469. return this._data;
  9470. };
  9471. VertexBuffer.prototype.getBuffer = function () {
  9472. return this._buffer;
  9473. };
  9474. VertexBuffer.prototype.getStrideSize = function () {
  9475. return this._strideSize;
  9476. };
  9477. // Methods
  9478. VertexBuffer.prototype.create = function (data) {
  9479. if (!data && this._buffer) {
  9480. return; // nothing to do
  9481. }
  9482. data = data || this._data;
  9483. if (!this._buffer) {
  9484. if (this._updatable) {
  9485. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9486. }
  9487. else {
  9488. this._buffer = this._engine.createVertexBuffer(data);
  9489. }
  9490. }
  9491. if (this._updatable) {
  9492. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9493. this._data = data;
  9494. }
  9495. };
  9496. VertexBuffer.prototype.update = function (data) {
  9497. this.create(data);
  9498. };
  9499. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9500. if (!this._buffer) {
  9501. return;
  9502. }
  9503. if (this._updatable) {
  9504. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9505. this._data = null;
  9506. }
  9507. };
  9508. VertexBuffer.prototype.dispose = function () {
  9509. if (!this._buffer) {
  9510. return;
  9511. }
  9512. if (this._engine._releaseBuffer(this._buffer)) {
  9513. this._buffer = null;
  9514. }
  9515. };
  9516. Object.defineProperty(VertexBuffer, "PositionKind", {
  9517. get: function () {
  9518. return VertexBuffer._PositionKind;
  9519. },
  9520. enumerable: true,
  9521. configurable: true
  9522. });
  9523. Object.defineProperty(VertexBuffer, "NormalKind", {
  9524. get: function () {
  9525. return VertexBuffer._NormalKind;
  9526. },
  9527. enumerable: true,
  9528. configurable: true
  9529. });
  9530. Object.defineProperty(VertexBuffer, "UVKind", {
  9531. get: function () {
  9532. return VertexBuffer._UVKind;
  9533. },
  9534. enumerable: true,
  9535. configurable: true
  9536. });
  9537. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9538. get: function () {
  9539. return VertexBuffer._UV2Kind;
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. Object.defineProperty(VertexBuffer, "ColorKind", {
  9545. get: function () {
  9546. return VertexBuffer._ColorKind;
  9547. },
  9548. enumerable: true,
  9549. configurable: true
  9550. });
  9551. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9552. get: function () {
  9553. return VertexBuffer._MatricesIndicesKind;
  9554. },
  9555. enumerable: true,
  9556. configurable: true
  9557. });
  9558. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9559. get: function () {
  9560. return VertexBuffer._MatricesWeightsKind;
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. // Enums
  9566. VertexBuffer._PositionKind = "position";
  9567. VertexBuffer._NormalKind = "normal";
  9568. VertexBuffer._UVKind = "uv";
  9569. VertexBuffer._UV2Kind = "uv2";
  9570. VertexBuffer._ColorKind = "color";
  9571. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9572. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9573. return VertexBuffer;
  9574. })();
  9575. BABYLON.VertexBuffer = VertexBuffer;
  9576. })(BABYLON || (BABYLON = {}));
  9577. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9578. var BABYLON;
  9579. (function (BABYLON) {
  9580. var AbstractMesh = (function (_super) {
  9581. __extends(AbstractMesh, _super);
  9582. function AbstractMesh(name, scene) {
  9583. _super.call(this, name, scene);
  9584. // Properties
  9585. this.definedFacingForward = true; // orientation for POV movement & rotation
  9586. this.position = new BABYLON.Vector3(0, 0, 0);
  9587. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9588. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9589. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9590. this.visibility = 1.0;
  9591. this.alphaIndex = Number.MAX_VALUE;
  9592. this.infiniteDistance = false;
  9593. this.isVisible = true;
  9594. this.isPickable = true;
  9595. this.showBoundingBox = false;
  9596. this.showSubMeshesBoundingBox = false;
  9597. this.onDispose = null;
  9598. this.checkCollisions = false;
  9599. this.isBlocker = false;
  9600. this.renderingGroupId = 0;
  9601. this.receiveShadows = false;
  9602. this.renderOutline = false;
  9603. this.outlineColor = BABYLON.Color3.Red();
  9604. this.outlineWidth = 0.02;
  9605. this.renderOverlay = false;
  9606. this.overlayColor = BABYLON.Color3.Red();
  9607. this.overlayAlpha = 0.5;
  9608. this.hasVertexAlpha = false;
  9609. this.useVertexColors = true;
  9610. this.applyFog = true;
  9611. this.useOctreeForRenderingSelection = true;
  9612. this.useOctreeForPicking = true;
  9613. this.useOctreeForCollisions = true;
  9614. this.layerMask = 0xFFFFFFFF;
  9615. // Physics
  9616. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9617. // Collisions
  9618. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9619. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9620. this._collider = new BABYLON.Collider();
  9621. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9622. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9623. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9624. // Cache
  9625. this._localScaling = BABYLON.Matrix.Zero();
  9626. this._localRotation = BABYLON.Matrix.Zero();
  9627. this._localTranslation = BABYLON.Matrix.Zero();
  9628. this._localBillboard = BABYLON.Matrix.Zero();
  9629. this._localPivotScaling = BABYLON.Matrix.Zero();
  9630. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9631. this._localWorld = BABYLON.Matrix.Zero();
  9632. this._worldMatrix = BABYLON.Matrix.Zero();
  9633. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9634. this._absolutePosition = BABYLON.Vector3.Zero();
  9635. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9636. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9637. this._isDirty = false;
  9638. this._pivotMatrix = BABYLON.Matrix.Identity();
  9639. this._isDisposed = false;
  9640. this._renderId = 0;
  9641. this._intersectionsInProgress = new Array();
  9642. this._onAfterWorldMatrixUpdate = new Array();
  9643. scene.meshes.push(this);
  9644. }
  9645. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9646. get: function () {
  9647. return AbstractMesh._BILLBOARDMODE_NONE;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9653. get: function () {
  9654. return AbstractMesh._BILLBOARDMODE_X;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9660. get: function () {
  9661. return AbstractMesh._BILLBOARDMODE_Y;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9667. get: function () {
  9668. return AbstractMesh._BILLBOARDMODE_Z;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9674. get: function () {
  9675. return AbstractMesh._BILLBOARDMODE_ALL;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9681. // Methods
  9682. get: function () {
  9683. return false;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. AbstractMesh.prototype.getLOD = function (camera) {
  9689. return this;
  9690. };
  9691. AbstractMesh.prototype.getTotalVertices = function () {
  9692. return 0;
  9693. };
  9694. AbstractMesh.prototype.getIndices = function () {
  9695. return null;
  9696. };
  9697. AbstractMesh.prototype.getVerticesData = function (kind) {
  9698. return null;
  9699. };
  9700. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9701. return false;
  9702. };
  9703. AbstractMesh.prototype.getBoundingInfo = function () {
  9704. if (this._masterMesh) {
  9705. return this._masterMesh.getBoundingInfo();
  9706. }
  9707. if (!this._boundingInfo) {
  9708. this._updateBoundingInfo();
  9709. }
  9710. return this._boundingInfo;
  9711. };
  9712. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9713. get: function () {
  9714. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. AbstractMesh.prototype._preActivate = function () {
  9720. };
  9721. AbstractMesh.prototype._activate = function (renderId) {
  9722. this._renderId = renderId;
  9723. };
  9724. AbstractMesh.prototype.getWorldMatrix = function () {
  9725. if (this._masterMesh) {
  9726. return this._masterMesh.getWorldMatrix();
  9727. }
  9728. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9729. this.computeWorldMatrix();
  9730. }
  9731. return this._worldMatrix;
  9732. };
  9733. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9734. get: function () {
  9735. return this._worldMatrix;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9741. get: function () {
  9742. return this._absolutePosition;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9748. if (!this.rotationQuaternion) {
  9749. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9750. this.rotation = BABYLON.Vector3.Zero();
  9751. }
  9752. if (!space || space == 0 /* LOCAL */) {
  9753. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9754. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9755. }
  9756. else {
  9757. if (this.parent) {
  9758. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9759. invertParentWorldMatrix.invert();
  9760. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9761. }
  9762. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9763. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9764. }
  9765. };
  9766. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9767. var displacementVector = axis.scale(distance);
  9768. if (!space || space == 0 /* LOCAL */) {
  9769. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9770. this.setPositionWithLocalVector(tempV3);
  9771. }
  9772. else {
  9773. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9774. }
  9775. };
  9776. AbstractMesh.prototype.getAbsolutePosition = function () {
  9777. this.computeWorldMatrix();
  9778. return this._absolutePosition;
  9779. };
  9780. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9781. if (!absolutePosition) {
  9782. return;
  9783. }
  9784. var absolutePositionX;
  9785. var absolutePositionY;
  9786. var absolutePositionZ;
  9787. if (absolutePosition.x === undefined) {
  9788. if (arguments.length < 3) {
  9789. return;
  9790. }
  9791. absolutePositionX = arguments[0];
  9792. absolutePositionY = arguments[1];
  9793. absolutePositionZ = arguments[2];
  9794. }
  9795. else {
  9796. absolutePositionX = absolutePosition.x;
  9797. absolutePositionY = absolutePosition.y;
  9798. absolutePositionZ = absolutePosition.z;
  9799. }
  9800. if (this.parent) {
  9801. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9802. invertParentWorldMatrix.invert();
  9803. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9804. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9805. }
  9806. else {
  9807. this.position.x = absolutePositionX;
  9808. this.position.y = absolutePositionY;
  9809. this.position.z = absolutePositionZ;
  9810. }
  9811. };
  9812. // ================================== Point of View Movement =================================
  9813. /**
  9814. * Perform relative position change from the point of view of behind the front of the mesh.
  9815. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9816. * Supports definition of mesh facing forward or backward.
  9817. * @param {number} amountRight
  9818. * @param {number} amountUp
  9819. * @param {number} amountForward
  9820. */
  9821. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9822. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9823. };
  9824. /**
  9825. * Calculate relative position change from the point of view of behind the front of the mesh.
  9826. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9827. * Supports definition of mesh facing forward or backward.
  9828. * @param {number} amountRight
  9829. * @param {number} amountUp
  9830. * @param {number} amountForward
  9831. */
  9832. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9833. var rotMatrix = new BABYLON.Matrix();
  9834. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9835. rotQuaternion.toRotationMatrix(rotMatrix);
  9836. var translationDelta = BABYLON.Vector3.Zero();
  9837. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9839. return translationDelta;
  9840. };
  9841. // ================================== Point of View Rotation =================================
  9842. /**
  9843. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9844. * Supports definition of mesh facing forward or backward.
  9845. * @param {number} flipBack
  9846. * @param {number} twirlClockwise
  9847. * @param {number} tiltRight
  9848. */
  9849. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9850. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9851. };
  9852. /**
  9853. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9854. * Supports definition of mesh facing forward or backward.
  9855. * @param {number} flipBack
  9856. * @param {number} twirlClockwise
  9857. * @param {number} tiltRight
  9858. */
  9859. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9860. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9861. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9862. };
  9863. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9864. this._pivotMatrix = matrix;
  9865. this._cache.pivotMatrixUpdated = true;
  9866. };
  9867. AbstractMesh.prototype.getPivotMatrix = function () {
  9868. return this._pivotMatrix;
  9869. };
  9870. AbstractMesh.prototype._isSynchronized = function () {
  9871. if (this._isDirty) {
  9872. return false;
  9873. }
  9874. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9875. return false;
  9876. if (this._cache.pivotMatrixUpdated) {
  9877. return false;
  9878. }
  9879. if (this.infiniteDistance) {
  9880. return false;
  9881. }
  9882. if (!this._cache.position.equals(this.position))
  9883. return false;
  9884. if (this.rotationQuaternion) {
  9885. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9886. return false;
  9887. }
  9888. else {
  9889. if (!this._cache.rotation.equals(this.rotation))
  9890. return false;
  9891. }
  9892. if (!this._cache.scaling.equals(this.scaling))
  9893. return false;
  9894. return true;
  9895. };
  9896. AbstractMesh.prototype._initCache = function () {
  9897. _super.prototype._initCache.call(this);
  9898. this._cache.localMatrixUpdated = false;
  9899. this._cache.position = BABYLON.Vector3.Zero();
  9900. this._cache.scaling = BABYLON.Vector3.Zero();
  9901. this._cache.rotation = BABYLON.Vector3.Zero();
  9902. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9903. };
  9904. AbstractMesh.prototype.markAsDirty = function (property) {
  9905. if (property === "rotation") {
  9906. this.rotationQuaternion = null;
  9907. }
  9908. this._currentRenderId = Number.MAX_VALUE;
  9909. this._isDirty = true;
  9910. };
  9911. AbstractMesh.prototype._updateBoundingInfo = function () {
  9912. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9913. this._boundingInfo._update(this.worldMatrixFromCache);
  9914. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9915. };
  9916. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9917. if (!this.subMeshes) {
  9918. return;
  9919. }
  9920. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9921. var subMesh = this.subMeshes[subIndex];
  9922. subMesh.updateBoundingInfo(matrix);
  9923. }
  9924. };
  9925. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9926. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9927. return this._worldMatrix;
  9928. }
  9929. this._cache.position.copyFrom(this.position);
  9930. this._cache.scaling.copyFrom(this.scaling);
  9931. this._cache.pivotMatrixUpdated = false;
  9932. this._currentRenderId = this.getScene().getRenderId();
  9933. this._isDirty = false;
  9934. // Scaling
  9935. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9936. // Rotation
  9937. if (this.rotationQuaternion) {
  9938. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9939. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9940. }
  9941. else {
  9942. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9943. this._cache.rotation.copyFrom(this.rotation);
  9944. }
  9945. // Translation
  9946. if (this.infiniteDistance && !this.parent) {
  9947. var camera = this.getScene().activeCamera;
  9948. var cameraWorldMatrix = camera.getWorldMatrix();
  9949. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9950. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9951. }
  9952. else {
  9953. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9954. }
  9955. // Composing transformations
  9956. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9957. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9958. // Billboarding
  9959. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9960. var localPosition = this.position.clone();
  9961. var zero = this.getScene().activeCamera.position.clone();
  9962. if (this.parent && this.parent.position) {
  9963. localPosition.addInPlace(this.parent.position);
  9964. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9965. }
  9966. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9967. zero = this.getScene().activeCamera.position;
  9968. }
  9969. else {
  9970. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9971. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9972. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9973. zero.y = localPosition.y + 0.001;
  9974. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9975. zero.z = localPosition.z + 0.001;
  9976. }
  9977. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9978. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9979. this._localBillboard.invert();
  9980. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9981. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9982. }
  9983. // Local world
  9984. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9985. // Parent
  9986. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9987. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9988. }
  9989. else {
  9990. this._worldMatrix.copyFrom(this._localWorld);
  9991. }
  9992. // Bounding info
  9993. this._updateBoundingInfo();
  9994. // Absolute position
  9995. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9996. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9997. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9998. }
  9999. return this._worldMatrix;
  10000. };
  10001. /**
  10002. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10003. * @param func: callback function to add
  10004. */
  10005. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10006. this._onAfterWorldMatrixUpdate.push(func);
  10007. };
  10008. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10009. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10010. if (index > -1) {
  10011. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10012. }
  10013. };
  10014. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10015. this.computeWorldMatrix();
  10016. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10017. };
  10018. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10019. this.computeWorldMatrix();
  10020. var invLocalWorldMatrix = this._localWorld.clone();
  10021. invLocalWorldMatrix.invert();
  10022. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10023. };
  10024. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10025. this.computeWorldMatrix();
  10026. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10027. };
  10028. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10029. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10030. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  10031. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10032. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10033. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10034. /// <returns>Mesh oriented towards targetMesh</returns>
  10035. yawCor = yawCor || 0; // default to zero if undefined
  10036. pitchCor = pitchCor || 0;
  10037. rollCor = rollCor || 0;
  10038. var dv = targetPoint.subtract(this.position);
  10039. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10040. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10041. var pitch = Math.atan2(dv.y, len);
  10042. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10043. };
  10044. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10045. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10046. return false;
  10047. }
  10048. return true;
  10049. };
  10050. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10051. if (!camera) {
  10052. camera = this.getScene().activeCamera;
  10053. }
  10054. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10055. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10056. return false;
  10057. }
  10058. return true;
  10059. };
  10060. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10061. if (!this._boundingInfo || !mesh._boundingInfo) {
  10062. return false;
  10063. }
  10064. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10065. };
  10066. AbstractMesh.prototype.intersectsPoint = function (point) {
  10067. if (!this._boundingInfo) {
  10068. return false;
  10069. }
  10070. return this._boundingInfo.intersectsPoint(point);
  10071. };
  10072. // Physics
  10073. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10074. var physicsEngine = this.getScene().getPhysicsEngine();
  10075. if (!physicsEngine) {
  10076. return;
  10077. }
  10078. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10079. if (impostor.impostor) {
  10080. // Old API
  10081. options = impostor;
  10082. impostor = impostor.impostor;
  10083. }
  10084. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10085. physicsEngine._unregisterMesh(this);
  10086. return;
  10087. }
  10088. if (!options) {
  10089. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10090. }
  10091. else {
  10092. if (!options.mass && options.mass !== 0)
  10093. options.mass = 0;
  10094. if (!options.friction && options.friction !== 0)
  10095. options.friction = 0.2;
  10096. if (!options.restitution && options.restitution !== 0)
  10097. options.restitution = 0.2;
  10098. }
  10099. this._physicImpostor = impostor;
  10100. this._physicsMass = options.mass;
  10101. this._physicsFriction = options.friction;
  10102. this._physicRestitution = options.restitution;
  10103. return physicsEngine._registerMesh(this, impostor, options);
  10104. };
  10105. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10106. if (!this._physicImpostor) {
  10107. return BABYLON.PhysicsEngine.NoImpostor;
  10108. }
  10109. return this._physicImpostor;
  10110. };
  10111. AbstractMesh.prototype.getPhysicsMass = function () {
  10112. if (!this._physicsMass) {
  10113. return 0;
  10114. }
  10115. return this._physicsMass;
  10116. };
  10117. AbstractMesh.prototype.getPhysicsFriction = function () {
  10118. if (!this._physicsFriction) {
  10119. return 0;
  10120. }
  10121. return this._physicsFriction;
  10122. };
  10123. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10124. if (!this._physicRestitution) {
  10125. return 0;
  10126. }
  10127. return this._physicRestitution;
  10128. };
  10129. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10130. if (!camera) {
  10131. camera = this.getScene().activeCamera;
  10132. }
  10133. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10134. };
  10135. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10136. if (!camera) {
  10137. camera = this.getScene().activeCamera;
  10138. }
  10139. return this.absolutePosition.subtract(camera.position).length();
  10140. };
  10141. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10142. if (!this._physicImpostor) {
  10143. return;
  10144. }
  10145. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10146. };
  10147. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10148. if (!this._physicImpostor) {
  10149. return;
  10150. }
  10151. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10152. };
  10153. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10154. if (!this._physicImpostor) {
  10155. return;
  10156. }
  10157. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10158. };
  10159. // Collisions
  10160. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10161. var globalPosition = this.getAbsolutePosition();
  10162. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10163. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10164. this._collider.radius = this.ellipsoid;
  10165. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10166. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10167. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10168. this.position.addInPlace(this._diffPositionForCollisions);
  10169. }
  10170. };
  10171. // Submeshes octree
  10172. /**
  10173. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10174. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10175. */
  10176. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10177. if (maxCapacity === void 0) { maxCapacity = 64; }
  10178. if (maxDepth === void 0) { maxDepth = 2; }
  10179. if (!this._submeshesOctree) {
  10180. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10181. }
  10182. this.computeWorldMatrix(true);
  10183. // Update octree
  10184. var bbox = this.getBoundingInfo().boundingBox;
  10185. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10186. return this._submeshesOctree;
  10187. };
  10188. // Collisions
  10189. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10190. this._generatePointsArray();
  10191. // Transformation
  10192. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10193. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10194. subMesh._lastColliderWorldVertices = [];
  10195. subMesh._trianglePlanes = [];
  10196. var start = subMesh.verticesStart;
  10197. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10198. for (var i = start; i < end; i++) {
  10199. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10200. }
  10201. }
  10202. // Collide
  10203. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10204. };
  10205. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10206. var subMeshes;
  10207. var len;
  10208. // Octrees
  10209. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10210. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10211. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10212. len = intersections.length;
  10213. subMeshes = intersections.data;
  10214. }
  10215. else {
  10216. subMeshes = this.subMeshes;
  10217. len = subMeshes.length;
  10218. }
  10219. for (var index = 0; index < len; index++) {
  10220. var subMesh = subMeshes[index];
  10221. // Bounding test
  10222. if (len > 1 && !subMesh._checkCollision(collider))
  10223. continue;
  10224. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10225. }
  10226. };
  10227. AbstractMesh.prototype._checkCollision = function (collider) {
  10228. // Bounding box test
  10229. if (!this._boundingInfo._checkCollision(collider))
  10230. return;
  10231. // Transformation matrix
  10232. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10233. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10234. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10235. };
  10236. // Picking
  10237. AbstractMesh.prototype._generatePointsArray = function () {
  10238. return false;
  10239. };
  10240. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10241. var pickingInfo = new BABYLON.PickingInfo();
  10242. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10243. return pickingInfo;
  10244. }
  10245. if (!this._generatePointsArray()) {
  10246. return pickingInfo;
  10247. }
  10248. var intersectInfo = null;
  10249. // Octrees
  10250. var subMeshes;
  10251. var len;
  10252. if (this._submeshesOctree && this.useOctreeForPicking) {
  10253. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10254. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10255. len = intersections.length;
  10256. subMeshes = intersections.data;
  10257. }
  10258. else {
  10259. subMeshes = this.subMeshes;
  10260. len = subMeshes.length;
  10261. }
  10262. for (var index = 0; index < len; index++) {
  10263. var subMesh = subMeshes[index];
  10264. // Bounding test
  10265. if (len > 1 && !subMesh.canIntersects(ray))
  10266. continue;
  10267. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10268. if (currentIntersectInfo) {
  10269. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10270. intersectInfo = currentIntersectInfo;
  10271. intersectInfo.subMeshId = index;
  10272. if (fastCheck) {
  10273. break;
  10274. }
  10275. }
  10276. }
  10277. }
  10278. if (intersectInfo) {
  10279. // Get picked point
  10280. var world = this.getWorldMatrix();
  10281. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10282. var direction = ray.direction.clone();
  10283. direction = direction.scale(intersectInfo.distance);
  10284. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10285. var pickedPoint = worldOrigin.add(worldDirection);
  10286. // Return result
  10287. pickingInfo.hit = true;
  10288. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10289. pickingInfo.pickedPoint = pickedPoint;
  10290. pickingInfo.pickedMesh = this;
  10291. pickingInfo.bu = intersectInfo.bu;
  10292. pickingInfo.bv = intersectInfo.bv;
  10293. pickingInfo.faceId = intersectInfo.faceId;
  10294. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10295. return pickingInfo;
  10296. }
  10297. return pickingInfo;
  10298. };
  10299. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10300. return null;
  10301. };
  10302. AbstractMesh.prototype.releaseSubMeshes = function () {
  10303. if (this.subMeshes) {
  10304. while (this.subMeshes.length) {
  10305. this.subMeshes[0].dispose();
  10306. }
  10307. }
  10308. else {
  10309. this.subMeshes = new Array();
  10310. }
  10311. };
  10312. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10313. // Physics
  10314. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10315. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10316. }
  10317. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10318. var other = this._intersectionsInProgress[index];
  10319. var pos = other._intersectionsInProgress.indexOf(this);
  10320. other._intersectionsInProgress.splice(pos, 1);
  10321. }
  10322. this._intersectionsInProgress = [];
  10323. // SubMeshes
  10324. this.releaseSubMeshes();
  10325. // Remove from scene
  10326. var index = this.getScene().meshes.indexOf(this);
  10327. if (index != -1) {
  10328. // Remove from the scene if mesh found
  10329. this.getScene().meshes.splice(index, 1);
  10330. }
  10331. if (!doNotRecurse) {
  10332. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10333. if (this.getScene().particleSystems[index].emitter == this) {
  10334. this.getScene().particleSystems[index].dispose();
  10335. index--;
  10336. }
  10337. }
  10338. // Children
  10339. var objects = this.getScene().meshes.slice(0);
  10340. for (index = 0; index < objects.length; index++) {
  10341. if (objects[index].parent == this) {
  10342. objects[index].dispose();
  10343. }
  10344. }
  10345. }
  10346. else {
  10347. for (index = 0; index < this.getScene().meshes.length; index++) {
  10348. var obj = this.getScene().meshes[index];
  10349. if (obj.parent === this) {
  10350. obj.parent = null;
  10351. obj.computeWorldMatrix(true);
  10352. }
  10353. }
  10354. }
  10355. this._onAfterWorldMatrixUpdate = [];
  10356. this._isDisposed = true;
  10357. // Callback
  10358. if (this.onDispose) {
  10359. this.onDispose();
  10360. }
  10361. };
  10362. // Statics
  10363. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10364. AbstractMesh._BILLBOARDMODE_X = 1;
  10365. AbstractMesh._BILLBOARDMODE_Y = 2;
  10366. AbstractMesh._BILLBOARDMODE_Z = 4;
  10367. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10368. return AbstractMesh;
  10369. })(BABYLON.Node);
  10370. BABYLON.AbstractMesh = AbstractMesh;
  10371. })(BABYLON || (BABYLON = {}));
  10372. //# sourceMappingURL=babylon.abstractMesh.js.map
  10373. var BABYLON;
  10374. (function (BABYLON) {
  10375. var _InstancesBatch = (function () {
  10376. function _InstancesBatch() {
  10377. this.mustReturn = false;
  10378. this.visibleInstances = new Array();
  10379. this.renderSelf = new Array();
  10380. }
  10381. return _InstancesBatch;
  10382. })();
  10383. BABYLON._InstancesBatch = _InstancesBatch;
  10384. var Mesh = (function (_super) {
  10385. __extends(Mesh, _super);
  10386. /**
  10387. * @constructor
  10388. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10389. * @param {Scene} scene - The scene to add this mesh to.
  10390. * @param {Node} parent - The parent of this mesh, if it has one
  10391. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10392. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10393. * When false, achieved by calling a clone(), also passing False.
  10394. * This will make creation of children, recursive.
  10395. */
  10396. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10397. if (parent === void 0) { parent = null; }
  10398. _super.call(this, name, scene);
  10399. // Members
  10400. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10401. this.instances = new Array();
  10402. this._LODLevels = new Array();
  10403. this._onBeforeRenderCallbacks = new Array();
  10404. this._onAfterRenderCallbacks = new Array();
  10405. this._visibleInstances = {};
  10406. this._renderIdForInstances = new Array();
  10407. this._batchCache = new _InstancesBatch();
  10408. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10409. if (source) {
  10410. // Geometry
  10411. if (source._geometry) {
  10412. source._geometry.applyToMesh(this);
  10413. }
  10414. // Deep copy
  10415. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10416. // Material
  10417. this.material = source.material;
  10418. if (!doNotCloneChildren) {
  10419. for (var index = 0; index < scene.meshes.length; index++) {
  10420. var mesh = scene.meshes[index];
  10421. if (mesh.parent === source) {
  10422. // doNotCloneChildren is always going to be False
  10423. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10424. }
  10425. }
  10426. }
  10427. for (index = 0; index < scene.particleSystems.length; index++) {
  10428. var system = scene.particleSystems[index];
  10429. if (system.emitter === source) {
  10430. system.clone(system.name, this);
  10431. }
  10432. }
  10433. this.computeWorldMatrix(true);
  10434. }
  10435. // Parent
  10436. if (parent !== null) {
  10437. this.parent = parent;
  10438. }
  10439. }
  10440. Object.defineProperty(Mesh, "FRONTSIDE", {
  10441. get: function () {
  10442. return Mesh._FRONTSIDE;
  10443. },
  10444. enumerable: true,
  10445. configurable: true
  10446. });
  10447. Object.defineProperty(Mesh, "BACKSIDE", {
  10448. get: function () {
  10449. return Mesh._BACKSIDE;
  10450. },
  10451. enumerable: true,
  10452. configurable: true
  10453. });
  10454. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10455. get: function () {
  10456. return Mesh._DOUBLESIDE;
  10457. },
  10458. enumerable: true,
  10459. configurable: true
  10460. });
  10461. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10462. get: function () {
  10463. return Mesh._DEFAULTSIDE;
  10464. },
  10465. enumerable: true,
  10466. configurable: true
  10467. });
  10468. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10469. // Methods
  10470. get: function () {
  10471. return this._LODLevels.length > 0;
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. Mesh.prototype._sortLODLevels = function () {
  10477. this._LODLevels.sort(function (a, b) {
  10478. if (a.distance < b.distance) {
  10479. return 1;
  10480. }
  10481. if (a.distance > b.distance) {
  10482. return -1;
  10483. }
  10484. return 0;
  10485. });
  10486. };
  10487. /**
  10488. * Add a mesh as LOD level triggered at the given distance.
  10489. * @param {number} distance - the distance from the center of the object to show this level
  10490. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10491. * @return {BABYLON.Mesh} this mesh (for chaining)
  10492. */
  10493. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10494. if (mesh && mesh._masterMesh) {
  10495. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10496. return this;
  10497. }
  10498. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10499. this._LODLevels.push(level);
  10500. if (mesh) {
  10501. mesh._masterMesh = this;
  10502. }
  10503. this._sortLODLevels();
  10504. return this;
  10505. };
  10506. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10507. for (var index = 0; index < this._LODLevels.length; index++) {
  10508. var level = this._LODLevels[index];
  10509. if (level.distance === distance) {
  10510. return level.mesh;
  10511. }
  10512. }
  10513. return null;
  10514. };
  10515. /**
  10516. * Remove a mesh from the LOD array
  10517. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10518. * @return {BABYLON.Mesh} this mesh (for chaining)
  10519. */
  10520. Mesh.prototype.removeLODLevel = function (mesh) {
  10521. for (var index = 0; index < this._LODLevels.length; index++) {
  10522. if (this._LODLevels[index].mesh === mesh) {
  10523. this._LODLevels.splice(index, 1);
  10524. if (mesh) {
  10525. mesh._masterMesh = null;
  10526. }
  10527. }
  10528. }
  10529. this._sortLODLevels();
  10530. return this;
  10531. };
  10532. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10533. if (!this._LODLevels || this._LODLevels.length === 0) {
  10534. return this;
  10535. }
  10536. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10537. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10538. return this;
  10539. }
  10540. for (var index = 0; index < this._LODLevels.length; index++) {
  10541. var level = this._LODLevels[index];
  10542. if (level.distance < distanceToCamera) {
  10543. if (level.mesh) {
  10544. level.mesh._preActivate();
  10545. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10546. }
  10547. return level.mesh;
  10548. }
  10549. }
  10550. return this;
  10551. };
  10552. Object.defineProperty(Mesh.prototype, "geometry", {
  10553. get: function () {
  10554. return this._geometry;
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Mesh.prototype.getTotalVertices = function () {
  10560. if (!this._geometry) {
  10561. return 0;
  10562. }
  10563. return this._geometry.getTotalVertices();
  10564. };
  10565. Mesh.prototype.getVerticesData = function (kind) {
  10566. if (!this._geometry) {
  10567. return null;
  10568. }
  10569. return this._geometry.getVerticesData(kind);
  10570. };
  10571. Mesh.prototype.getVertexBuffer = function (kind) {
  10572. if (!this._geometry) {
  10573. return undefined;
  10574. }
  10575. return this._geometry.getVertexBuffer(kind);
  10576. };
  10577. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10578. if (!this._geometry) {
  10579. if (this._delayInfo) {
  10580. return this._delayInfo.indexOf(kind) !== -1;
  10581. }
  10582. return false;
  10583. }
  10584. return this._geometry.isVerticesDataPresent(kind);
  10585. };
  10586. Mesh.prototype.getVerticesDataKinds = function () {
  10587. if (!this._geometry) {
  10588. var result = [];
  10589. if (this._delayInfo) {
  10590. for (var kind in this._delayInfo) {
  10591. result.push(kind);
  10592. }
  10593. }
  10594. return result;
  10595. }
  10596. return this._geometry.getVerticesDataKinds();
  10597. };
  10598. Mesh.prototype.getTotalIndices = function () {
  10599. if (!this._geometry) {
  10600. return 0;
  10601. }
  10602. return this._geometry.getTotalIndices();
  10603. };
  10604. Mesh.prototype.getIndices = function () {
  10605. if (!this._geometry) {
  10606. return [];
  10607. }
  10608. return this._geometry.getIndices();
  10609. };
  10610. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10611. get: function () {
  10612. return this._masterMesh !== null && this._masterMesh !== undefined;
  10613. },
  10614. enumerable: true,
  10615. configurable: true
  10616. });
  10617. Mesh.prototype.isReady = function () {
  10618. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10619. return false;
  10620. }
  10621. return _super.prototype.isReady.call(this);
  10622. };
  10623. Mesh.prototype.isDisposed = function () {
  10624. return this._isDisposed;
  10625. };
  10626. // Methods
  10627. Mesh.prototype._preActivate = function () {
  10628. var sceneRenderId = this.getScene().getRenderId();
  10629. if (this._preActivateId === sceneRenderId) {
  10630. return;
  10631. }
  10632. this._preActivateId = sceneRenderId;
  10633. this._visibleInstances = null;
  10634. };
  10635. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10636. if (!this._visibleInstances) {
  10637. this._visibleInstances = {};
  10638. this._visibleInstances.defaultRenderId = renderId;
  10639. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10640. }
  10641. if (!this._visibleInstances[renderId]) {
  10642. this._visibleInstances[renderId] = new Array();
  10643. }
  10644. this._visibleInstances[renderId].push(instance);
  10645. };
  10646. Mesh.prototype.refreshBoundingInfo = function () {
  10647. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10648. if (data) {
  10649. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10650. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10651. }
  10652. if (this.subMeshes) {
  10653. for (var index = 0; index < this.subMeshes.length; index++) {
  10654. this.subMeshes[index].refreshBoundingInfo();
  10655. }
  10656. }
  10657. this._updateBoundingInfo();
  10658. };
  10659. Mesh.prototype._createGlobalSubMesh = function () {
  10660. var totalVertices = this.getTotalVertices();
  10661. if (!totalVertices || !this.getIndices()) {
  10662. return null;
  10663. }
  10664. this.releaseSubMeshes();
  10665. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10666. };
  10667. Mesh.prototype.subdivide = function (count) {
  10668. if (count < 1) {
  10669. return;
  10670. }
  10671. var totalIndices = this.getTotalIndices();
  10672. var subdivisionSize = (totalIndices / count) | 0;
  10673. var offset = 0;
  10674. while (subdivisionSize % 3 !== 0) {
  10675. subdivisionSize++;
  10676. }
  10677. this.releaseSubMeshes();
  10678. for (var index = 0; index < count; index++) {
  10679. if (offset >= totalIndices) {
  10680. break;
  10681. }
  10682. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10683. offset += subdivisionSize;
  10684. }
  10685. this.synchronizeInstances();
  10686. };
  10687. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10688. if (kind instanceof Array) {
  10689. var temp = data;
  10690. data = kind;
  10691. kind = temp;
  10692. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10693. }
  10694. if (!this._geometry) {
  10695. var vertexData = new BABYLON.VertexData();
  10696. vertexData.set(data, kind);
  10697. var scene = this.getScene();
  10698. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10699. }
  10700. else {
  10701. this._geometry.setVerticesData(kind, data, updatable, stride);
  10702. }
  10703. };
  10704. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10705. if (!this._geometry) {
  10706. return;
  10707. }
  10708. if (!makeItUnique) {
  10709. this._geometry.updateVerticesData(kind, data, updateExtends);
  10710. }
  10711. else {
  10712. this.makeGeometryUnique();
  10713. this.updateVerticesData(kind, data, updateExtends, false);
  10714. }
  10715. };
  10716. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10717. if (!this._geometry) {
  10718. return;
  10719. }
  10720. if (!makeItUnique) {
  10721. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10722. }
  10723. else {
  10724. this.makeGeometryUnique();
  10725. this.updateVerticesDataDirectly(kind, data, offset, false);
  10726. }
  10727. };
  10728. Mesh.prototype.makeGeometryUnique = function () {
  10729. if (!this._geometry) {
  10730. return;
  10731. }
  10732. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10733. geometry.applyToMesh(this);
  10734. };
  10735. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10736. if (!this._geometry) {
  10737. var vertexData = new BABYLON.VertexData();
  10738. vertexData.indices = indices;
  10739. var scene = this.getScene();
  10740. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10741. }
  10742. else {
  10743. this._geometry.setIndices(indices, totalVertices);
  10744. }
  10745. };
  10746. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10747. var engine = this.getScene().getEngine();
  10748. // Wireframe
  10749. var indexToBind;
  10750. switch (fillMode) {
  10751. case BABYLON.Material.PointFillMode:
  10752. indexToBind = null;
  10753. break;
  10754. case BABYLON.Material.WireFrameFillMode:
  10755. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10756. break;
  10757. default:
  10758. case BABYLON.Material.TriangleFillMode:
  10759. indexToBind = this._geometry.getIndexBuffer();
  10760. break;
  10761. }
  10762. // VBOs
  10763. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10764. };
  10765. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10766. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10767. return;
  10768. }
  10769. var engine = this.getScene().getEngine();
  10770. switch (fillMode) {
  10771. case BABYLON.Material.PointFillMode:
  10772. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10773. break;
  10774. case BABYLON.Material.WireFrameFillMode:
  10775. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10776. break;
  10777. default:
  10778. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10779. }
  10780. };
  10781. Mesh.prototype.registerBeforeRender = function (func) {
  10782. this._onBeforeRenderCallbacks.push(func);
  10783. };
  10784. Mesh.prototype.unregisterBeforeRender = function (func) {
  10785. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10786. if (index > -1) {
  10787. this._onBeforeRenderCallbacks.splice(index, 1);
  10788. }
  10789. };
  10790. Mesh.prototype.registerAfterRender = function (func) {
  10791. this._onAfterRenderCallbacks.push(func);
  10792. };
  10793. Mesh.prototype.unregisterAfterRender = function (func) {
  10794. var index = this._onAfterRenderCallbacks.indexOf(func);
  10795. if (index > -1) {
  10796. this._onAfterRenderCallbacks.splice(index, 1);
  10797. }
  10798. };
  10799. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10800. var scene = this.getScene();
  10801. this._batchCache.mustReturn = false;
  10802. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10803. this._batchCache.visibleInstances[subMeshId] = null;
  10804. if (this._visibleInstances) {
  10805. var currentRenderId = scene.getRenderId();
  10806. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10807. var selfRenderId = this._renderId;
  10808. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10809. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10810. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10811. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10812. }
  10813. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10814. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10815. this._batchCache.mustReturn = true;
  10816. return this._batchCache;
  10817. }
  10818. if (currentRenderId !== selfRenderId) {
  10819. this._batchCache.renderSelf[subMeshId] = false;
  10820. }
  10821. }
  10822. this._renderIdForInstances[subMeshId] = currentRenderId;
  10823. }
  10824. return this._batchCache;
  10825. };
  10826. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10827. var visibleInstances = batch.visibleInstances[subMesh._id];
  10828. var matricesCount = visibleInstances.length + 1;
  10829. var bufferSize = matricesCount * 16 * 4;
  10830. while (this._instancesBufferSize < bufferSize) {
  10831. this._instancesBufferSize *= 2;
  10832. }
  10833. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10834. if (this._worldMatricesInstancesBuffer) {
  10835. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10836. }
  10837. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10838. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10839. }
  10840. var offset = 0;
  10841. var instancesCount = 0;
  10842. var world = this.getWorldMatrix();
  10843. if (batch.renderSelf[subMesh._id]) {
  10844. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10845. offset += 16;
  10846. instancesCount++;
  10847. }
  10848. if (visibleInstances) {
  10849. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10850. var instance = visibleInstances[instanceIndex];
  10851. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10852. offset += 16;
  10853. instancesCount++;
  10854. }
  10855. }
  10856. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10857. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10858. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10859. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10860. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10861. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10862. this._draw(subMesh, fillMode, instancesCount);
  10863. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10864. };
  10865. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10866. var scene = this.getScene();
  10867. var engine = scene.getEngine();
  10868. if (hardwareInstancedRendering) {
  10869. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10870. }
  10871. else {
  10872. if (batch.renderSelf[subMesh._id]) {
  10873. // Draw
  10874. if (onBeforeDraw) {
  10875. onBeforeDraw(false, this.getWorldMatrix());
  10876. }
  10877. this._draw(subMesh, fillMode);
  10878. }
  10879. if (batch.visibleInstances[subMesh._id]) {
  10880. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10881. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10882. // World
  10883. var world = instance.getWorldMatrix();
  10884. if (onBeforeDraw) {
  10885. onBeforeDraw(true, world);
  10886. }
  10887. // Draw
  10888. this._draw(subMesh, fillMode);
  10889. }
  10890. }
  10891. }
  10892. };
  10893. Mesh.prototype.render = function (subMesh) {
  10894. var scene = this.getScene();
  10895. // Managing instances
  10896. var batch = this._getInstancesRenderList(subMesh._id);
  10897. if (batch.mustReturn) {
  10898. return;
  10899. }
  10900. // Checking geometry state
  10901. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10902. return;
  10903. }
  10904. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10905. this._onBeforeRenderCallbacks[callbackIndex](this);
  10906. }
  10907. var engine = scene.getEngine();
  10908. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10909. // Material
  10910. var effectiveMaterial = subMesh.getMaterial();
  10911. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10912. return;
  10913. }
  10914. // Outline - step 1
  10915. var savedDepthWrite = engine.getDepthWrite();
  10916. if (this.renderOutline) {
  10917. engine.setDepthWrite(false);
  10918. scene.getOutlineRenderer().render(subMesh, batch);
  10919. engine.setDepthWrite(savedDepthWrite);
  10920. }
  10921. effectiveMaterial._preBind();
  10922. var effect = effectiveMaterial.getEffect();
  10923. // Bind
  10924. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10925. this._bind(subMesh, effect, fillMode);
  10926. var world = this.getWorldMatrix();
  10927. effectiveMaterial.bind(world, this);
  10928. // Draw
  10929. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10930. if (isInstance) {
  10931. effectiveMaterial.bindOnlyWorldMatrix(world);
  10932. }
  10933. });
  10934. // Unbind
  10935. effectiveMaterial.unbind();
  10936. // Outline - step 2
  10937. if (this.renderOutline && savedDepthWrite) {
  10938. engine.setDepthWrite(true);
  10939. engine.setColorWrite(false);
  10940. scene.getOutlineRenderer().render(subMesh, batch);
  10941. engine.setColorWrite(true);
  10942. }
  10943. // Overlay
  10944. if (this.renderOverlay) {
  10945. var currentMode = engine.getAlphaMode();
  10946. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10947. scene.getOutlineRenderer().render(subMesh, batch, true);
  10948. engine.setAlphaMode(currentMode);
  10949. }
  10950. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10951. this._onAfterRenderCallbacks[callbackIndex](this);
  10952. }
  10953. };
  10954. Mesh.prototype.getEmittedParticleSystems = function () {
  10955. var results = new Array();
  10956. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10957. var particleSystem = this.getScene().particleSystems[index];
  10958. if (particleSystem.emitter === this) {
  10959. results.push(particleSystem);
  10960. }
  10961. }
  10962. return results;
  10963. };
  10964. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10965. var results = new Array();
  10966. var descendants = this.getDescendants();
  10967. descendants.push(this);
  10968. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10969. var particleSystem = this.getScene().particleSystems[index];
  10970. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10971. results.push(particleSystem);
  10972. }
  10973. }
  10974. return results;
  10975. };
  10976. Mesh.prototype.getChildren = function () {
  10977. var results = [];
  10978. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10979. var mesh = this.getScene().meshes[index];
  10980. if (mesh.parent === this) {
  10981. results.push(mesh);
  10982. }
  10983. }
  10984. return results;
  10985. };
  10986. Mesh.prototype._checkDelayState = function () {
  10987. var _this = this;
  10988. var that = this;
  10989. var scene = this.getScene();
  10990. if (this._geometry) {
  10991. this._geometry.load(scene);
  10992. }
  10993. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10994. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10995. scene._addPendingData(that);
  10996. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10997. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10998. if (data instanceof ArrayBuffer) {
  10999. _this._delayLoadingFunction(data, _this);
  11000. }
  11001. else {
  11002. _this._delayLoadingFunction(JSON.parse(data), _this);
  11003. }
  11004. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11005. scene._removePendingData(_this);
  11006. }, function () {
  11007. }, scene.database, getBinaryData);
  11008. }
  11009. };
  11010. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11011. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11012. return false;
  11013. }
  11014. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11015. return false;
  11016. }
  11017. this._checkDelayState();
  11018. return true;
  11019. };
  11020. Mesh.prototype.setMaterialByID = function (id) {
  11021. var materials = this.getScene().materials;
  11022. for (var index = 0; index < materials.length; index++) {
  11023. if (materials[index].id === id) {
  11024. this.material = materials[index];
  11025. return;
  11026. }
  11027. }
  11028. // Multi
  11029. var multiMaterials = this.getScene().multiMaterials;
  11030. for (index = 0; index < multiMaterials.length; index++) {
  11031. if (multiMaterials[index].id === id) {
  11032. this.material = multiMaterials[index];
  11033. return;
  11034. }
  11035. }
  11036. };
  11037. Mesh.prototype.getAnimatables = function () {
  11038. var results = [];
  11039. if (this.material) {
  11040. results.push(this.material);
  11041. }
  11042. if (this.skeleton) {
  11043. results.push(this.skeleton);
  11044. }
  11045. return results;
  11046. };
  11047. // Geometry
  11048. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11049. // Position
  11050. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11051. return;
  11052. }
  11053. this._resetPointsArrayCache();
  11054. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11055. var temp = [];
  11056. for (var index = 0; index < data.length; index += 3) {
  11057. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11058. }
  11059. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11060. // Normals
  11061. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11062. return;
  11063. }
  11064. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11065. for (index = 0; index < data.length; index += 3) {
  11066. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11067. }
  11068. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11069. };
  11070. // Cache
  11071. Mesh.prototype._resetPointsArrayCache = function () {
  11072. this._positions = null;
  11073. };
  11074. Mesh.prototype._generatePointsArray = function () {
  11075. if (this._positions)
  11076. return true;
  11077. this._positions = [];
  11078. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11079. if (!data) {
  11080. return false;
  11081. }
  11082. for (var index = 0; index < data.length; index += 3) {
  11083. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11084. }
  11085. return true;
  11086. };
  11087. // Clone
  11088. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11089. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11090. };
  11091. // Dispose
  11092. Mesh.prototype.dispose = function (doNotRecurse) {
  11093. if (this._geometry) {
  11094. this._geometry.releaseForMesh(this, true);
  11095. }
  11096. // Instances
  11097. if (this._worldMatricesInstancesBuffer) {
  11098. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11099. this._worldMatricesInstancesBuffer = null;
  11100. }
  11101. while (this.instances.length) {
  11102. this.instances[0].dispose();
  11103. }
  11104. _super.prototype.dispose.call(this, doNotRecurse);
  11105. };
  11106. // Geometric tools
  11107. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11108. var _this = this;
  11109. var scene = this.getScene();
  11110. var onload = function (img) {
  11111. // Getting height map data
  11112. var canvas = document.createElement("canvas");
  11113. var context = canvas.getContext("2d");
  11114. var heightMapWidth = img.width;
  11115. var heightMapHeight = img.height;
  11116. canvas.width = heightMapWidth;
  11117. canvas.height = heightMapHeight;
  11118. context.drawImage(img, 0, 0);
  11119. // Create VertexData from map data
  11120. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11121. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11122. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11123. //execute success callback, if set
  11124. if (onSuccess) {
  11125. onSuccess(_this);
  11126. }
  11127. };
  11128. BABYLON.Tools.LoadImage(url, onload, function () {
  11129. }, scene.database);
  11130. };
  11131. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11132. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11133. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11134. return;
  11135. }
  11136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11137. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11138. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11139. var position = BABYLON.Vector3.Zero();
  11140. var normal = BABYLON.Vector3.Zero();
  11141. var uv = BABYLON.Vector2.Zero();
  11142. for (var index = 0; index < positions.length; index += 3) {
  11143. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11144. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11145. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11146. // Compute height
  11147. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11148. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11149. var pos = (u + v * heightMapWidth) * 4;
  11150. var r = buffer[pos] / 255.0;
  11151. var g = buffer[pos + 1] / 255.0;
  11152. var b = buffer[pos + 2] / 255.0;
  11153. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11154. normal.normalize();
  11155. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11156. position = position.add(normal);
  11157. position.toArray(positions, index);
  11158. }
  11159. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11160. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11161. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11162. };
  11163. Mesh.prototype.convertToFlatShadedMesh = function () {
  11164. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11165. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11166. var kinds = this.getVerticesDataKinds();
  11167. var vbs = [];
  11168. var data = [];
  11169. var newdata = [];
  11170. var updatableNormals = false;
  11171. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11172. var kind = kinds[kindIndex];
  11173. var vertexBuffer = this.getVertexBuffer(kind);
  11174. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11175. updatableNormals = vertexBuffer.isUpdatable();
  11176. kinds.splice(kindIndex, 1);
  11177. kindIndex--;
  11178. continue;
  11179. }
  11180. vbs[kind] = vertexBuffer;
  11181. data[kind] = vbs[kind].getData();
  11182. newdata[kind] = [];
  11183. }
  11184. // Save previous submeshes
  11185. var previousSubmeshes = this.subMeshes.slice(0);
  11186. var indices = this.getIndices();
  11187. var totalIndices = this.getTotalIndices();
  11188. for (var index = 0; index < totalIndices; index++) {
  11189. var vertexIndex = indices[index];
  11190. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11191. kind = kinds[kindIndex];
  11192. var stride = vbs[kind].getStrideSize();
  11193. for (var offset = 0; offset < stride; offset++) {
  11194. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11195. }
  11196. }
  11197. }
  11198. // Updating faces & normal
  11199. var normals = [];
  11200. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11201. for (index = 0; index < totalIndices; index += 3) {
  11202. indices[index] = index;
  11203. indices[index + 1] = index + 1;
  11204. indices[index + 2] = index + 2;
  11205. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11206. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11207. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11208. var p1p2 = p1.subtract(p2);
  11209. var p3p2 = p3.subtract(p2);
  11210. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11211. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11212. normals.push(normal.x);
  11213. normals.push(normal.y);
  11214. normals.push(normal.z);
  11215. }
  11216. }
  11217. this.setIndices(indices);
  11218. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11219. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11220. kind = kinds[kindIndex];
  11221. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11222. }
  11223. // Updating submeshes
  11224. this.releaseSubMeshes();
  11225. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11226. var previousOne = previousSubmeshes[submeshIndex];
  11227. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11228. }
  11229. this.synchronizeInstances();
  11230. };
  11231. // Instances
  11232. Mesh.prototype.createInstance = function (name) {
  11233. return new BABYLON.InstancedMesh(name, this);
  11234. };
  11235. Mesh.prototype.synchronizeInstances = function () {
  11236. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11237. var instance = this.instances[instanceIndex];
  11238. instance._syncSubMeshes();
  11239. }
  11240. };
  11241. /**
  11242. * Simplify the mesh according to the given array of settings.
  11243. * Function will return immediately and will simplify async.
  11244. * @param settings a collection of simplification settings.
  11245. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11246. * @param type the type of simplification to run.
  11247. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11248. */
  11249. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11250. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11251. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11252. this.getScene().simplificationQueue.addTask({
  11253. settings: settings,
  11254. parallelProcessing: parallelProcessing,
  11255. mesh: this,
  11256. simplificationType: simplificationType,
  11257. successCallback: successCallback
  11258. });
  11259. };
  11260. // Statics
  11261. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11262. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11263. var ribbon = new Mesh(name, scene);
  11264. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11265. vertexData.applyToMesh(ribbon, updatable);
  11266. return ribbon;
  11267. };
  11268. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11269. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11270. var box = new Mesh(name, scene);
  11271. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11272. vertexData.applyToMesh(box, updatable);
  11273. return box;
  11274. };
  11275. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11276. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11277. var sphere = new Mesh(name, scene);
  11278. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11279. vertexData.applyToMesh(sphere, updatable);
  11280. return sphere;
  11281. };
  11282. // Cylinder and cone (Code inspired by SharpDX.org)
  11283. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11284. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11285. // subdivisions is a new parameter, we need to support old signature
  11286. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11287. if (scene !== undefined) {
  11288. updatable = scene;
  11289. }
  11290. scene = subdivisions;
  11291. subdivisions = 1;
  11292. }
  11293. var cylinder = new Mesh(name, scene);
  11294. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11295. vertexData.applyToMesh(cylinder, updatable);
  11296. return cylinder;
  11297. };
  11298. // Torus (Code from SharpDX.org)
  11299. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11300. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11301. var torus = new Mesh(name, scene);
  11302. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11303. vertexData.applyToMesh(torus, updatable);
  11304. return torus;
  11305. };
  11306. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11307. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11308. var torusKnot = new Mesh(name, scene);
  11309. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11310. vertexData.applyToMesh(torusKnot, updatable);
  11311. return torusKnot;
  11312. };
  11313. // Lines
  11314. Mesh.CreateLines = function (name, points, scene, updatable) {
  11315. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11316. var vertexData = BABYLON.VertexData.CreateLines(points);
  11317. vertexData.applyToMesh(lines, updatable);
  11318. return lines;
  11319. };
  11320. // Extrusion
  11321. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11322. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11323. scale = scale || 1;
  11324. rotation = rotation || 0;
  11325. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11326. return extruded;
  11327. };
  11328. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11329. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11330. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11331. return extrudedCustom;
  11332. };
  11333. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotationFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11334. var path3D = new BABYLON.Path3D(curve);
  11335. var shapePaths = [];
  11336. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11337. return extrudedGeneric;
  11338. };
  11339. // Plane & ground
  11340. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11341. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11342. var plane = new Mesh(name, scene);
  11343. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11344. vertexData.applyToMesh(plane, updatable);
  11345. return plane;
  11346. };
  11347. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11348. var ground = new BABYLON.GroundMesh(name, scene);
  11349. ground._setReady(false);
  11350. ground._subdivisions = subdivisions;
  11351. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11352. vertexData.applyToMesh(ground, updatable);
  11353. ground._setReady(true);
  11354. return ground;
  11355. };
  11356. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11357. var tiledGround = new Mesh(name, scene);
  11358. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11359. vertexData.applyToMesh(tiledGround, updatable);
  11360. return tiledGround;
  11361. };
  11362. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11363. var ground = new BABYLON.GroundMesh(name, scene);
  11364. ground._subdivisions = subdivisions;
  11365. ground._setReady(false);
  11366. var onload = function (img) {
  11367. // Getting height map data
  11368. var canvas = document.createElement("canvas");
  11369. var context = canvas.getContext("2d");
  11370. var heightMapWidth = img.width;
  11371. var heightMapHeight = img.height;
  11372. canvas.width = heightMapWidth;
  11373. canvas.height = heightMapHeight;
  11374. context.drawImage(img, 0, 0);
  11375. // Create VertexData from map data
  11376. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11377. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11378. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11379. vertexData.applyToMesh(ground, updatable);
  11380. ground._setReady(true);
  11381. //execute ready callback, if set
  11382. if (onReady) {
  11383. onReady(ground);
  11384. }
  11385. };
  11386. BABYLON.Tools.LoadImage(url, onload, function () {
  11387. }, scene.database);
  11388. return ground;
  11389. };
  11390. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11391. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11392. var path3D = new BABYLON.Path3D(path);
  11393. var tangents = path3D.getTangents();
  11394. var normals = path3D.getNormals();
  11395. var distances = path3D.getDistances();
  11396. var pi2 = Math.PI * 2;
  11397. var step = pi2 / tesselation;
  11398. var returnRadius = function (i, distance) { return radius; };
  11399. var radiusFunctionFinal = radiusFunction || returnRadius;
  11400. var circlePaths = new Array();
  11401. var circlePath;
  11402. var rad;
  11403. var normal;
  11404. var rotated;
  11405. var rotationMatrix;
  11406. for (var i = 0; i < path.length; i++) {
  11407. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11408. circlePath = Array(); // current circle array
  11409. normal = normals[i]; // current normal
  11410. for (var ang = 0; ang < pi2; ang += step) {
  11411. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11412. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11413. circlePath.push(rotated);
  11414. }
  11415. circlePaths.push(circlePath);
  11416. }
  11417. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11418. return tube;
  11419. };
  11420. // Tools
  11421. Mesh.MinMax = function (meshes) {
  11422. var minVector = null;
  11423. var maxVector = null;
  11424. for (var i in meshes) {
  11425. var mesh = meshes[i];
  11426. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11427. if (!minVector) {
  11428. minVector = boundingBox.minimumWorld;
  11429. maxVector = boundingBox.maximumWorld;
  11430. continue;
  11431. }
  11432. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11433. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11434. }
  11435. return {
  11436. min: minVector,
  11437. max: maxVector
  11438. };
  11439. };
  11440. Mesh.Center = function (meshesOrMinMaxVector) {
  11441. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11442. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11443. };
  11444. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11445. if (disposeSource === void 0) { disposeSource = true; }
  11446. var source = meshes[0];
  11447. var material = source.material;
  11448. var scene = source.getScene();
  11449. if (!allow32BitsIndices) {
  11450. var totalVertices = 0;
  11451. for (var index = 0; index < meshes.length; index++) {
  11452. totalVertices += meshes[index].getTotalVertices();
  11453. if (totalVertices > 65536) {
  11454. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11455. return null;
  11456. }
  11457. }
  11458. }
  11459. // Merge
  11460. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11461. vertexData.transform(source.getWorldMatrix());
  11462. for (index = 1; index < meshes.length; index++) {
  11463. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11464. otherVertexData.transform(meshes[index].getWorldMatrix());
  11465. vertexData.merge(otherVertexData);
  11466. }
  11467. var newMesh = new Mesh(source.name + "_merged", scene);
  11468. vertexData.applyToMesh(newMesh);
  11469. // Setting properties
  11470. newMesh.material = material;
  11471. newMesh.checkCollisions = source.checkCollisions;
  11472. // Cleaning
  11473. if (disposeSource) {
  11474. for (index = 0; index < meshes.length; index++) {
  11475. meshes[index].dispose();
  11476. }
  11477. }
  11478. return newMesh;
  11479. };
  11480. // Consts
  11481. Mesh._FRONTSIDE = 0;
  11482. Mesh._BACKSIDE = 1;
  11483. Mesh._DOUBLESIDE = 2;
  11484. Mesh._DEFAULTSIDE = 0;
  11485. return Mesh;
  11486. })(BABYLON.AbstractMesh);
  11487. BABYLON.Mesh = Mesh;
  11488. })(BABYLON || (BABYLON = {}));
  11489. //# sourceMappingURL=babylon.mesh.js.map
  11490. var BABYLON;
  11491. (function (BABYLON) {
  11492. var GroundMesh = (function (_super) {
  11493. __extends(GroundMesh, _super);
  11494. function GroundMesh(name, scene) {
  11495. _super.call(this, name, scene);
  11496. this.generateOctree = false;
  11497. this._worldInverse = new BABYLON.Matrix();
  11498. }
  11499. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11500. get: function () {
  11501. return this._subdivisions;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. GroundMesh.prototype.optimize = function (chunksCount) {
  11507. this.subdivide(this._subdivisions);
  11508. this.createOrUpdateSubmeshesOctree(32);
  11509. };
  11510. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11511. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11512. this.getWorldMatrix().invertToRef(this._worldInverse);
  11513. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11514. var pickInfo = this.intersects(ray);
  11515. if (pickInfo.hit) {
  11516. return pickInfo.pickedPoint.y;
  11517. }
  11518. return 0;
  11519. };
  11520. return GroundMesh;
  11521. })(BABYLON.Mesh);
  11522. BABYLON.GroundMesh = GroundMesh;
  11523. })(BABYLON || (BABYLON = {}));
  11524. //# sourceMappingURL=babylon.groundMesh.js.map
  11525. var BABYLON;
  11526. (function (BABYLON) {
  11527. /**
  11528. * Creates an instance based on a source mesh.
  11529. */
  11530. var InstancedMesh = (function (_super) {
  11531. __extends(InstancedMesh, _super);
  11532. function InstancedMesh(name, source) {
  11533. _super.call(this, name, source.getScene());
  11534. source.instances.push(this);
  11535. this._sourceMesh = source;
  11536. this.position.copyFrom(source.position);
  11537. this.rotation.copyFrom(source.rotation);
  11538. this.scaling.copyFrom(source.scaling);
  11539. if (source.rotationQuaternion) {
  11540. this.rotationQuaternion = source.rotationQuaternion.clone();
  11541. }
  11542. this.infiniteDistance = source.infiniteDistance;
  11543. this.setPivotMatrix(source.getPivotMatrix());
  11544. this.refreshBoundingInfo();
  11545. this._syncSubMeshes();
  11546. }
  11547. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11548. // Methods
  11549. get: function () {
  11550. return this._sourceMesh.receiveShadows;
  11551. },
  11552. enumerable: true,
  11553. configurable: true
  11554. });
  11555. Object.defineProperty(InstancedMesh.prototype, "material", {
  11556. get: function () {
  11557. return this._sourceMesh.material;
  11558. },
  11559. enumerable: true,
  11560. configurable: true
  11561. });
  11562. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11563. get: function () {
  11564. return this._sourceMesh.visibility;
  11565. },
  11566. enumerable: true,
  11567. configurable: true
  11568. });
  11569. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11570. get: function () {
  11571. return this._sourceMesh.skeleton;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. InstancedMesh.prototype.getTotalVertices = function () {
  11577. return this._sourceMesh.getTotalVertices();
  11578. };
  11579. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11580. get: function () {
  11581. return this._sourceMesh;
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. InstancedMesh.prototype.getVerticesData = function (kind) {
  11587. return this._sourceMesh.getVerticesData(kind);
  11588. };
  11589. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11590. return this._sourceMesh.isVerticesDataPresent(kind);
  11591. };
  11592. InstancedMesh.prototype.getIndices = function () {
  11593. return this._sourceMesh.getIndices();
  11594. };
  11595. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11596. get: function () {
  11597. return this._sourceMesh._positions;
  11598. },
  11599. enumerable: true,
  11600. configurable: true
  11601. });
  11602. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11603. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11604. if (data) {
  11605. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11606. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11607. }
  11608. this._updateBoundingInfo();
  11609. };
  11610. InstancedMesh.prototype._preActivate = function () {
  11611. if (this._currentLOD) {
  11612. this._currentLOD._preActivate();
  11613. }
  11614. };
  11615. InstancedMesh.prototype._activate = function (renderId) {
  11616. if (this._currentLOD) {
  11617. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11618. }
  11619. };
  11620. InstancedMesh.prototype.getLOD = function (camera) {
  11621. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11622. if (this._currentLOD === this.sourceMesh) {
  11623. return this;
  11624. }
  11625. return this._currentLOD;
  11626. };
  11627. InstancedMesh.prototype._syncSubMeshes = function () {
  11628. this.releaseSubMeshes();
  11629. if (this._sourceMesh.subMeshes) {
  11630. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11631. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11632. }
  11633. }
  11634. };
  11635. InstancedMesh.prototype._generatePointsArray = function () {
  11636. return this._sourceMesh._generatePointsArray();
  11637. };
  11638. // Clone
  11639. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11640. var result = this._sourceMesh.createInstance(name);
  11641. // Deep copy
  11642. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11643. // Bounding info
  11644. this.refreshBoundingInfo();
  11645. // Parent
  11646. if (newParent) {
  11647. result.parent = newParent;
  11648. }
  11649. if (!doNotCloneChildren) {
  11650. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11651. var mesh = this.getScene().meshes[index];
  11652. if (mesh.parent === this) {
  11653. mesh.clone(mesh.name, result);
  11654. }
  11655. }
  11656. }
  11657. result.computeWorldMatrix(true);
  11658. return result;
  11659. };
  11660. // Dispoe
  11661. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11662. // Remove from mesh
  11663. var index = this._sourceMesh.instances.indexOf(this);
  11664. this._sourceMesh.instances.splice(index, 1);
  11665. _super.prototype.dispose.call(this, doNotRecurse);
  11666. };
  11667. return InstancedMesh;
  11668. })(BABYLON.AbstractMesh);
  11669. BABYLON.InstancedMesh = InstancedMesh;
  11670. })(BABYLON || (BABYLON = {}));
  11671. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11672. (function (BABYLON) {
  11673. var SubMesh = (function () {
  11674. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11675. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11676. this.materialIndex = materialIndex;
  11677. this.verticesStart = verticesStart;
  11678. this.verticesCount = verticesCount;
  11679. this.indexStart = indexStart;
  11680. this.indexCount = indexCount;
  11681. this._renderId = 0;
  11682. this._mesh = mesh;
  11683. this._renderingMesh = renderingMesh || mesh;
  11684. mesh.subMeshes.push(this);
  11685. this._id = mesh.subMeshes.length - 1;
  11686. if (createBoundingBox) {
  11687. this.refreshBoundingInfo();
  11688. }
  11689. }
  11690. SubMesh.prototype.getBoundingInfo = function () {
  11691. return this._boundingInfo;
  11692. };
  11693. SubMesh.prototype.getMesh = function () {
  11694. return this._mesh;
  11695. };
  11696. SubMesh.prototype.getRenderingMesh = function () {
  11697. return this._renderingMesh;
  11698. };
  11699. SubMesh.prototype.getMaterial = function () {
  11700. var rootMaterial = this._renderingMesh.material;
  11701. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11702. var multiMaterial = rootMaterial;
  11703. return multiMaterial.getSubMaterial(this.materialIndex);
  11704. }
  11705. if (!rootMaterial) {
  11706. return this._mesh.getScene().defaultMaterial;
  11707. }
  11708. return rootMaterial;
  11709. };
  11710. // Methods
  11711. SubMesh.prototype.refreshBoundingInfo = function () {
  11712. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11713. if (!data) {
  11714. this._boundingInfo = this._mesh._boundingInfo;
  11715. return;
  11716. }
  11717. var indices = this._renderingMesh.getIndices();
  11718. var extend;
  11719. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11720. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11721. }
  11722. else {
  11723. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11724. }
  11725. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11726. };
  11727. SubMesh.prototype._checkCollision = function (collider) {
  11728. return this._boundingInfo._checkCollision(collider);
  11729. };
  11730. SubMesh.prototype.updateBoundingInfo = function (world) {
  11731. if (!this._boundingInfo) {
  11732. this.refreshBoundingInfo();
  11733. }
  11734. this._boundingInfo._update(world);
  11735. };
  11736. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11737. return this._boundingInfo.isInFrustum(frustumPlanes);
  11738. };
  11739. SubMesh.prototype.render = function () {
  11740. this._renderingMesh.render(this);
  11741. };
  11742. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11743. if (!this._linesIndexBuffer) {
  11744. var linesIndices = [];
  11745. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11746. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11747. }
  11748. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11749. this.linesIndexCount = linesIndices.length;
  11750. }
  11751. return this._linesIndexBuffer;
  11752. };
  11753. SubMesh.prototype.canIntersects = function (ray) {
  11754. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11755. };
  11756. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11757. var intersectInfo = null;
  11758. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11759. var p0 = positions[indices[index]];
  11760. var p1 = positions[indices[index + 1]];
  11761. var p2 = positions[indices[index + 2]];
  11762. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11763. if (currentIntersectInfo) {
  11764. if (currentIntersectInfo.distance < 0) {
  11765. continue;
  11766. }
  11767. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11768. intersectInfo = currentIntersectInfo;
  11769. intersectInfo.faceId = index / 3;
  11770. if (fastCheck) {
  11771. break;
  11772. }
  11773. }
  11774. }
  11775. }
  11776. return intersectInfo;
  11777. };
  11778. // Clone
  11779. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11780. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11781. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11782. return result;
  11783. };
  11784. // Dispose
  11785. SubMesh.prototype.dispose = function () {
  11786. if (this._linesIndexBuffer) {
  11787. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11788. this._linesIndexBuffer = null;
  11789. }
  11790. // Remove from mesh
  11791. var index = this._mesh.subMeshes.indexOf(this);
  11792. this._mesh.subMeshes.splice(index, 1);
  11793. };
  11794. // Statics
  11795. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11796. var minVertexIndex = Number.MAX_VALUE;
  11797. var maxVertexIndex = -Number.MAX_VALUE;
  11798. renderingMesh = renderingMesh || mesh;
  11799. var indices = renderingMesh.getIndices();
  11800. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11801. var vertexIndex = indices[index];
  11802. if (vertexIndex < minVertexIndex)
  11803. minVertexIndex = vertexIndex;
  11804. if (vertexIndex > maxVertexIndex)
  11805. maxVertexIndex = vertexIndex;
  11806. }
  11807. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11808. };
  11809. return SubMesh;
  11810. })();
  11811. BABYLON.SubMesh = SubMesh;
  11812. })(BABYLON || (BABYLON = {}));
  11813. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11814. (function (BABYLON) {
  11815. var BaseTexture = (function () {
  11816. function BaseTexture(scene) {
  11817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11818. this.hasAlpha = false;
  11819. this.getAlphaFromRGB = false;
  11820. this.level = 1;
  11821. this.isCube = false;
  11822. this.isRenderTarget = false;
  11823. this.animations = new Array();
  11824. this.coordinatesIndex = 0;
  11825. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11826. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11827. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11828. this.anisotropicFilteringLevel = 4;
  11829. this._scene = scene;
  11830. this._scene.textures.push(this);
  11831. }
  11832. BaseTexture.prototype.getScene = function () {
  11833. return this._scene;
  11834. };
  11835. BaseTexture.prototype.getTextureMatrix = function () {
  11836. return null;
  11837. };
  11838. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11839. return null;
  11840. };
  11841. BaseTexture.prototype.getInternalTexture = function () {
  11842. return this._texture;
  11843. };
  11844. BaseTexture.prototype.isReady = function () {
  11845. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11846. return true;
  11847. }
  11848. if (this._texture) {
  11849. return this._texture.isReady;
  11850. }
  11851. return false;
  11852. };
  11853. BaseTexture.prototype.getSize = function () {
  11854. if (this._texture._width) {
  11855. return { width: this._texture._width, height: this._texture._height };
  11856. }
  11857. if (this._texture._size) {
  11858. return { width: this._texture._size, height: this._texture._size };
  11859. }
  11860. return { width: 0, height: 0 };
  11861. };
  11862. BaseTexture.prototype.getBaseSize = function () {
  11863. if (!this.isReady())
  11864. return { width: 0, height: 0 };
  11865. if (this._texture._size) {
  11866. return { width: this._texture._size, height: this._texture._size };
  11867. }
  11868. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11869. };
  11870. BaseTexture.prototype.scale = function (ratio) {
  11871. };
  11872. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11873. get: function () {
  11874. return false;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11880. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11881. for (var index = 0; index < texturesCache.length; index++) {
  11882. var texturesCacheEntry = texturesCache[index];
  11883. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11884. texturesCache.splice(index, 1);
  11885. return;
  11886. }
  11887. }
  11888. };
  11889. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11890. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11891. for (var index = 0; index < texturesCache.length; index++) {
  11892. var texturesCacheEntry = texturesCache[index];
  11893. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11894. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11895. texturesCacheEntry.references++;
  11896. return texturesCacheEntry;
  11897. }
  11898. }
  11899. }
  11900. return null;
  11901. };
  11902. BaseTexture.prototype.delayLoad = function () {
  11903. };
  11904. BaseTexture.prototype.releaseInternalTexture = function () {
  11905. if (!this._texture) {
  11906. return;
  11907. }
  11908. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11909. this._texture.references--;
  11910. // Final reference ?
  11911. if (this._texture.references === 0) {
  11912. var index = texturesCache.indexOf(this._texture);
  11913. texturesCache.splice(index, 1);
  11914. this._scene.getEngine()._releaseTexture(this._texture);
  11915. delete this._texture;
  11916. }
  11917. };
  11918. BaseTexture.prototype.clone = function () {
  11919. return null;
  11920. };
  11921. BaseTexture.prototype.dispose = function () {
  11922. // Remove from scene
  11923. var index = this._scene.textures.indexOf(this);
  11924. if (index >= 0) {
  11925. this._scene.textures.splice(index, 1);
  11926. }
  11927. if (this._texture === undefined) {
  11928. return;
  11929. }
  11930. this.releaseInternalTexture();
  11931. // Callback
  11932. if (this.onDispose) {
  11933. this.onDispose();
  11934. }
  11935. };
  11936. return BaseTexture;
  11937. })();
  11938. BABYLON.BaseTexture = BaseTexture;
  11939. })(BABYLON || (BABYLON = {}));
  11940. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11941. (function (BABYLON) {
  11942. var RenderingGroup = (function () {
  11943. function RenderingGroup(index, scene) {
  11944. this.index = index;
  11945. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11946. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11947. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11948. this._scene = scene;
  11949. }
  11950. RenderingGroup.prototype.render = function (customRenderFunction) {
  11951. if (customRenderFunction) {
  11952. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11953. return true;
  11954. }
  11955. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11956. return false;
  11957. }
  11958. var engine = this._scene.getEngine();
  11959. // Opaque
  11960. var subIndex;
  11961. var submesh;
  11962. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11963. submesh = this._opaqueSubMeshes.data[subIndex];
  11964. submesh.render();
  11965. }
  11966. // Alpha test
  11967. engine.setAlphaTesting(true);
  11968. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11969. submesh = this._alphaTestSubMeshes.data[subIndex];
  11970. submesh.render();
  11971. }
  11972. engine.setAlphaTesting(false);
  11973. // Transparent
  11974. if (this._transparentSubMeshes.length) {
  11975. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11976. submesh = this._transparentSubMeshes.data[subIndex];
  11977. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11978. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11979. }
  11980. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11981. sortedArray.sort(function (a, b) {
  11982. // Alpha index first
  11983. if (a._alphaIndex > b._alphaIndex) {
  11984. return 1;
  11985. }
  11986. if (a._alphaIndex < b._alphaIndex) {
  11987. return -1;
  11988. }
  11989. // Then distance to camera
  11990. if (a._distanceToCamera < b._distanceToCamera) {
  11991. return 1;
  11992. }
  11993. if (a._distanceToCamera > b._distanceToCamera) {
  11994. return -1;
  11995. }
  11996. return 0;
  11997. });
  11998. // Rendering
  11999. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12000. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12001. submesh = sortedArray[subIndex];
  12002. submesh.render();
  12003. }
  12004. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12005. }
  12006. return true;
  12007. };
  12008. RenderingGroup.prototype.prepare = function () {
  12009. this._opaqueSubMeshes.reset();
  12010. this._transparentSubMeshes.reset();
  12011. this._alphaTestSubMeshes.reset();
  12012. };
  12013. RenderingGroup.prototype.dispatch = function (subMesh) {
  12014. var material = subMesh.getMaterial();
  12015. var mesh = subMesh.getMesh();
  12016. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12017. this._transparentSubMeshes.push(subMesh);
  12018. }
  12019. else if (material.needAlphaTesting()) {
  12020. this._alphaTestSubMeshes.push(subMesh);
  12021. }
  12022. else {
  12023. this._opaqueSubMeshes.push(subMesh); // Opaque
  12024. }
  12025. };
  12026. return RenderingGroup;
  12027. })();
  12028. BABYLON.RenderingGroup = RenderingGroup;
  12029. })(BABYLON || (BABYLON = {}));
  12030. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12031. (function (BABYLON) {
  12032. var RenderingManager = (function () {
  12033. function RenderingManager(scene) {
  12034. this._renderingGroups = new Array();
  12035. this._scene = scene;
  12036. }
  12037. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12038. if (this._scene._activeParticleSystems.length === 0) {
  12039. return;
  12040. }
  12041. // Particles
  12042. var beforeParticlesDate = BABYLON.Tools.Now;
  12043. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12044. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12045. if (particleSystem.renderingGroupId !== index) {
  12046. continue;
  12047. }
  12048. this._clearDepthBuffer();
  12049. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12050. this._scene._activeParticles += particleSystem.render();
  12051. }
  12052. }
  12053. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12054. };
  12055. RenderingManager.prototype._renderSprites = function (index) {
  12056. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12057. return;
  12058. }
  12059. // Sprites
  12060. var beforeSpritessDate = BABYLON.Tools.Now;
  12061. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12062. var spriteManager = this._scene.spriteManagers[id];
  12063. if (spriteManager.renderingGroupId === index) {
  12064. this._clearDepthBuffer();
  12065. spriteManager.render();
  12066. }
  12067. }
  12068. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12069. };
  12070. RenderingManager.prototype._clearDepthBuffer = function () {
  12071. if (this._depthBufferAlreadyCleaned) {
  12072. return;
  12073. }
  12074. this._scene.getEngine().clear(0, false, true);
  12075. this._depthBufferAlreadyCleaned = true;
  12076. };
  12077. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12078. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12079. this._depthBufferAlreadyCleaned = false;
  12080. var renderingGroup = this._renderingGroups[index];
  12081. var needToStepBack = false;
  12082. if (renderingGroup) {
  12083. this._clearDepthBuffer();
  12084. if (!renderingGroup.render(customRenderFunction)) {
  12085. this._renderingGroups.splice(index, 1);
  12086. needToStepBack = true;
  12087. }
  12088. }
  12089. if (renderSprites) {
  12090. this._renderSprites(index);
  12091. }
  12092. if (renderParticles) {
  12093. this._renderParticles(index, activeMeshes);
  12094. }
  12095. if (needToStepBack) {
  12096. index--;
  12097. }
  12098. }
  12099. };
  12100. RenderingManager.prototype.reset = function () {
  12101. for (var index in this._renderingGroups) {
  12102. var renderingGroup = this._renderingGroups[index];
  12103. renderingGroup.prepare();
  12104. }
  12105. };
  12106. RenderingManager.prototype.dispatch = function (subMesh) {
  12107. var mesh = subMesh.getMesh();
  12108. var renderingGroupId = mesh.renderingGroupId || 0;
  12109. if (!this._renderingGroups[renderingGroupId]) {
  12110. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12111. }
  12112. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12113. };
  12114. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12115. return RenderingManager;
  12116. })();
  12117. BABYLON.RenderingManager = RenderingManager;
  12118. })(BABYLON || (BABYLON = {}));
  12119. //# sourceMappingURL=babylon.renderingManager.js.map
  12120. var BABYLON;
  12121. (function (BABYLON) {
  12122. var Texture = (function (_super) {
  12123. __extends(Texture, _super);
  12124. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12125. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12126. if (onLoad === void 0) { onLoad = null; }
  12127. if (onError === void 0) { onError = null; }
  12128. if (buffer === void 0) { buffer = null; }
  12129. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12130. _super.call(this, scene);
  12131. this.uOffset = 0;
  12132. this.vOffset = 0;
  12133. this.uScale = 1.0;
  12134. this.vScale = 1.0;
  12135. this.uAng = 0;
  12136. this.vAng = 0;
  12137. this.wAng = 0;
  12138. this.name = url;
  12139. this.url = url;
  12140. this._noMipmap = noMipmap;
  12141. this._invertY = invertY;
  12142. this._samplingMode = samplingMode;
  12143. this._buffer = buffer;
  12144. this._deleteBuffer = deleteBuffer;
  12145. if (!url) {
  12146. return;
  12147. }
  12148. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12149. if (!this._texture) {
  12150. if (!scene.useDelayedTextureLoading) {
  12151. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12152. if (deleteBuffer) {
  12153. delete this._buffer;
  12154. }
  12155. }
  12156. else {
  12157. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12158. }
  12159. }
  12160. }
  12161. Texture.prototype.delayLoad = function () {
  12162. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12163. return;
  12164. }
  12165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12166. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12167. if (!this._texture) {
  12168. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12169. if (this._deleteBuffer) {
  12170. delete this._buffer;
  12171. }
  12172. }
  12173. };
  12174. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12175. x -= this.uOffset + 0.5;
  12176. y -= this.vOffset + 0.5;
  12177. z -= 0.5;
  12178. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12179. t.x *= this.uScale;
  12180. t.y *= this.vScale;
  12181. t.x += 0.5;
  12182. t.y += 0.5;
  12183. t.z += 0.5;
  12184. };
  12185. Texture.prototype.getTextureMatrix = function () {
  12186. 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) {
  12187. return this._cachedTextureMatrix;
  12188. }
  12189. this._cachedUOffset = this.uOffset;
  12190. this._cachedVOffset = this.vOffset;
  12191. this._cachedUScale = this.uScale;
  12192. this._cachedVScale = this.vScale;
  12193. this._cachedUAng = this.uAng;
  12194. this._cachedVAng = this.vAng;
  12195. this._cachedWAng = this.wAng;
  12196. if (!this._cachedTextureMatrix) {
  12197. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12198. this._rowGenerationMatrix = new BABYLON.Matrix();
  12199. this._t0 = BABYLON.Vector3.Zero();
  12200. this._t1 = BABYLON.Vector3.Zero();
  12201. this._t2 = BABYLON.Vector3.Zero();
  12202. }
  12203. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12204. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12205. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12206. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12207. this._t1.subtractInPlace(this._t0);
  12208. this._t2.subtractInPlace(this._t0);
  12209. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12210. this._cachedTextureMatrix.m[0] = this._t1.x;
  12211. this._cachedTextureMatrix.m[1] = this._t1.y;
  12212. this._cachedTextureMatrix.m[2] = this._t1.z;
  12213. this._cachedTextureMatrix.m[4] = this._t2.x;
  12214. this._cachedTextureMatrix.m[5] = this._t2.y;
  12215. this._cachedTextureMatrix.m[6] = this._t2.z;
  12216. this._cachedTextureMatrix.m[8] = this._t0.x;
  12217. this._cachedTextureMatrix.m[9] = this._t0.y;
  12218. this._cachedTextureMatrix.m[10] = this._t0.z;
  12219. return this._cachedTextureMatrix;
  12220. };
  12221. Texture.prototype.getReflectionTextureMatrix = function () {
  12222. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12223. return this._cachedTextureMatrix;
  12224. }
  12225. if (!this._cachedTextureMatrix) {
  12226. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12227. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12228. }
  12229. this._cachedCoordinatesMode = this.coordinatesMode;
  12230. switch (this.coordinatesMode) {
  12231. case BABYLON.Texture.SPHERICAL_MODE:
  12232. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12233. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12234. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12235. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12236. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12237. break;
  12238. case BABYLON.Texture.PLANAR_MODE:
  12239. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12240. this._cachedTextureMatrix[0] = this.uScale;
  12241. this._cachedTextureMatrix[5] = this.vScale;
  12242. this._cachedTextureMatrix[12] = this.uOffset;
  12243. this._cachedTextureMatrix[13] = this.vOffset;
  12244. break;
  12245. case BABYLON.Texture.PROJECTION_MODE:
  12246. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12247. this._projectionModeMatrix.m[0] = 0.5;
  12248. this._projectionModeMatrix.m[5] = -0.5;
  12249. this._projectionModeMatrix.m[10] = 0.0;
  12250. this._projectionModeMatrix.m[12] = 0.5;
  12251. this._projectionModeMatrix.m[13] = 0.5;
  12252. this._projectionModeMatrix.m[14] = 1.0;
  12253. this._projectionModeMatrix.m[15] = 1.0;
  12254. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12255. break;
  12256. default:
  12257. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12258. break;
  12259. }
  12260. return this._cachedTextureMatrix;
  12261. };
  12262. Texture.prototype.clone = function () {
  12263. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12264. // Base texture
  12265. newTexture.hasAlpha = this.hasAlpha;
  12266. newTexture.level = this.level;
  12267. newTexture.wrapU = this.wrapU;
  12268. newTexture.wrapV = this.wrapV;
  12269. newTexture.coordinatesIndex = this.coordinatesIndex;
  12270. newTexture.coordinatesMode = this.coordinatesMode;
  12271. // Texture
  12272. newTexture.uOffset = this.uOffset;
  12273. newTexture.vOffset = this.vOffset;
  12274. newTexture.uScale = this.uScale;
  12275. newTexture.vScale = this.vScale;
  12276. newTexture.uAng = this.uAng;
  12277. newTexture.vAng = this.vAng;
  12278. newTexture.wAng = this.wAng;
  12279. return newTexture;
  12280. };
  12281. // Statics
  12282. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12283. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12284. if (onLoad === void 0) { onLoad = null; }
  12285. if (onError === void 0) { onError = null; }
  12286. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12287. };
  12288. // Constants
  12289. Texture.NEAREST_SAMPLINGMODE = 1;
  12290. Texture.BILINEAR_SAMPLINGMODE = 2;
  12291. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12292. Texture.EXPLICIT_MODE = 0;
  12293. Texture.SPHERICAL_MODE = 1;
  12294. Texture.PLANAR_MODE = 2;
  12295. Texture.CUBIC_MODE = 3;
  12296. Texture.PROJECTION_MODE = 4;
  12297. Texture.SKYBOX_MODE = 5;
  12298. Texture.CLAMP_ADDRESSMODE = 0;
  12299. Texture.WRAP_ADDRESSMODE = 1;
  12300. Texture.MIRROR_ADDRESSMODE = 2;
  12301. return Texture;
  12302. })(BABYLON.BaseTexture);
  12303. BABYLON.Texture = Texture;
  12304. })(BABYLON || (BABYLON = {}));
  12305. //# sourceMappingURL=babylon.texture.js.map
  12306. var BABYLON;
  12307. (function (BABYLON) {
  12308. var CubeTexture = (function (_super) {
  12309. __extends(CubeTexture, _super);
  12310. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12311. _super.call(this, scene);
  12312. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12313. this.name = rootUrl;
  12314. this.url = rootUrl;
  12315. this._noMipmap = noMipmap;
  12316. this.hasAlpha = false;
  12317. this._texture = this._getFromCache(rootUrl, noMipmap);
  12318. if (!extensions) {
  12319. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12320. }
  12321. this._extensions = extensions;
  12322. if (!this._texture) {
  12323. if (!scene.useDelayedTextureLoading) {
  12324. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12325. }
  12326. else {
  12327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12328. }
  12329. }
  12330. this.isCube = true;
  12331. this._textureMatrix = BABYLON.Matrix.Identity();
  12332. }
  12333. CubeTexture.prototype.clone = function () {
  12334. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12335. // Base texture
  12336. newTexture.level = this.level;
  12337. newTexture.wrapU = this.wrapU;
  12338. newTexture.wrapV = this.wrapV;
  12339. newTexture.coordinatesIndex = this.coordinatesIndex;
  12340. newTexture.coordinatesMode = this.coordinatesMode;
  12341. return newTexture;
  12342. };
  12343. // Methods
  12344. CubeTexture.prototype.delayLoad = function () {
  12345. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12346. return;
  12347. }
  12348. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12349. this._texture = this._getFromCache(this.url, this._noMipmap);
  12350. if (!this._texture) {
  12351. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12352. }
  12353. };
  12354. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12355. return this._textureMatrix;
  12356. };
  12357. return CubeTexture;
  12358. })(BABYLON.BaseTexture);
  12359. BABYLON.CubeTexture = CubeTexture;
  12360. })(BABYLON || (BABYLON = {}));
  12361. //# sourceMappingURL=babylon.cubeTexture.js.map
  12362. var BABYLON;
  12363. (function (BABYLON) {
  12364. var RenderTargetTexture = (function (_super) {
  12365. __extends(RenderTargetTexture, _super);
  12366. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12367. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12368. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12369. _super.call(this, null, scene, !generateMipMaps);
  12370. this.renderList = new Array();
  12371. this.renderParticles = true;
  12372. this.renderSprites = false;
  12373. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12374. this._currentRefreshId = -1;
  12375. this._refreshRate = 1;
  12376. this.name = name;
  12377. this.isRenderTarget = true;
  12378. this._size = size;
  12379. this._generateMipMaps = generateMipMaps;
  12380. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12381. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12382. // Rendering groups
  12383. this._renderingManager = new BABYLON.RenderingManager(scene);
  12384. }
  12385. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12386. this._currentRefreshId = -1;
  12387. };
  12388. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12389. get: function () {
  12390. return this._refreshRate;
  12391. },
  12392. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12393. set: function (value) {
  12394. this._refreshRate = value;
  12395. this.resetRefreshCounter();
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. RenderTargetTexture.prototype._shouldRender = function () {
  12401. if (this._currentRefreshId === -1) {
  12402. this._currentRefreshId = 1;
  12403. return true;
  12404. }
  12405. if (this.refreshRate === this._currentRefreshId) {
  12406. this._currentRefreshId = 1;
  12407. return true;
  12408. }
  12409. this._currentRefreshId++;
  12410. return false;
  12411. };
  12412. RenderTargetTexture.prototype.isReady = function () {
  12413. if (!this.getScene().renderTargetsEnabled) {
  12414. return false;
  12415. }
  12416. return _super.prototype.isReady.call(this);
  12417. };
  12418. RenderTargetTexture.prototype.getRenderSize = function () {
  12419. return this._size;
  12420. };
  12421. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12422. get: function () {
  12423. return true;
  12424. },
  12425. enumerable: true,
  12426. configurable: true
  12427. });
  12428. RenderTargetTexture.prototype.scale = function (ratio) {
  12429. var newSize = this._size * ratio;
  12430. this.resize(newSize, this._generateMipMaps);
  12431. };
  12432. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12433. this.releaseInternalTexture();
  12434. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12435. };
  12436. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12437. var scene = this.getScene();
  12438. var engine = scene.getEngine();
  12439. if (this._waitingRenderList) {
  12440. this.renderList = [];
  12441. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12442. var id = this._waitingRenderList[index];
  12443. this.renderList.push(scene.getMeshByID(id));
  12444. }
  12445. delete this._waitingRenderList;
  12446. }
  12447. if (this.renderList && this.renderList.length === 0) {
  12448. return;
  12449. }
  12450. // Bind
  12451. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12452. engine.bindFramebuffer(this._texture);
  12453. }
  12454. this._renderingManager.reset();
  12455. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12456. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12457. var mesh = currentRenderList[meshIndex];
  12458. if (mesh) {
  12459. if (!mesh.isReady()) {
  12460. // Reset _currentRefreshId
  12461. this.resetRefreshCounter();
  12462. continue;
  12463. }
  12464. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12465. mesh._activate(scene.getRenderId());
  12466. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12467. var subMesh = mesh.subMeshes[subIndex];
  12468. scene._activeVertices += subMesh.indexCount;
  12469. this._renderingManager.dispatch(subMesh);
  12470. }
  12471. }
  12472. }
  12473. }
  12474. if (this.onBeforeRender) {
  12475. this.onBeforeRender();
  12476. }
  12477. // Clear
  12478. if (this.onClear) {
  12479. this.onClear(engine);
  12480. }
  12481. else {
  12482. engine.clear(scene.clearColor, true, true);
  12483. }
  12484. if (!this._doNotChangeAspectRatio) {
  12485. scene.updateTransformMatrix(true);
  12486. }
  12487. // Render
  12488. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12489. if (useCameraPostProcess) {
  12490. scene.postProcessManager._finalizeFrame(false, this._texture);
  12491. }
  12492. if (!this._doNotChangeAspectRatio) {
  12493. scene.updateTransformMatrix(true);
  12494. }
  12495. if (this.onAfterRender) {
  12496. this.onAfterRender();
  12497. }
  12498. // Dump ?
  12499. if (dumpForDebug) {
  12500. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12501. }
  12502. // Unbind
  12503. engine.unBindFramebuffer(this._texture);
  12504. if (this.onAfterUnbind) {
  12505. this.onAfterUnbind();
  12506. }
  12507. };
  12508. RenderTargetTexture.prototype.clone = function () {
  12509. var textureSize = this.getSize();
  12510. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12511. // Base texture
  12512. newTexture.hasAlpha = this.hasAlpha;
  12513. newTexture.level = this.level;
  12514. // RenderTarget Texture
  12515. newTexture.coordinatesMode = this.coordinatesMode;
  12516. newTexture.renderList = this.renderList.slice(0);
  12517. return newTexture;
  12518. };
  12519. return RenderTargetTexture;
  12520. })(BABYLON.Texture);
  12521. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12522. })(BABYLON || (BABYLON = {}));
  12523. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12524. var BABYLON;
  12525. (function (BABYLON) {
  12526. var ProceduralTexture = (function (_super) {
  12527. __extends(ProceduralTexture, _super);
  12528. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12529. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12530. _super.call(this, null, scene, !generateMipMaps);
  12531. this._currentRefreshId = -1;
  12532. this._refreshRate = 1;
  12533. this._vertexDeclaration = [2];
  12534. this._vertexStrideSize = 2 * 4;
  12535. this._uniforms = new Array();
  12536. this._samplers = new Array();
  12537. this._textures = new Array();
  12538. this._floats = new Array();
  12539. this._floatsArrays = {};
  12540. this._colors3 = new Array();
  12541. this._colors4 = new Array();
  12542. this._vectors2 = new Array();
  12543. this._vectors3 = new Array();
  12544. this._matrices = new Array();
  12545. this._fallbackTextureUsed = false;
  12546. scene._proceduralTextures.push(this);
  12547. this.name = name;
  12548. this.isRenderTarget = true;
  12549. this._size = size;
  12550. this._generateMipMaps = generateMipMaps;
  12551. this.setFragment(fragment);
  12552. this._fallbackTexture = fallbackTexture;
  12553. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12554. // VBO
  12555. var vertices = [];
  12556. vertices.push(1, 1);
  12557. vertices.push(-1, 1);
  12558. vertices.push(-1, -1);
  12559. vertices.push(1, -1);
  12560. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12561. // Indices
  12562. var indices = [];
  12563. indices.push(0);
  12564. indices.push(1);
  12565. indices.push(2);
  12566. indices.push(0);
  12567. indices.push(2);
  12568. indices.push(3);
  12569. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12570. }
  12571. ProceduralTexture.prototype.reset = function () {
  12572. if (this._effect === undefined) {
  12573. return;
  12574. }
  12575. var engine = this.getScene().getEngine();
  12576. engine._releaseEffect(this._effect);
  12577. };
  12578. ProceduralTexture.prototype.isReady = function () {
  12579. var _this = this;
  12580. var engine = this.getScene().getEngine();
  12581. var shaders;
  12582. if (!this._fragment) {
  12583. return false;
  12584. }
  12585. if (this._fallbackTextureUsed) {
  12586. return true;
  12587. }
  12588. if (this._fragment.fragmentElement !== undefined) {
  12589. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12590. }
  12591. else {
  12592. shaders = { vertex: "procedural", fragment: this._fragment };
  12593. }
  12594. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12595. _this.releaseInternalTexture();
  12596. if (_this._fallbackTexture) {
  12597. _this._texture = _this._fallbackTexture._texture;
  12598. _this._texture.references++;
  12599. }
  12600. _this._fallbackTextureUsed = true;
  12601. });
  12602. return this._effect.isReady();
  12603. };
  12604. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12605. this._currentRefreshId = -1;
  12606. };
  12607. ProceduralTexture.prototype.setFragment = function (fragment) {
  12608. this._fragment = fragment;
  12609. };
  12610. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12611. get: function () {
  12612. return this._refreshRate;
  12613. },
  12614. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12615. set: function (value) {
  12616. this._refreshRate = value;
  12617. this.resetRefreshCounter();
  12618. },
  12619. enumerable: true,
  12620. configurable: true
  12621. });
  12622. ProceduralTexture.prototype._shouldRender = function () {
  12623. if (!this.isReady() || !this._texture) {
  12624. return false;
  12625. }
  12626. if (this._fallbackTextureUsed) {
  12627. return false;
  12628. }
  12629. if (this._currentRefreshId === -1) {
  12630. this._currentRefreshId = 1;
  12631. return true;
  12632. }
  12633. if (this.refreshRate === this._currentRefreshId) {
  12634. this._currentRefreshId = 1;
  12635. return true;
  12636. }
  12637. this._currentRefreshId++;
  12638. return false;
  12639. };
  12640. ProceduralTexture.prototype.getRenderSize = function () {
  12641. return this._size;
  12642. };
  12643. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12644. if (this._fallbackTextureUsed) {
  12645. return;
  12646. }
  12647. this.releaseInternalTexture();
  12648. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12649. };
  12650. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12651. if (this._uniforms.indexOf(uniformName) === -1) {
  12652. this._uniforms.push(uniformName);
  12653. }
  12654. };
  12655. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12656. if (this._samplers.indexOf(name) === -1) {
  12657. this._samplers.push(name);
  12658. }
  12659. this._textures[name] = texture;
  12660. return this;
  12661. };
  12662. ProceduralTexture.prototype.setFloat = function (name, value) {
  12663. this._checkUniform(name);
  12664. this._floats[name] = value;
  12665. return this;
  12666. };
  12667. ProceduralTexture.prototype.setFloats = function (name, value) {
  12668. this._checkUniform(name);
  12669. this._floatsArrays[name] = value;
  12670. return this;
  12671. };
  12672. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12673. this._checkUniform(name);
  12674. this._colors3[name] = value;
  12675. return this;
  12676. };
  12677. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12678. this._checkUniform(name);
  12679. this._colors4[name] = value;
  12680. return this;
  12681. };
  12682. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12683. this._checkUniform(name);
  12684. this._vectors2[name] = value;
  12685. return this;
  12686. };
  12687. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12688. this._checkUniform(name);
  12689. this._vectors3[name] = value;
  12690. return this;
  12691. };
  12692. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12693. this._checkUniform(name);
  12694. this._matrices[name] = value;
  12695. return this;
  12696. };
  12697. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12698. var scene = this.getScene();
  12699. var engine = scene.getEngine();
  12700. engine.bindFramebuffer(this._texture);
  12701. // Clear
  12702. engine.clear(scene.clearColor, true, true);
  12703. // Render
  12704. engine.enableEffect(this._effect);
  12705. engine.setState(false);
  12706. for (var name in this._textures) {
  12707. this._effect.setTexture(name, this._textures[name]);
  12708. }
  12709. for (name in this._floats) {
  12710. this._effect.setFloat(name, this._floats[name]);
  12711. }
  12712. for (name in this._floatsArrays) {
  12713. this._effect.setArray(name, this._floatsArrays[name]);
  12714. }
  12715. for (name in this._colors3) {
  12716. this._effect.setColor3(name, this._colors3[name]);
  12717. }
  12718. for (name in this._colors4) {
  12719. var color = this._colors4[name];
  12720. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12721. }
  12722. for (name in this._vectors2) {
  12723. this._effect.setVector2(name, this._vectors2[name]);
  12724. }
  12725. for (name in this._vectors3) {
  12726. this._effect.setVector3(name, this._vectors3[name]);
  12727. }
  12728. for (name in this._matrices) {
  12729. this._effect.setMatrix(name, this._matrices[name]);
  12730. }
  12731. // VBOs
  12732. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12733. // Draw order
  12734. engine.draw(true, 0, 6);
  12735. // Unbind
  12736. engine.unBindFramebuffer(this._texture);
  12737. };
  12738. ProceduralTexture.prototype.clone = function () {
  12739. var textureSize = this.getSize();
  12740. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12741. // Base texture
  12742. newTexture.hasAlpha = this.hasAlpha;
  12743. newTexture.level = this.level;
  12744. // RenderTarget Texture
  12745. newTexture.coordinatesMode = this.coordinatesMode;
  12746. return newTexture;
  12747. };
  12748. ProceduralTexture.prototype.dispose = function () {
  12749. var index = this.getScene()._proceduralTextures.indexOf(this);
  12750. if (index >= 0) {
  12751. this.getScene()._proceduralTextures.splice(index, 1);
  12752. }
  12753. _super.prototype.dispose.call(this);
  12754. };
  12755. return ProceduralTexture;
  12756. })(BABYLON.Texture);
  12757. BABYLON.ProceduralTexture = ProceduralTexture;
  12758. })(BABYLON || (BABYLON = {}));
  12759. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12760. var BABYLON;
  12761. (function (BABYLON) {
  12762. var WoodProceduralTexture = (function (_super) {
  12763. __extends(WoodProceduralTexture, _super);
  12764. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12765. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12766. this._ampScale = 100.0;
  12767. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12768. this.updateShaderUniforms();
  12769. this.refreshRate = 0;
  12770. }
  12771. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12772. this.setFloat("ampScale", this._ampScale);
  12773. this.setColor3("woodColor", this._woodColor);
  12774. };
  12775. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12776. get: function () {
  12777. return this._ampScale;
  12778. },
  12779. set: function (value) {
  12780. this._ampScale = value;
  12781. this.updateShaderUniforms();
  12782. },
  12783. enumerable: true,
  12784. configurable: true
  12785. });
  12786. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12787. get: function () {
  12788. return this._woodColor;
  12789. },
  12790. set: function (value) {
  12791. this._woodColor = value;
  12792. this.updateShaderUniforms();
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. return WoodProceduralTexture;
  12798. })(BABYLON.ProceduralTexture);
  12799. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12800. var FireProceduralTexture = (function (_super) {
  12801. __extends(FireProceduralTexture, _super);
  12802. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12803. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12804. this._time = 0.0;
  12805. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12806. this._shift = 1.6;
  12807. this._autoGenerateTime = true;
  12808. this._alphaThreshold = 0.5;
  12809. this._fireColors = FireProceduralTexture.RedFireColors;
  12810. this.updateShaderUniforms();
  12811. this.refreshRate = 1;
  12812. }
  12813. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12814. this.setFloat("time", this._time);
  12815. this.setVector2("speed", this._speed);
  12816. this.setFloat("shift", this._shift);
  12817. this.setColor3("c1", this._fireColors[0]);
  12818. this.setColor3("c2", this._fireColors[1]);
  12819. this.setColor3("c3", this._fireColors[2]);
  12820. this.setColor3("c4", this._fireColors[3]);
  12821. this.setColor3("c5", this._fireColors[4]);
  12822. this.setColor3("c6", this._fireColors[5]);
  12823. this.setFloat("alphaThreshold", this._alphaThreshold);
  12824. };
  12825. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12826. if (this._autoGenerateTime) {
  12827. this._time += this.getScene().getAnimationRatio() * 0.03;
  12828. this.updateShaderUniforms();
  12829. }
  12830. _super.prototype.render.call(this, useCameraPostProcess);
  12831. };
  12832. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12833. get: function () {
  12834. return [
  12835. new BABYLON.Color3(0.5, 0.0, 1.0),
  12836. new BABYLON.Color3(0.9, 0.0, 1.0),
  12837. new BABYLON.Color3(0.2, 0.0, 1.0),
  12838. new BABYLON.Color3(1.0, 0.9, 1.0),
  12839. new BABYLON.Color3(0.1, 0.1, 1.0),
  12840. new BABYLON.Color3(0.9, 0.9, 1.0)
  12841. ];
  12842. },
  12843. enumerable: true,
  12844. configurable: true
  12845. });
  12846. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12847. get: function () {
  12848. return [
  12849. new BABYLON.Color3(0.5, 1.0, 0.0),
  12850. new BABYLON.Color3(0.5, 1.0, 0.0),
  12851. new BABYLON.Color3(0.3, 0.4, 0.0),
  12852. new BABYLON.Color3(0.5, 1.0, 0.0),
  12853. new BABYLON.Color3(0.2, 0.0, 0.0),
  12854. new BABYLON.Color3(0.5, 1.0, 0.0)
  12855. ];
  12856. },
  12857. enumerable: true,
  12858. configurable: true
  12859. });
  12860. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12861. get: function () {
  12862. return [
  12863. new BABYLON.Color3(0.5, 0.0, 0.1),
  12864. new BABYLON.Color3(0.9, 0.0, 0.0),
  12865. new BABYLON.Color3(0.2, 0.0, 0.0),
  12866. new BABYLON.Color3(1.0, 0.9, 0.0),
  12867. new BABYLON.Color3(0.1, 0.1, 0.1),
  12868. new BABYLON.Color3(0.9, 0.9, 0.9)
  12869. ];
  12870. },
  12871. enumerable: true,
  12872. configurable: true
  12873. });
  12874. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12875. get: function () {
  12876. return [
  12877. new BABYLON.Color3(0.1, 0.0, 0.5),
  12878. new BABYLON.Color3(0.0, 0.0, 0.5),
  12879. new BABYLON.Color3(0.1, 0.0, 0.2),
  12880. new BABYLON.Color3(0.0, 0.0, 1.0),
  12881. new BABYLON.Color3(0.1, 0.2, 0.3),
  12882. new BABYLON.Color3(0.0, 0.2, 0.9)
  12883. ];
  12884. },
  12885. enumerable: true,
  12886. configurable: true
  12887. });
  12888. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12889. get: function () {
  12890. return this._fireColors;
  12891. },
  12892. set: function (value) {
  12893. this._fireColors = value;
  12894. this.updateShaderUniforms();
  12895. },
  12896. enumerable: true,
  12897. configurable: true
  12898. });
  12899. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12900. get: function () {
  12901. return this._time;
  12902. },
  12903. set: function (value) {
  12904. this._time = value;
  12905. this.updateShaderUniforms();
  12906. },
  12907. enumerable: true,
  12908. configurable: true
  12909. });
  12910. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12911. get: function () {
  12912. return this._speed;
  12913. },
  12914. set: function (value) {
  12915. this._speed = value;
  12916. this.updateShaderUniforms();
  12917. },
  12918. enumerable: true,
  12919. configurable: true
  12920. });
  12921. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12922. get: function () {
  12923. return this._shift;
  12924. },
  12925. set: function (value) {
  12926. this._shift = value;
  12927. this.updateShaderUniforms();
  12928. },
  12929. enumerable: true,
  12930. configurable: true
  12931. });
  12932. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12933. get: function () {
  12934. return this._alphaThreshold;
  12935. },
  12936. set: function (value) {
  12937. this._alphaThreshold = value;
  12938. this.updateShaderUniforms();
  12939. },
  12940. enumerable: true,
  12941. configurable: true
  12942. });
  12943. return FireProceduralTexture;
  12944. })(BABYLON.ProceduralTexture);
  12945. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12946. var CloudProceduralTexture = (function (_super) {
  12947. __extends(CloudProceduralTexture, _super);
  12948. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12949. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12950. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12951. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12952. this.updateShaderUniforms();
  12953. this.refreshRate = 0;
  12954. }
  12955. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12956. this.setColor3("skyColor", this._skyColor);
  12957. this.setColor3("cloudColor", this._cloudColor);
  12958. };
  12959. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12960. get: function () {
  12961. return this._skyColor;
  12962. },
  12963. set: function (value) {
  12964. this._skyColor = value;
  12965. this.updateShaderUniforms();
  12966. },
  12967. enumerable: true,
  12968. configurable: true
  12969. });
  12970. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12971. get: function () {
  12972. return this._cloudColor;
  12973. },
  12974. set: function (value) {
  12975. this._cloudColor = value;
  12976. this.updateShaderUniforms();
  12977. },
  12978. enumerable: true,
  12979. configurable: true
  12980. });
  12981. return CloudProceduralTexture;
  12982. })(BABYLON.ProceduralTexture);
  12983. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12984. var GrassProceduralTexture = (function (_super) {
  12985. __extends(GrassProceduralTexture, _super);
  12986. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12987. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12988. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12989. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12990. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12991. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12992. this._grassColors = [
  12993. new BABYLON.Color3(0.29, 0.38, 0.02),
  12994. new BABYLON.Color3(0.36, 0.49, 0.09),
  12995. new BABYLON.Color3(0.51, 0.6, 0.28)
  12996. ];
  12997. this.updateShaderUniforms();
  12998. this.refreshRate = 0;
  12999. }
  13000. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13001. this.setColor3("herb1Color", this._grassColors[0]);
  13002. this.setColor3("herb2Color", this._grassColors[1]);
  13003. this.setColor3("herb3Color", this._grassColors[2]);
  13004. this.setColor3("groundColor", this._groundColor);
  13005. };
  13006. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13007. get: function () {
  13008. return this._grassColors;
  13009. },
  13010. set: function (value) {
  13011. this._grassColors = value;
  13012. this.updateShaderUniforms();
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13018. get: function () {
  13019. return this._groundColor;
  13020. },
  13021. set: function (value) {
  13022. this.groundColor = value;
  13023. this.updateShaderUniforms();
  13024. },
  13025. enumerable: true,
  13026. configurable: true
  13027. });
  13028. return GrassProceduralTexture;
  13029. })(BABYLON.ProceduralTexture);
  13030. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13031. var RoadProceduralTexture = (function (_super) {
  13032. __extends(RoadProceduralTexture, _super);
  13033. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13034. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13035. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13036. this.updateShaderUniforms();
  13037. this.refreshRate = 0;
  13038. }
  13039. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13040. this.setColor3("roadColor", this._roadColor);
  13041. };
  13042. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13043. get: function () {
  13044. return this._roadColor;
  13045. },
  13046. set: function (value) {
  13047. this._roadColor = value;
  13048. this.updateShaderUniforms();
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. return RoadProceduralTexture;
  13054. })(BABYLON.ProceduralTexture);
  13055. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13056. var BrickProceduralTexture = (function (_super) {
  13057. __extends(BrickProceduralTexture, _super);
  13058. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13059. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13060. this._numberOfBricksHeight = 15;
  13061. this._numberOfBricksWidth = 5;
  13062. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13063. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13064. this.updateShaderUniforms();
  13065. this.refreshRate = 0;
  13066. }
  13067. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13068. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13069. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13070. this.setColor3("brickColor", this._brickColor);
  13071. this.setColor3("jointColor", this._jointColor);
  13072. };
  13073. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13074. get: function () {
  13075. return this._numberOfBricksHeight;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13081. set: function (value) {
  13082. this._numberOfBricksHeight = value;
  13083. this.updateShaderUniforms();
  13084. },
  13085. enumerable: true,
  13086. configurable: true
  13087. });
  13088. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13089. get: function () {
  13090. return this._numberOfBricksWidth;
  13091. },
  13092. set: function (value) {
  13093. this._numberOfBricksHeight = value;
  13094. this.updateShaderUniforms();
  13095. },
  13096. enumerable: true,
  13097. configurable: true
  13098. });
  13099. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13100. get: function () {
  13101. return this._jointColor;
  13102. },
  13103. set: function (value) {
  13104. this._jointColor = value;
  13105. this.updateShaderUniforms();
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13111. get: function () {
  13112. return this._brickColor;
  13113. },
  13114. set: function (value) {
  13115. this._brickColor = value;
  13116. this.updateShaderUniforms();
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. return BrickProceduralTexture;
  13122. })(BABYLON.ProceduralTexture);
  13123. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13124. var MarbleProceduralTexture = (function (_super) {
  13125. __extends(MarbleProceduralTexture, _super);
  13126. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13127. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13128. this._numberOfTilesHeight = 3;
  13129. this._numberOfTilesWidth = 3;
  13130. this._amplitude = 9.0;
  13131. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13132. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13133. this.updateShaderUniforms();
  13134. this.refreshRate = 0;
  13135. }
  13136. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13137. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13138. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13139. this.setFloat("amplitude", this._amplitude);
  13140. this.setColor3("marbleColor", this._marbleColor);
  13141. this.setColor3("jointColor", this._jointColor);
  13142. };
  13143. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13144. get: function () {
  13145. return this._numberOfTilesHeight;
  13146. },
  13147. set: function (value) {
  13148. this._numberOfTilesHeight = value;
  13149. this.updateShaderUniforms();
  13150. },
  13151. enumerable: true,
  13152. configurable: true
  13153. });
  13154. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13155. get: function () {
  13156. return this._numberOfTilesWidth;
  13157. },
  13158. set: function (value) {
  13159. this._numberOfTilesWidth = value;
  13160. this.updateShaderUniforms();
  13161. },
  13162. enumerable: true,
  13163. configurable: true
  13164. });
  13165. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13166. get: function () {
  13167. return this._jointColor;
  13168. },
  13169. set: function (value) {
  13170. this._jointColor = value;
  13171. this.updateShaderUniforms();
  13172. },
  13173. enumerable: true,
  13174. configurable: true
  13175. });
  13176. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13177. get: function () {
  13178. return this._marbleColor;
  13179. },
  13180. set: function (value) {
  13181. this._marbleColor = value;
  13182. this.updateShaderUniforms();
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. return MarbleProceduralTexture;
  13188. })(BABYLON.ProceduralTexture);
  13189. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13190. })(BABYLON || (BABYLON = {}));
  13191. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13192. var BABYLON;
  13193. (function (BABYLON) {
  13194. var CustomProceduralTexture = (function (_super) {
  13195. __extends(CustomProceduralTexture, _super);
  13196. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13197. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13198. this._animate = true;
  13199. this._time = 0;
  13200. this._texturePath = texturePath;
  13201. //Try to load json
  13202. this.loadJson(texturePath);
  13203. this.refreshRate = 1;
  13204. }
  13205. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13206. var _this = this;
  13207. var that = this;
  13208. function noConfigFile() {
  13209. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13210. try {
  13211. that.setFragment(that._texturePath);
  13212. }
  13213. catch (ex) {
  13214. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13215. }
  13216. }
  13217. var configFileUrl = jsonUrl + "/config.json";
  13218. var xhr = new XMLHttpRequest();
  13219. xhr.open("GET", configFileUrl, true);
  13220. xhr.addEventListener("load", function () {
  13221. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13222. try {
  13223. _this._config = JSON.parse(xhr.response);
  13224. _this.updateShaderUniforms();
  13225. _this.updateTextures();
  13226. _this.setFragment(_this._texturePath + "/custom");
  13227. _this._animate = _this._config.animate;
  13228. _this.refreshRate = _this._config.refreshrate;
  13229. }
  13230. catch (ex) {
  13231. noConfigFile();
  13232. }
  13233. }
  13234. else {
  13235. noConfigFile();
  13236. }
  13237. }, false);
  13238. xhr.addEventListener("error", function () {
  13239. noConfigFile();
  13240. }, false);
  13241. try {
  13242. xhr.send();
  13243. }
  13244. catch (ex) {
  13245. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13246. }
  13247. };
  13248. CustomProceduralTexture.prototype.isReady = function () {
  13249. if (!_super.prototype.isReady.call(this)) {
  13250. return false;
  13251. }
  13252. for (var name in this._textures) {
  13253. var texture = this._textures[name];
  13254. if (!texture.isReady()) {
  13255. return false;
  13256. }
  13257. }
  13258. return true;
  13259. };
  13260. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13261. if (this._animate) {
  13262. this._time += this.getScene().getAnimationRatio() * 0.03;
  13263. this.updateShaderUniforms();
  13264. }
  13265. _super.prototype.render.call(this, useCameraPostProcess);
  13266. };
  13267. CustomProceduralTexture.prototype.updateTextures = function () {
  13268. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13269. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13270. }
  13271. };
  13272. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13273. if (this._config) {
  13274. for (var j = 0; j < this._config.uniforms.length; j++) {
  13275. var uniform = this._config.uniforms[j];
  13276. switch (uniform.type) {
  13277. case "float":
  13278. this.setFloat(uniform.name, uniform.value);
  13279. break;
  13280. case "color3":
  13281. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13282. break;
  13283. case "color4":
  13284. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13285. break;
  13286. case "vector2":
  13287. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13288. break;
  13289. case "vector3":
  13290. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13291. break;
  13292. }
  13293. }
  13294. }
  13295. this.setFloat("time", this._time);
  13296. };
  13297. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13298. get: function () {
  13299. return this._animate;
  13300. },
  13301. set: function (value) {
  13302. this._animate = value;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. return CustomProceduralTexture;
  13308. })(BABYLON.ProceduralTexture);
  13309. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13310. })(BABYLON || (BABYLON = {}));
  13311. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13312. var BABYLON;
  13313. (function (BABYLON) {
  13314. var MirrorTexture = (function (_super) {
  13315. __extends(MirrorTexture, _super);
  13316. function MirrorTexture(name, size, scene, generateMipMaps) {
  13317. var _this = this;
  13318. _super.call(this, name, size, scene, generateMipMaps, true);
  13319. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13320. this._transformMatrix = BABYLON.Matrix.Zero();
  13321. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13322. this.onBeforeRender = function () {
  13323. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13324. _this._savedViewMatrix = scene.getViewMatrix();
  13325. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13326. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13327. scene.clipPlane = _this.mirrorPlane;
  13328. scene.getEngine().cullBackFaces = false;
  13329. };
  13330. this.onAfterRender = function () {
  13331. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13332. scene.getEngine().cullBackFaces = true;
  13333. delete scene.clipPlane;
  13334. };
  13335. }
  13336. MirrorTexture.prototype.clone = function () {
  13337. var textureSize = this.getSize();
  13338. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13339. // Base texture
  13340. newTexture.hasAlpha = this.hasAlpha;
  13341. newTexture.level = this.level;
  13342. // Mirror Texture
  13343. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13344. newTexture.renderList = this.renderList.slice(0);
  13345. return newTexture;
  13346. };
  13347. return MirrorTexture;
  13348. })(BABYLON.RenderTargetTexture);
  13349. BABYLON.MirrorTexture = MirrorTexture;
  13350. })(BABYLON || (BABYLON = {}));
  13351. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13352. var BABYLON;
  13353. (function (BABYLON) {
  13354. var DynamicTexture = (function (_super) {
  13355. __extends(DynamicTexture, _super);
  13356. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13357. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13358. _super.call(this, null, scene, !generateMipMaps);
  13359. this.name = name;
  13360. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13361. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13362. this._generateMipMaps = generateMipMaps;
  13363. if (options.getContext) {
  13364. this._canvas = options;
  13365. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13366. }
  13367. else {
  13368. this._canvas = document.createElement("canvas");
  13369. if (options.width) {
  13370. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13371. }
  13372. else {
  13373. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13374. }
  13375. }
  13376. var textureSize = this.getSize();
  13377. this._canvas.width = textureSize.width;
  13378. this._canvas.height = textureSize.height;
  13379. this._context = this._canvas.getContext("2d");
  13380. }
  13381. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13382. get: function () {
  13383. return true;
  13384. },
  13385. enumerable: true,
  13386. configurable: true
  13387. });
  13388. DynamicTexture.prototype.scale = function (ratio) {
  13389. var textureSize = this.getSize();
  13390. textureSize.width *= ratio;
  13391. textureSize.height *= ratio;
  13392. this._canvas.width = textureSize.width;
  13393. this._canvas.height = textureSize.height;
  13394. this.releaseInternalTexture();
  13395. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13396. };
  13397. DynamicTexture.prototype.getContext = function () {
  13398. return this._context;
  13399. };
  13400. DynamicTexture.prototype.clear = function () {
  13401. var size = this.getSize();
  13402. this._context.fillRect(0, 0, size.width, size.height);
  13403. };
  13404. DynamicTexture.prototype.update = function (invertY) {
  13405. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13406. };
  13407. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13408. if (update === void 0) { update = true; }
  13409. var size = this.getSize();
  13410. if (clearColor) {
  13411. this._context.fillStyle = clearColor;
  13412. this._context.fillRect(0, 0, size.width, size.height);
  13413. }
  13414. this._context.font = font;
  13415. if (x === null) {
  13416. var textSize = this._context.measureText(text);
  13417. x = (size.width - textSize.width) / 2;
  13418. }
  13419. this._context.fillStyle = color;
  13420. this._context.fillText(text, x, y);
  13421. if (update) {
  13422. this.update(invertY);
  13423. }
  13424. };
  13425. DynamicTexture.prototype.clone = function () {
  13426. var textureSize = this.getSize();
  13427. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13428. // Base texture
  13429. newTexture.hasAlpha = this.hasAlpha;
  13430. newTexture.level = this.level;
  13431. // Dynamic Texture
  13432. newTexture.wrapU = this.wrapU;
  13433. newTexture.wrapV = this.wrapV;
  13434. return newTexture;
  13435. };
  13436. return DynamicTexture;
  13437. })(BABYLON.Texture);
  13438. BABYLON.DynamicTexture = DynamicTexture;
  13439. })(BABYLON || (BABYLON = {}));
  13440. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13441. var BABYLON;
  13442. (function (BABYLON) {
  13443. var VideoTexture = (function (_super) {
  13444. __extends(VideoTexture, _super);
  13445. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13446. var _this = this;
  13447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13448. _super.call(this, null, scene, !generateMipMaps, invertY);
  13449. this._autoLaunch = true;
  13450. this.name = name;
  13451. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13452. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13453. var requiredWidth = size.width || size;
  13454. var requiredHeight = size.height || size;
  13455. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13456. var textureSize = this.getSize();
  13457. this.video = document.createElement("video");
  13458. this.video.width = textureSize.width;
  13459. this.video.height = textureSize.height;
  13460. this.video.autoplay = false;
  13461. this.video.loop = true;
  13462. this.video.addEventListener("canplaythrough", function () {
  13463. if (_this._texture) {
  13464. _this._texture.isReady = true;
  13465. }
  13466. });
  13467. urls.forEach(function (url) {
  13468. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13469. var source = document.createElement("source");
  13470. source.src = url;
  13471. _this.video.appendChild(source);
  13472. });
  13473. this._lastUpdate = BABYLON.Tools.Now;
  13474. }
  13475. VideoTexture.prototype.update = function () {
  13476. if (this._autoLaunch) {
  13477. this._autoLaunch = false;
  13478. this.video.play();
  13479. }
  13480. var now = BABYLON.Tools.Now;
  13481. if (now - this._lastUpdate < 15) {
  13482. return false;
  13483. }
  13484. this._lastUpdate = now;
  13485. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13486. return true;
  13487. };
  13488. return VideoTexture;
  13489. })(BABYLON.Texture);
  13490. BABYLON.VideoTexture = VideoTexture;
  13491. })(BABYLON || (BABYLON = {}));
  13492. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13493. (function (BABYLON) {
  13494. var EffectFallbacks = (function () {
  13495. function EffectFallbacks() {
  13496. this._defines = {};
  13497. this._currentRank = 32;
  13498. this._maxRank = -1;
  13499. }
  13500. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13501. if (!this._defines[rank]) {
  13502. if (rank < this._currentRank) {
  13503. this._currentRank = rank;
  13504. }
  13505. if (rank > this._maxRank) {
  13506. this._maxRank = rank;
  13507. }
  13508. this._defines[rank] = new Array();
  13509. }
  13510. this._defines[rank].push(define);
  13511. };
  13512. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13513. get: function () {
  13514. return this._currentRank <= this._maxRank;
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13520. var currentFallbacks = this._defines[this._currentRank];
  13521. for (var index = 0; index < currentFallbacks.length; index++) {
  13522. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13523. }
  13524. this._currentRank++;
  13525. return currentDefines;
  13526. };
  13527. return EffectFallbacks;
  13528. })();
  13529. BABYLON.EffectFallbacks = EffectFallbacks;
  13530. var Effect = (function () {
  13531. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13532. var _this = this;
  13533. this._isReady = false;
  13534. this._compilationError = "";
  13535. this._valueCache = [];
  13536. this._engine = engine;
  13537. this.name = baseName;
  13538. this.defines = defines;
  13539. this._uniformsNames = uniformsNames.concat(samplers);
  13540. this._samplers = samplers;
  13541. this._attributesNames = attributesNames;
  13542. this.onError = onError;
  13543. this.onCompiled = onCompiled;
  13544. var vertexSource;
  13545. var fragmentSource;
  13546. if (baseName.vertexElement) {
  13547. vertexSource = document.getElementById(baseName.vertexElement);
  13548. if (!vertexSource) {
  13549. vertexSource = baseName.vertexElement;
  13550. }
  13551. }
  13552. else {
  13553. vertexSource = baseName.vertex || baseName;
  13554. }
  13555. if (baseName.fragmentElement) {
  13556. fragmentSource = document.getElementById(baseName.fragmentElement);
  13557. if (!fragmentSource) {
  13558. fragmentSource = baseName.fragmentElement;
  13559. }
  13560. }
  13561. else {
  13562. fragmentSource = baseName.fragment || baseName;
  13563. }
  13564. this._loadVertexShader(vertexSource, function (vertexCode) {
  13565. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13566. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13567. });
  13568. });
  13569. }
  13570. // Properties
  13571. Effect.prototype.isReady = function () {
  13572. return this._isReady;
  13573. };
  13574. Effect.prototype.getProgram = function () {
  13575. return this._program;
  13576. };
  13577. Effect.prototype.getAttributesNames = function () {
  13578. return this._attributesNames;
  13579. };
  13580. Effect.prototype.getAttributeLocation = function (index) {
  13581. return this._attributes[index];
  13582. };
  13583. Effect.prototype.getAttributeLocationByName = function (name) {
  13584. var index = this._attributesNames.indexOf(name);
  13585. return this._attributes[index];
  13586. };
  13587. Effect.prototype.getAttributesCount = function () {
  13588. return this._attributes.length;
  13589. };
  13590. Effect.prototype.getUniformIndex = function (uniformName) {
  13591. return this._uniformsNames.indexOf(uniformName);
  13592. };
  13593. Effect.prototype.getUniform = function (uniformName) {
  13594. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13595. };
  13596. Effect.prototype.getSamplers = function () {
  13597. return this._samplers;
  13598. };
  13599. Effect.prototype.getCompilationError = function () {
  13600. return this._compilationError;
  13601. };
  13602. // Methods
  13603. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13604. // DOM element ?
  13605. if (vertex instanceof HTMLElement) {
  13606. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13607. callback(vertexCode);
  13608. return;
  13609. }
  13610. // Is in local store ?
  13611. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13612. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13613. return;
  13614. }
  13615. var vertexShaderUrl;
  13616. if (vertex[0] === ".") {
  13617. vertexShaderUrl = vertex;
  13618. }
  13619. else {
  13620. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13621. }
  13622. // Vertex shader
  13623. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13624. };
  13625. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13626. // DOM element ?
  13627. if (fragment instanceof HTMLElement) {
  13628. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13629. callback(fragmentCode);
  13630. return;
  13631. }
  13632. // Is in local store ?
  13633. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13634. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13635. return;
  13636. }
  13637. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13638. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13639. return;
  13640. }
  13641. var fragmentShaderUrl;
  13642. if (fragment[0] === ".") {
  13643. fragmentShaderUrl = fragment;
  13644. }
  13645. else {
  13646. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13647. }
  13648. // Fragment shader
  13649. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13650. };
  13651. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13652. try {
  13653. var engine = this._engine;
  13654. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13655. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13656. this._attributes = engine.getAttributes(this._program, attributesNames);
  13657. for (var index = 0; index < this._samplers.length; index++) {
  13658. var sampler = this.getUniform(this._samplers[index]);
  13659. if (sampler == null) {
  13660. this._samplers.splice(index, 1);
  13661. index--;
  13662. }
  13663. }
  13664. engine.bindSamplers(this);
  13665. this._isReady = true;
  13666. if (this.onCompiled) {
  13667. this.onCompiled(this);
  13668. }
  13669. }
  13670. catch (e) {
  13671. // Is it a problem with precision?
  13672. if (e.message.indexOf("highp") !== -1) {
  13673. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13674. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13675. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13676. return;
  13677. }
  13678. // Let's go through fallbacks then
  13679. if (fallbacks && fallbacks.isMoreFallbacks) {
  13680. defines = fallbacks.reduce(defines);
  13681. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13682. }
  13683. else {
  13684. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13685. BABYLON.Tools.Error("Defines: " + defines);
  13686. BABYLON.Tools.Error("Error: " + e.message);
  13687. this._compilationError = e.message;
  13688. if (this.onError) {
  13689. this.onError(this, this._compilationError);
  13690. }
  13691. }
  13692. }
  13693. };
  13694. Effect.prototype._bindTexture = function (channel, texture) {
  13695. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13696. };
  13697. Effect.prototype.setTexture = function (channel, texture) {
  13698. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13699. };
  13700. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13701. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13702. };
  13703. //public _cacheMatrix(uniformName, matrix) {
  13704. // if (!this._valueCache[uniformName]) {
  13705. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13706. // }
  13707. // for (var index = 0; index < 16; index++) {
  13708. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13709. // }
  13710. //};
  13711. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13712. if (!this._valueCache[uniformName]) {
  13713. this._valueCache[uniformName] = [x, y];
  13714. return;
  13715. }
  13716. this._valueCache[uniformName][0] = x;
  13717. this._valueCache[uniformName][1] = y;
  13718. };
  13719. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13720. if (!this._valueCache[uniformName]) {
  13721. this._valueCache[uniformName] = [x, y, z];
  13722. return;
  13723. }
  13724. this._valueCache[uniformName][0] = x;
  13725. this._valueCache[uniformName][1] = y;
  13726. this._valueCache[uniformName][2] = z;
  13727. };
  13728. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13729. if (!this._valueCache[uniformName]) {
  13730. this._valueCache[uniformName] = [x, y, z, w];
  13731. return;
  13732. }
  13733. this._valueCache[uniformName][0] = x;
  13734. this._valueCache[uniformName][1] = y;
  13735. this._valueCache[uniformName][2] = z;
  13736. this._valueCache[uniformName][3] = w;
  13737. };
  13738. Effect.prototype.setArray = function (uniformName, array) {
  13739. this._engine.setArray(this.getUniform(uniformName), array);
  13740. return this;
  13741. };
  13742. Effect.prototype.setArray2 = function (uniformName, array) {
  13743. this._engine.setArray2(this.getUniform(uniformName), array);
  13744. return this;
  13745. };
  13746. Effect.prototype.setArray3 = function (uniformName, array) {
  13747. this._engine.setArray3(this.getUniform(uniformName), array);
  13748. return this;
  13749. };
  13750. Effect.prototype.setArray4 = function (uniformName, array) {
  13751. this._engine.setArray4(this.getUniform(uniformName), array);
  13752. return this;
  13753. };
  13754. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13755. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13756. return this;
  13757. };
  13758. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13759. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13760. // return;
  13761. //this._cacheMatrix(uniformName, matrix);
  13762. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13763. return this;
  13764. };
  13765. Effect.prototype.setFloat = function (uniformName, value) {
  13766. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13767. return this;
  13768. this._valueCache[uniformName] = value;
  13769. this._engine.setFloat(this.getUniform(uniformName), value);
  13770. return this;
  13771. };
  13772. Effect.prototype.setBool = function (uniformName, bool) {
  13773. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13774. return this;
  13775. this._valueCache[uniformName] = bool;
  13776. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13777. return this;
  13778. };
  13779. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13780. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13781. return this;
  13782. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13783. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13784. return this;
  13785. };
  13786. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13787. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13788. return this;
  13789. this._cacheFloat2(uniformName, x, y);
  13790. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13791. return this;
  13792. };
  13793. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13794. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13795. return this;
  13796. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13797. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13798. return this;
  13799. };
  13800. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13801. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13802. return this;
  13803. this._cacheFloat3(uniformName, x, y, z);
  13804. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13805. return this;
  13806. };
  13807. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13808. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13809. return this;
  13810. this._cacheFloat4(uniformName, x, y, z, w);
  13811. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13812. return this;
  13813. };
  13814. Effect.prototype.setColor3 = function (uniformName, color3) {
  13815. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13816. return this;
  13817. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13818. this._engine.setColor3(this.getUniform(uniformName), color3);
  13819. return this;
  13820. };
  13821. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13822. 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)
  13823. return this;
  13824. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13825. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13826. return this;
  13827. };
  13828. // Statics
  13829. 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}",
  13830. 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}",
  13831. 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}",
  13832. 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}",
  13833. 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}",
  13834. 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}",
  13835. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13836. 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}",
  13837. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\n// varyings\nvarying vec2 vUV;\n\n// constants\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n// it means the image is 256x16 pixels\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; // space of 1 slice\n float slicePixelSize = sliceSize / width; // space of 1 pixel\n float sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\n\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  13838. 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}",
  13839. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n bias = 0.02 + bias;\n if (t <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, bias);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05 - bias, 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13840. 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}",
  13841. 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}",
  13842. 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#if defined(ALPHATEST) || defined(BASIC_RENDER)\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#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}",
  13843. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  13844. 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}",
  13845. 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}",
  13846. 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}",
  13847. 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}",
  13848. 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}",
  13849. 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}",
  13850. 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}",
  13851. 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}",
  13852. 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}",
  13853. 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}",
  13854. 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}",
  13855. 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}",
  13856. 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}",
  13857. 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}",
  13858. 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}",
  13859. 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}",
  13860. 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}",
  13861. 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}",
  13862. 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}",
  13863. 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}",
  13864. 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}",
  13865. 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}",
  13866. 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}",
  13867. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  13868. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13869. 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}",
  13870. 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}",
  13871. 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}",
  13872. 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}",
  13873. 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}",
  13874. 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}",
  13875. 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}",
  13876. };
  13877. return Effect;
  13878. })();
  13879. BABYLON.Effect = Effect;
  13880. })(BABYLON || (BABYLON = {}));
  13881. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13882. (function (BABYLON) {
  13883. var Material = (function () {
  13884. function Material(name, scene, doNotAdd) {
  13885. this.name = name;
  13886. this.checkReadyOnEveryCall = true;
  13887. this.checkReadyOnlyOnce = false;
  13888. this.state = "";
  13889. this.alpha = 1.0;
  13890. this.backFaceCulling = true;
  13891. this._wasPreviouslyReady = false;
  13892. this._fillMode = Material.TriangleFillMode;
  13893. this.pointSize = 1.0;
  13894. this.id = name;
  13895. this._scene = scene;
  13896. if (!doNotAdd) {
  13897. scene.materials.push(this);
  13898. }
  13899. }
  13900. Object.defineProperty(Material, "TriangleFillMode", {
  13901. get: function () {
  13902. return Material._TriangleFillMode;
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. Object.defineProperty(Material, "WireFrameFillMode", {
  13908. get: function () {
  13909. return Material._WireFrameFillMode;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(Material, "PointFillMode", {
  13915. get: function () {
  13916. return Material._PointFillMode;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. Object.defineProperty(Material.prototype, "wireframe", {
  13922. get: function () {
  13923. return this._fillMode === Material.WireFrameFillMode;
  13924. },
  13925. set: function (value) {
  13926. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13927. },
  13928. enumerable: true,
  13929. configurable: true
  13930. });
  13931. Object.defineProperty(Material.prototype, "pointsCloud", {
  13932. get: function () {
  13933. return this._fillMode === Material.PointFillMode;
  13934. },
  13935. set: function (value) {
  13936. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13937. },
  13938. enumerable: true,
  13939. configurable: true
  13940. });
  13941. Object.defineProperty(Material.prototype, "fillMode", {
  13942. get: function () {
  13943. return this._fillMode;
  13944. },
  13945. set: function (value) {
  13946. this._fillMode = value;
  13947. },
  13948. enumerable: true,
  13949. configurable: true
  13950. });
  13951. Material.prototype.isReady = function (mesh, useInstances) {
  13952. return true;
  13953. };
  13954. Material.prototype.getEffect = function () {
  13955. return this._effect;
  13956. };
  13957. Material.prototype.getScene = function () {
  13958. return this._scene;
  13959. };
  13960. Material.prototype.needAlphaBlending = function () {
  13961. return (this.alpha < 1.0);
  13962. };
  13963. Material.prototype.needAlphaTesting = function () {
  13964. return false;
  13965. };
  13966. Material.prototype.getAlphaTestTexture = function () {
  13967. return null;
  13968. };
  13969. Material.prototype.trackCreation = function (onCompiled, onError) {
  13970. };
  13971. Material.prototype._preBind = function () {
  13972. var engine = this._scene.getEngine();
  13973. engine.enableEffect(this._effect);
  13974. engine.setState(this.backFaceCulling);
  13975. };
  13976. Material.prototype.bind = function (world, mesh) {
  13977. this._scene._cachedMaterial = this;
  13978. if (this.onBind) {
  13979. this.onBind(this);
  13980. }
  13981. };
  13982. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13983. };
  13984. Material.prototype.unbind = function () {
  13985. };
  13986. Material.prototype.dispose = function (forceDisposeEffect) {
  13987. // Remove from scene
  13988. var index = this._scene.materials.indexOf(this);
  13989. this._scene.materials.splice(index, 1);
  13990. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13991. if (forceDisposeEffect && this._effect) {
  13992. this._scene.getEngine()._releaseEffect(this._effect);
  13993. this._effect = null;
  13994. }
  13995. // Callback
  13996. if (this.onDispose) {
  13997. this.onDispose();
  13998. }
  13999. };
  14000. Material._TriangleFillMode = 0;
  14001. Material._WireFrameFillMode = 1;
  14002. Material._PointFillMode = 2;
  14003. return Material;
  14004. })();
  14005. BABYLON.Material = Material;
  14006. })(BABYLON || (BABYLON = {}));
  14007. //# sourceMappingURL=babylon.material.js.map
  14008. var BABYLON;
  14009. (function (BABYLON) {
  14010. var maxSimultaneousLights = 4;
  14011. var FresnelParameters = (function () {
  14012. function FresnelParameters() {
  14013. this.isEnabled = true;
  14014. this.leftColor = BABYLON.Color3.White();
  14015. this.rightColor = BABYLON.Color3.Black();
  14016. this.bias = 0;
  14017. this.power = 1;
  14018. }
  14019. return FresnelParameters;
  14020. })();
  14021. BABYLON.FresnelParameters = FresnelParameters;
  14022. var StandardMaterial = (function (_super) {
  14023. __extends(StandardMaterial, _super);
  14024. function StandardMaterial(name, scene) {
  14025. var _this = this;
  14026. _super.call(this, name, scene);
  14027. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14028. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14029. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14030. this.specularPower = 64;
  14031. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14032. this.useAlphaFromDiffuseTexture = false;
  14033. this.useSpecularOverAlpha = true;
  14034. this.fogEnabled = true;
  14035. this._cachedDefines = null;
  14036. this._renderTargets = new BABYLON.SmartArray(16);
  14037. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14038. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14039. this._scaledDiffuse = new BABYLON.Color3();
  14040. this._scaledSpecular = new BABYLON.Color3();
  14041. this.getRenderTargetTextures = function () {
  14042. _this._renderTargets.reset();
  14043. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14044. _this._renderTargets.push(_this.reflectionTexture);
  14045. }
  14046. return _this._renderTargets;
  14047. };
  14048. }
  14049. StandardMaterial.prototype.needAlphaBlending = function () {
  14050. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14051. };
  14052. StandardMaterial.prototype.needAlphaTesting = function () {
  14053. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14054. };
  14055. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14056. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14057. };
  14058. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14059. return this.diffuseTexture;
  14060. };
  14061. // Methods
  14062. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14063. if (this.checkReadyOnlyOnce) {
  14064. if (this._wasPreviouslyReady) {
  14065. return true;
  14066. }
  14067. }
  14068. var scene = this.getScene();
  14069. if (!this.checkReadyOnEveryCall) {
  14070. if (this._renderId === scene.getRenderId()) {
  14071. return true;
  14072. }
  14073. }
  14074. var engine = scene.getEngine();
  14075. var defines = [];
  14076. var fallbacks = new BABYLON.EffectFallbacks();
  14077. var needNormals = false;
  14078. var needUVs = false;
  14079. // Textures
  14080. if (scene.texturesEnabled) {
  14081. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14082. if (!this.diffuseTexture.isReady()) {
  14083. return false;
  14084. }
  14085. else {
  14086. needUVs = true;
  14087. defines.push("#define DIFFUSE");
  14088. }
  14089. }
  14090. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14091. if (!this.ambientTexture.isReady()) {
  14092. return false;
  14093. }
  14094. else {
  14095. needUVs = true;
  14096. defines.push("#define AMBIENT");
  14097. }
  14098. }
  14099. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14100. if (!this.opacityTexture.isReady()) {
  14101. return false;
  14102. }
  14103. else {
  14104. needUVs = true;
  14105. defines.push("#define OPACITY");
  14106. if (this.opacityTexture.getAlphaFromRGB) {
  14107. defines.push("#define OPACITYRGB");
  14108. }
  14109. }
  14110. }
  14111. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14112. if (!this.reflectionTexture.isReady()) {
  14113. return false;
  14114. }
  14115. else {
  14116. needNormals = true;
  14117. needUVs = true;
  14118. defines.push("#define REFLECTION");
  14119. fallbacks.addFallback(0, "REFLECTION");
  14120. }
  14121. }
  14122. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14123. if (!this.emissiveTexture.isReady()) {
  14124. return false;
  14125. }
  14126. else {
  14127. needUVs = true;
  14128. defines.push("#define EMISSIVE");
  14129. }
  14130. }
  14131. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14132. if (!this.specularTexture.isReady()) {
  14133. return false;
  14134. }
  14135. else {
  14136. needUVs = true;
  14137. defines.push("#define SPECULAR");
  14138. fallbacks.addFallback(0, "SPECULAR");
  14139. }
  14140. }
  14141. }
  14142. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14143. if (!this.bumpTexture.isReady()) {
  14144. return false;
  14145. }
  14146. else {
  14147. needUVs = true;
  14148. defines.push("#define BUMP");
  14149. fallbacks.addFallback(0, "BUMP");
  14150. }
  14151. }
  14152. // Effect
  14153. if (this.useSpecularOverAlpha) {
  14154. defines.push("#define SPECULAROVERALPHA");
  14155. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14156. }
  14157. if (scene.clipPlane) {
  14158. defines.push("#define CLIPPLANE");
  14159. }
  14160. if (engine.getAlphaTesting()) {
  14161. defines.push("#define ALPHATEST");
  14162. }
  14163. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14164. defines.push("#define ALPHAFROMDIFFUSE");
  14165. }
  14166. // Point size
  14167. if (this.pointsCloud || scene.forcePointsCloud) {
  14168. defines.push("#define POINTSIZE");
  14169. }
  14170. // Fog
  14171. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14172. defines.push("#define FOG");
  14173. fallbacks.addFallback(1, "FOG");
  14174. }
  14175. var shadowsActivated = false;
  14176. var lightIndex = 0;
  14177. if (scene.lightsEnabled) {
  14178. for (var index = 0; index < scene.lights.length; index++) {
  14179. var light = scene.lights[index];
  14180. if (!light.isEnabled()) {
  14181. continue;
  14182. }
  14183. // Excluded check
  14184. if (light._excludedMeshesIds.length > 0) {
  14185. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14186. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14187. if (excludedMesh) {
  14188. light.excludedMeshes.push(excludedMesh);
  14189. }
  14190. }
  14191. light._excludedMeshesIds = [];
  14192. }
  14193. // Included check
  14194. if (light._includedOnlyMeshesIds.length > 0) {
  14195. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14196. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14197. if (includedOnlyMesh) {
  14198. light.includedOnlyMeshes.push(includedOnlyMesh);
  14199. }
  14200. }
  14201. light._includedOnlyMeshesIds = [];
  14202. }
  14203. if (!light.canAffectMesh(mesh)) {
  14204. continue;
  14205. }
  14206. needNormals = true;
  14207. defines.push("#define LIGHT" + lightIndex);
  14208. if (lightIndex > 0) {
  14209. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14210. }
  14211. var type;
  14212. if (light instanceof BABYLON.SpotLight) {
  14213. type = "#define SPOTLIGHT" + lightIndex;
  14214. }
  14215. else if (light instanceof BABYLON.HemisphericLight) {
  14216. type = "#define HEMILIGHT" + lightIndex;
  14217. }
  14218. else {
  14219. type = "#define POINTDIRLIGHT" + lightIndex;
  14220. }
  14221. defines.push(type);
  14222. if (lightIndex > 0) {
  14223. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14224. }
  14225. // Shadows
  14226. if (scene.shadowsEnabled) {
  14227. var shadowGenerator = light.getShadowGenerator();
  14228. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14229. defines.push("#define SHADOW" + lightIndex);
  14230. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14231. if (!shadowsActivated) {
  14232. defines.push("#define SHADOWS");
  14233. shadowsActivated = true;
  14234. }
  14235. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14236. defines.push("#define SHADOWVSM" + lightIndex);
  14237. if (lightIndex > 0) {
  14238. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14239. }
  14240. }
  14241. if (shadowGenerator.usePoissonSampling) {
  14242. defines.push("#define SHADOWPCF" + lightIndex);
  14243. if (lightIndex > 0) {
  14244. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14245. }
  14246. }
  14247. }
  14248. }
  14249. lightIndex++;
  14250. if (lightIndex === maxSimultaneousLights)
  14251. break;
  14252. }
  14253. }
  14254. if (StandardMaterial.FresnelEnabled) {
  14255. // Fresnel
  14256. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14257. var fresnelRank = 1;
  14258. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14259. defines.push("#define DIFFUSEFRESNEL");
  14260. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14261. fresnelRank++;
  14262. }
  14263. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14264. defines.push("#define OPACITYFRESNEL");
  14265. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14266. fresnelRank++;
  14267. }
  14268. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14269. defines.push("#define REFLECTIONFRESNEL");
  14270. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14271. fresnelRank++;
  14272. }
  14273. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14274. defines.push("#define EMISSIVEFRESNEL");
  14275. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14276. fresnelRank++;
  14277. }
  14278. needNormals = true;
  14279. defines.push("#define FRESNEL");
  14280. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14281. }
  14282. }
  14283. // Attribs
  14284. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14285. if (mesh) {
  14286. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14287. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14288. defines.push("#define NORMAL");
  14289. }
  14290. if (needUVs) {
  14291. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14292. attribs.push(BABYLON.VertexBuffer.UVKind);
  14293. defines.push("#define UV1");
  14294. }
  14295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14296. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14297. defines.push("#define UV2");
  14298. }
  14299. }
  14300. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14301. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14302. defines.push("#define VERTEXCOLOR");
  14303. if (mesh.hasVertexAlpha) {
  14304. defines.push("#define VERTEXALPHA");
  14305. }
  14306. }
  14307. if (mesh.useBones) {
  14308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14310. defines.push("#define BONES");
  14311. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14312. defines.push("#define BONES4");
  14313. fallbacks.addFallback(0, "BONES4");
  14314. }
  14315. // Instances
  14316. if (useInstances) {
  14317. defines.push("#define INSTANCES");
  14318. attribs.push("world0");
  14319. attribs.push("world1");
  14320. attribs.push("world2");
  14321. attribs.push("world3");
  14322. }
  14323. }
  14324. // Get correct effect
  14325. var join = defines.join("\n");
  14326. if (this._cachedDefines !== join) {
  14327. this._cachedDefines = join;
  14328. scene.resetCachedMaterial();
  14329. // Legacy browser patch
  14330. var shaderName = "default";
  14331. if (!scene.getEngine().getCaps().standardDerivatives) {
  14332. shaderName = "legacydefault";
  14333. }
  14334. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  14335. }
  14336. if (!this._effect.isReady()) {
  14337. return false;
  14338. }
  14339. this._renderId = scene.getRenderId();
  14340. this._wasPreviouslyReady = true;
  14341. return true;
  14342. };
  14343. StandardMaterial.prototype.unbind = function () {
  14344. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14345. this._effect.setTexture("reflection2DSampler", null);
  14346. }
  14347. };
  14348. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14349. this._effect.setMatrix("world", world);
  14350. };
  14351. StandardMaterial.prototype.bind = function (world, mesh) {
  14352. var scene = this.getScene();
  14353. // Matrices
  14354. this.bindOnlyWorldMatrix(world);
  14355. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14356. // Bones
  14357. if (mesh.useBones) {
  14358. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14359. }
  14360. if (scene.getCachedMaterial() !== this) {
  14361. if (StandardMaterial.FresnelEnabled) {
  14362. // Fresnel
  14363. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14364. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14365. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14366. }
  14367. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14368. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14369. }
  14370. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14371. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14372. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14373. }
  14374. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14375. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14376. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14377. }
  14378. }
  14379. // Textures
  14380. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14381. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14382. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14383. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14384. }
  14385. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14386. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14387. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14388. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14389. }
  14390. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14391. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14392. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14393. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14394. }
  14395. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14396. if (this.reflectionTexture.isCube) {
  14397. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14398. }
  14399. else {
  14400. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14401. }
  14402. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14403. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14404. }
  14405. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14406. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14407. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14408. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14409. }
  14410. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14411. this._effect.setTexture("specularSampler", this.specularTexture);
  14412. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14413. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14414. }
  14415. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14416. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14417. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14418. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14419. }
  14420. // Clip plane
  14421. if (scene.clipPlane) {
  14422. var clipPlane = scene.clipPlane;
  14423. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14424. }
  14425. // Point size
  14426. if (this.pointsCloud) {
  14427. this._effect.setFloat("pointSize", this.pointSize);
  14428. }
  14429. // Colors
  14430. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14431. // Scaling down color according to emissive
  14432. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14433. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14434. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14435. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14436. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14437. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14438. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14439. }
  14440. // Scaling down color according to emissive
  14441. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14442. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14443. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14444. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14445. if (scene.lightsEnabled) {
  14446. var lightIndex = 0;
  14447. for (var index = 0; index < scene.lights.length; index++) {
  14448. var light = scene.lights[index];
  14449. if (!light.isEnabled()) {
  14450. continue;
  14451. }
  14452. if (!light.canAffectMesh(mesh)) {
  14453. continue;
  14454. }
  14455. if (light instanceof BABYLON.PointLight) {
  14456. // Point Light
  14457. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14458. }
  14459. else if (light instanceof BABYLON.DirectionalLight) {
  14460. // Directional Light
  14461. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14462. }
  14463. else if (light instanceof BABYLON.SpotLight) {
  14464. // Spot Light
  14465. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14466. }
  14467. else if (light instanceof BABYLON.HemisphericLight) {
  14468. // Hemispheric Light
  14469. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14470. }
  14471. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14472. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14473. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14474. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14475. // Shadows
  14476. if (scene.shadowsEnabled) {
  14477. var shadowGenerator = light.getShadowGenerator();
  14478. if (mesh.receiveShadows && shadowGenerator) {
  14479. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14480. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14481. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14482. }
  14483. }
  14484. lightIndex++;
  14485. if (lightIndex === maxSimultaneousLights)
  14486. break;
  14487. }
  14488. }
  14489. // View
  14490. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14491. this._effect.setMatrix("view", scene.getViewMatrix());
  14492. }
  14493. // Fog
  14494. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14495. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14496. this._effect.setColor3("vFogColor", scene.fogColor);
  14497. }
  14498. _super.prototype.bind.call(this, world, mesh);
  14499. };
  14500. StandardMaterial.prototype.getAnimatables = function () {
  14501. var results = [];
  14502. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14503. results.push(this.diffuseTexture);
  14504. }
  14505. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14506. results.push(this.ambientTexture);
  14507. }
  14508. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14509. results.push(this.opacityTexture);
  14510. }
  14511. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14512. results.push(this.reflectionTexture);
  14513. }
  14514. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14515. results.push(this.emissiveTexture);
  14516. }
  14517. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14518. results.push(this.specularTexture);
  14519. }
  14520. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14521. results.push(this.bumpTexture);
  14522. }
  14523. return results;
  14524. };
  14525. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14526. if (this.diffuseTexture) {
  14527. this.diffuseTexture.dispose();
  14528. }
  14529. if (this.ambientTexture) {
  14530. this.ambientTexture.dispose();
  14531. }
  14532. if (this.opacityTexture) {
  14533. this.opacityTexture.dispose();
  14534. }
  14535. if (this.reflectionTexture) {
  14536. this.reflectionTexture.dispose();
  14537. }
  14538. if (this.emissiveTexture) {
  14539. this.emissiveTexture.dispose();
  14540. }
  14541. if (this.specularTexture) {
  14542. this.specularTexture.dispose();
  14543. }
  14544. if (this.bumpTexture) {
  14545. this.bumpTexture.dispose();
  14546. }
  14547. _super.prototype.dispose.call(this, forceDisposeEffect);
  14548. };
  14549. StandardMaterial.prototype.clone = function (name) {
  14550. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14551. // Base material
  14552. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14553. newStandardMaterial.alpha = this.alpha;
  14554. newStandardMaterial.fillMode = this.fillMode;
  14555. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14556. // Standard material
  14557. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14558. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14559. }
  14560. if (this.ambientTexture && this.ambientTexture.clone) {
  14561. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14562. }
  14563. if (this.opacityTexture && this.opacityTexture.clone) {
  14564. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14565. }
  14566. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14567. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14568. }
  14569. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14570. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14571. }
  14572. if (this.specularTexture && this.specularTexture.clone) {
  14573. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14574. }
  14575. if (this.bumpTexture && this.bumpTexture.clone) {
  14576. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14577. }
  14578. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14579. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14580. newStandardMaterial.specularColor = this.specularColor.clone();
  14581. newStandardMaterial.specularPower = this.specularPower;
  14582. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14583. return newStandardMaterial;
  14584. };
  14585. // Statics
  14586. // Flags used to enable or disable a type of texture for all Standard Materials
  14587. StandardMaterial.DiffuseTextureEnabled = true;
  14588. StandardMaterial.AmbientTextureEnabled = true;
  14589. StandardMaterial.OpacityTextureEnabled = true;
  14590. StandardMaterial.ReflectionTextureEnabled = true;
  14591. StandardMaterial.EmissiveTextureEnabled = true;
  14592. StandardMaterial.SpecularTextureEnabled = true;
  14593. StandardMaterial.BumpTextureEnabled = true;
  14594. StandardMaterial.FresnelEnabled = true;
  14595. return StandardMaterial;
  14596. })(BABYLON.Material);
  14597. BABYLON.StandardMaterial = StandardMaterial;
  14598. })(BABYLON || (BABYLON = {}));
  14599. //# sourceMappingURL=babylon.standardMaterial.js.map
  14600. var BABYLON;
  14601. (function (BABYLON) {
  14602. var MultiMaterial = (function (_super) {
  14603. __extends(MultiMaterial, _super);
  14604. function MultiMaterial(name, scene) {
  14605. _super.call(this, name, scene, true);
  14606. this.subMaterials = new Array();
  14607. scene.multiMaterials.push(this);
  14608. }
  14609. // Properties
  14610. MultiMaterial.prototype.getSubMaterial = function (index) {
  14611. if (index < 0 || index >= this.subMaterials.length) {
  14612. return this.getScene().defaultMaterial;
  14613. }
  14614. return this.subMaterials[index];
  14615. };
  14616. // Methods
  14617. MultiMaterial.prototype.isReady = function (mesh) {
  14618. for (var index = 0; index < this.subMaterials.length; index++) {
  14619. var subMaterial = this.subMaterials[index];
  14620. if (subMaterial) {
  14621. if (!this.subMaterials[index].isReady(mesh)) {
  14622. return false;
  14623. }
  14624. }
  14625. }
  14626. return true;
  14627. };
  14628. return MultiMaterial;
  14629. })(BABYLON.Material);
  14630. BABYLON.MultiMaterial = MultiMaterial;
  14631. })(BABYLON || (BABYLON = {}));
  14632. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14633. (function (BABYLON) {
  14634. var Database = (function () {
  14635. function Database(urlToScene, callbackManifestChecked) {
  14636. // Handling various flavors of prefixed version of IndexedDB
  14637. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14638. this.callbackManifestChecked = callbackManifestChecked;
  14639. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14640. this.db = null;
  14641. this.enableSceneOffline = false;
  14642. this.enableTexturesOffline = false;
  14643. this.manifestVersionFound = 0;
  14644. this.mustUpdateRessources = false;
  14645. this.hasReachedQuota = false;
  14646. this.checkManifestFile();
  14647. }
  14648. Database.prototype.checkManifestFile = function () {
  14649. var _this = this;
  14650. function noManifestFile() {
  14651. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14652. that.enableSceneOffline = false;
  14653. that.enableTexturesOffline = false;
  14654. that.callbackManifestChecked(false);
  14655. }
  14656. var that = this;
  14657. var manifestURL = this.currentSceneUrl + ".manifest";
  14658. var xhr = new XMLHttpRequest();
  14659. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14660. xhr.open("GET", manifestURLTimeStamped, true);
  14661. xhr.addEventListener("load", function () {
  14662. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14663. try {
  14664. var manifestFile = JSON.parse(xhr.response);
  14665. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14666. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14667. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14668. _this.manifestVersionFound = manifestFile.version;
  14669. }
  14670. if (_this.callbackManifestChecked) {
  14671. _this.callbackManifestChecked(true);
  14672. }
  14673. }
  14674. catch (ex) {
  14675. noManifestFile();
  14676. }
  14677. }
  14678. else {
  14679. noManifestFile();
  14680. }
  14681. }, false);
  14682. xhr.addEventListener("error", function (event) {
  14683. noManifestFile();
  14684. }, false);
  14685. try {
  14686. xhr.send();
  14687. }
  14688. catch (ex) {
  14689. BABYLON.Tools.Error("Error on XHR send request.");
  14690. that.callbackManifestChecked(false);
  14691. }
  14692. };
  14693. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14694. var _this = this;
  14695. function handleError() {
  14696. that.isSupported = false;
  14697. if (errorCallback)
  14698. errorCallback();
  14699. }
  14700. var that = this;
  14701. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14702. // Your browser doesn't support IndexedDB
  14703. this.isSupported = false;
  14704. if (errorCallback)
  14705. errorCallback();
  14706. }
  14707. else {
  14708. // If the DB hasn't been opened or created yet
  14709. if (!this.db) {
  14710. this.hasReachedQuota = false;
  14711. this.isSupported = true;
  14712. var request = this.idbFactory.open("babylonjs", 1);
  14713. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14714. request.onerror = function (event) {
  14715. handleError();
  14716. };
  14717. // executes when a version change transaction cannot complete due to other active transactions
  14718. request.onblocked = function (event) {
  14719. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14720. handleError();
  14721. };
  14722. // DB has been opened successfully
  14723. request.onsuccess = function (event) {
  14724. _this.db = request.result;
  14725. successCallback();
  14726. };
  14727. // Initialization of the DB. Creating Scenes & Textures stores
  14728. request.onupgradeneeded = function (event) {
  14729. _this.db = (event.target).result;
  14730. try {
  14731. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14732. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14733. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14734. }
  14735. catch (ex) {
  14736. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14737. handleError();
  14738. }
  14739. };
  14740. }
  14741. else {
  14742. if (successCallback)
  14743. successCallback();
  14744. }
  14745. }
  14746. };
  14747. Database.prototype.loadImageFromDB = function (url, image) {
  14748. var _this = this;
  14749. var completeURL = Database.ReturnFullUrlLocation(url);
  14750. var saveAndLoadImage = function () {
  14751. if (!_this.hasReachedQuota && _this.db !== null) {
  14752. // the texture is not yet in the DB, let's try to save it
  14753. _this._saveImageIntoDBAsync(completeURL, image);
  14754. }
  14755. else {
  14756. image.src = url;
  14757. }
  14758. };
  14759. if (!this.mustUpdateRessources) {
  14760. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14761. }
  14762. else {
  14763. saveAndLoadImage();
  14764. }
  14765. };
  14766. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14767. if (this.isSupported && this.db !== null) {
  14768. var texture;
  14769. var transaction = this.db.transaction(["textures"]);
  14770. transaction.onabort = function (event) {
  14771. image.src = url;
  14772. };
  14773. transaction.oncomplete = function (event) {
  14774. var blobTextureURL;
  14775. if (texture) {
  14776. var URL = window.URL || window.webkitURL;
  14777. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14778. image.onerror = function () {
  14779. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14780. image.src = url;
  14781. };
  14782. image.src = blobTextureURL;
  14783. }
  14784. else {
  14785. notInDBCallback();
  14786. }
  14787. };
  14788. var getRequest = transaction.objectStore("textures").get(url);
  14789. getRequest.onsuccess = function (event) {
  14790. texture = (event.target).result;
  14791. };
  14792. getRequest.onerror = function (event) {
  14793. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14794. image.src = url;
  14795. };
  14796. }
  14797. else {
  14798. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14799. image.src = url;
  14800. }
  14801. };
  14802. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14803. var _this = this;
  14804. if (this.isSupported) {
  14805. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14806. var generateBlobUrl = function () {
  14807. var blobTextureURL;
  14808. if (blob) {
  14809. var URL = window.URL || window.webkitURL;
  14810. try {
  14811. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14812. }
  14813. catch (ex) {
  14814. blobTextureURL = URL.createObjectURL(blob);
  14815. }
  14816. }
  14817. image.src = blobTextureURL;
  14818. };
  14819. if (Database.isUASupportingBlobStorage) {
  14820. var xhr = new XMLHttpRequest(), blob;
  14821. xhr.open("GET", url, true);
  14822. xhr.responseType = "blob";
  14823. xhr.addEventListener("load", function () {
  14824. if (xhr.status === 200) {
  14825. // Blob as response (XHR2)
  14826. blob = xhr.response;
  14827. var transaction = _this.db.transaction(["textures"], "readwrite");
  14828. // the transaction could abort because of a QuotaExceededError error
  14829. transaction.onabort = function (event) {
  14830. try {
  14831. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14832. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14833. this.hasReachedQuota = true;
  14834. }
  14835. }
  14836. catch (ex) {
  14837. }
  14838. generateBlobUrl();
  14839. };
  14840. transaction.oncomplete = function (event) {
  14841. generateBlobUrl();
  14842. };
  14843. var newTexture = { textureUrl: url, data: blob };
  14844. try {
  14845. // Put the blob into the dabase
  14846. var addRequest = transaction.objectStore("textures").put(newTexture);
  14847. addRequest.onsuccess = function (event) {
  14848. };
  14849. addRequest.onerror = function (event) {
  14850. generateBlobUrl();
  14851. };
  14852. }
  14853. catch (ex) {
  14854. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14855. if (ex.code === 25) {
  14856. Database.isUASupportingBlobStorage = false;
  14857. }
  14858. image.src = url;
  14859. }
  14860. }
  14861. else {
  14862. image.src = url;
  14863. }
  14864. }, false);
  14865. xhr.addEventListener("error", function (event) {
  14866. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14867. image.src = url;
  14868. }, false);
  14869. xhr.send();
  14870. }
  14871. else {
  14872. image.src = url;
  14873. }
  14874. }
  14875. else {
  14876. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14877. image.src = url;
  14878. }
  14879. };
  14880. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14881. var _this = this;
  14882. var updateVersion = function (event) {
  14883. // the version is not yet in the DB or we need to update it
  14884. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14885. };
  14886. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14887. };
  14888. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14889. var _this = this;
  14890. if (this.isSupported) {
  14891. var version;
  14892. try {
  14893. var transaction = this.db.transaction(["versions"]);
  14894. transaction.oncomplete = function (event) {
  14895. if (version) {
  14896. // If the version in the JSON file is > than the version in DB
  14897. if (_this.manifestVersionFound > version.data) {
  14898. _this.mustUpdateRessources = true;
  14899. updateInDBCallback();
  14900. }
  14901. else {
  14902. callback(version.data);
  14903. }
  14904. }
  14905. else {
  14906. _this.mustUpdateRessources = true;
  14907. updateInDBCallback();
  14908. }
  14909. };
  14910. transaction.onabort = function (event) {
  14911. callback(-1);
  14912. };
  14913. var getRequest = transaction.objectStore("versions").get(url);
  14914. getRequest.onsuccess = function (event) {
  14915. version = (event.target).result;
  14916. };
  14917. getRequest.onerror = function (event) {
  14918. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14919. callback(-1);
  14920. };
  14921. }
  14922. catch (ex) {
  14923. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14924. callback(-1);
  14925. }
  14926. }
  14927. else {
  14928. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14929. callback(-1);
  14930. }
  14931. };
  14932. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14933. var _this = this;
  14934. if (this.isSupported && !this.hasReachedQuota) {
  14935. try {
  14936. // Open a transaction to the database
  14937. var transaction = this.db.transaction(["versions"], "readwrite");
  14938. // the transaction could abort because of a QuotaExceededError error
  14939. transaction.onabort = function (event) {
  14940. try {
  14941. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14942. _this.hasReachedQuota = true;
  14943. }
  14944. }
  14945. catch (ex) {
  14946. }
  14947. callback(-1);
  14948. };
  14949. transaction.oncomplete = function (event) {
  14950. callback(_this.manifestVersionFound);
  14951. };
  14952. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14953. // Put the scene into the database
  14954. var addRequest = transaction.objectStore("versions").put(newVersion);
  14955. addRequest.onsuccess = function (event) {
  14956. };
  14957. addRequest.onerror = function (event) {
  14958. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14959. };
  14960. }
  14961. catch (ex) {
  14962. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14963. callback(-1);
  14964. }
  14965. }
  14966. else {
  14967. callback(-1);
  14968. }
  14969. };
  14970. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14971. var _this = this;
  14972. var completeUrl = Database.ReturnFullUrlLocation(url);
  14973. var saveAndLoadFile = function (event) {
  14974. // the scene is not yet in the DB, let's try to save it
  14975. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14976. };
  14977. this._checkVersionFromDB(completeUrl, function (version) {
  14978. if (version !== -1) {
  14979. if (!_this.mustUpdateRessources) {
  14980. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14981. }
  14982. else {
  14983. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14984. }
  14985. }
  14986. else {
  14987. errorCallback();
  14988. }
  14989. });
  14990. };
  14991. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14992. if (this.isSupported) {
  14993. var targetStore;
  14994. if (url.indexOf(".babylon") !== -1) {
  14995. targetStore = "scenes";
  14996. }
  14997. else {
  14998. targetStore = "textures";
  14999. }
  15000. var file;
  15001. var transaction = this.db.transaction([targetStore]);
  15002. transaction.oncomplete = function (event) {
  15003. if (file) {
  15004. callback(file.data);
  15005. }
  15006. else {
  15007. notInDBCallback();
  15008. }
  15009. };
  15010. transaction.onabort = function (event) {
  15011. notInDBCallback();
  15012. };
  15013. var getRequest = transaction.objectStore(targetStore).get(url);
  15014. getRequest.onsuccess = function (event) {
  15015. file = (event.target).result;
  15016. };
  15017. getRequest.onerror = function (event) {
  15018. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15019. notInDBCallback();
  15020. };
  15021. }
  15022. else {
  15023. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15024. callback();
  15025. }
  15026. };
  15027. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15028. var _this = this;
  15029. if (this.isSupported) {
  15030. var targetStore;
  15031. if (url.indexOf(".babylon") !== -1) {
  15032. targetStore = "scenes";
  15033. }
  15034. else {
  15035. targetStore = "textures";
  15036. }
  15037. // Create XHR
  15038. var xhr = new XMLHttpRequest(), fileData;
  15039. xhr.open("GET", url, true);
  15040. if (useArrayBuffer) {
  15041. xhr.responseType = "arraybuffer";
  15042. }
  15043. xhr.onprogress = progressCallback;
  15044. xhr.addEventListener("load", function () {
  15045. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15046. // Blob as response (XHR2)
  15047. //fileData = xhr.responseText;
  15048. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15049. if (!_this.hasReachedQuota) {
  15050. // Open a transaction to the database
  15051. var transaction = _this.db.transaction([targetStore], "readwrite");
  15052. // the transaction could abort because of a QuotaExceededError error
  15053. transaction.onabort = function (event) {
  15054. try {
  15055. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15056. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15057. this.hasReachedQuota = true;
  15058. }
  15059. }
  15060. catch (ex) {
  15061. }
  15062. callback(fileData);
  15063. };
  15064. transaction.oncomplete = function (event) {
  15065. callback(fileData);
  15066. };
  15067. var newFile;
  15068. if (targetStore === "scenes") {
  15069. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15070. }
  15071. else {
  15072. newFile = { textureUrl: url, data: fileData };
  15073. }
  15074. try {
  15075. // Put the scene into the database
  15076. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15077. addRequest.onsuccess = function (event) {
  15078. };
  15079. addRequest.onerror = function (event) {
  15080. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15081. };
  15082. }
  15083. catch (ex) {
  15084. callback(fileData);
  15085. }
  15086. }
  15087. else {
  15088. callback(fileData);
  15089. }
  15090. }
  15091. else {
  15092. callback();
  15093. }
  15094. }, false);
  15095. xhr.addEventListener("error", function (event) {
  15096. BABYLON.Tools.Error("error on XHR request.");
  15097. callback();
  15098. }, false);
  15099. xhr.send();
  15100. }
  15101. else {
  15102. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15103. callback();
  15104. }
  15105. };
  15106. Database.isUASupportingBlobStorage = true;
  15107. Database.parseURL = function (url) {
  15108. var a = document.createElement('a');
  15109. a.href = url;
  15110. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15111. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15112. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15113. return absLocation;
  15114. };
  15115. Database.ReturnFullUrlLocation = function (url) {
  15116. if (url.indexOf("http:/") === -1) {
  15117. return (BABYLON.Database.parseURL(window.location.href) + url);
  15118. }
  15119. else {
  15120. return url;
  15121. }
  15122. };
  15123. return Database;
  15124. })();
  15125. BABYLON.Database = Database;
  15126. })(BABYLON || (BABYLON = {}));
  15127. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15128. (function (BABYLON) {
  15129. var SpriteManager = (function () {
  15130. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15132. this.name = name;
  15133. this.cellSize = cellSize;
  15134. this.sprites = new Array();
  15135. this.renderingGroupId = 0;
  15136. this.fogEnabled = true;
  15137. this._vertexDeclaration = [3, 4, 4, 4];
  15138. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15139. this._capacity = capacity;
  15140. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15141. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15142. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15143. // temp fix for correct 'pixelated' appearance
  15144. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  15145. this._spriteTexture.anisotropicFilteringLevel = 1;
  15146. }
  15147. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15148. this._scene = scene;
  15149. this._scene.spriteManagers.push(this);
  15150. // VBO
  15151. this._vertexDeclaration = [3, 4, 4, 4];
  15152. this._vertexStrideSize = 15 * 4;
  15153. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15154. var indices = [];
  15155. var index = 0;
  15156. for (var count = 0; count < capacity; count++) {
  15157. indices.push(index);
  15158. indices.push(index + 1);
  15159. indices.push(index + 2);
  15160. indices.push(index);
  15161. indices.push(index + 2);
  15162. indices.push(index + 3);
  15163. index += 4;
  15164. }
  15165. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15166. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15167. // Effects
  15168. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15169. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15170. }
  15171. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15172. var arrayOffset = index * 15;
  15173. if (offsetX === 0)
  15174. offsetX = this._epsilon;
  15175. else if (offsetX === 1)
  15176. offsetX = 1 - this._epsilon;
  15177. if (offsetY === 0)
  15178. offsetY = this._epsilon;
  15179. else if (offsetY === 1)
  15180. offsetY = 1 - this._epsilon;
  15181. this._vertices[arrayOffset] = sprite.position.x;
  15182. this._vertices[arrayOffset + 1] = sprite.position.y;
  15183. this._vertices[arrayOffset + 2] = sprite.position.z;
  15184. this._vertices[arrayOffset + 3] = sprite.angle;
  15185. this._vertices[arrayOffset + 4] = sprite.size;
  15186. this._vertices[arrayOffset + 5] = offsetX;
  15187. this._vertices[arrayOffset + 6] = offsetY;
  15188. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15189. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15190. var offset = (sprite.cellIndex / rowSize) >> 0;
  15191. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15192. this._vertices[arrayOffset + 10] = offset;
  15193. // Color
  15194. this._vertices[arrayOffset + 11] = sprite.color.r;
  15195. this._vertices[arrayOffset + 12] = sprite.color.g;
  15196. this._vertices[arrayOffset + 13] = sprite.color.b;
  15197. this._vertices[arrayOffset + 14] = sprite.color.a;
  15198. };
  15199. SpriteManager.prototype.render = function () {
  15200. // Check
  15201. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15202. return;
  15203. var engine = this._scene.getEngine();
  15204. var baseSize = this._spriteTexture.getBaseSize();
  15205. // Sprites
  15206. var deltaTime = engine.getDeltaTime();
  15207. var max = Math.min(this._capacity, this.sprites.length);
  15208. var rowSize = baseSize.width / this.cellSize;
  15209. var offset = 0;
  15210. for (var index = 0; index < max; index++) {
  15211. var sprite = this.sprites[index];
  15212. if (!sprite) {
  15213. continue;
  15214. }
  15215. sprite._animate(deltaTime);
  15216. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15217. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15218. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15219. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15220. }
  15221. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15222. // Render
  15223. var effect = this._effectBase;
  15224. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15225. effect = this._effectFog;
  15226. }
  15227. engine.enableEffect(effect);
  15228. var viewMatrix = this._scene.getViewMatrix();
  15229. effect.setTexture("diffuseSampler", this._spriteTexture);
  15230. effect.setMatrix("view", viewMatrix);
  15231. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15232. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15233. // Fog
  15234. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15235. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15236. effect.setColor3("vFogColor", this._scene.fogColor);
  15237. }
  15238. // VBOs
  15239. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15240. // Draw order
  15241. effect.setBool("alphaTest", true);
  15242. engine.setColorWrite(false);
  15243. engine.draw(true, 0, max * 6);
  15244. engine.setColorWrite(true);
  15245. effect.setBool("alphaTest", false);
  15246. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15247. engine.draw(true, 0, max * 6);
  15248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15249. };
  15250. SpriteManager.prototype.dispose = function () {
  15251. if (this._vertexBuffer) {
  15252. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15253. this._vertexBuffer = null;
  15254. }
  15255. if (this._indexBuffer) {
  15256. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15257. this._indexBuffer = null;
  15258. }
  15259. if (this._spriteTexture) {
  15260. this._spriteTexture.dispose();
  15261. this._spriteTexture = null;
  15262. }
  15263. // Remove from scene
  15264. var index = this._scene.spriteManagers.indexOf(this);
  15265. this._scene.spriteManagers.splice(index, 1);
  15266. // Callback
  15267. if (this.onDispose) {
  15268. this.onDispose();
  15269. }
  15270. };
  15271. return SpriteManager;
  15272. })();
  15273. BABYLON.SpriteManager = SpriteManager;
  15274. })(BABYLON || (BABYLON = {}));
  15275. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15276. (function (BABYLON) {
  15277. var Sprite = (function () {
  15278. function Sprite(name, manager) {
  15279. this.name = name;
  15280. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15281. this.size = 1.0;
  15282. this.angle = 0;
  15283. this.cellIndex = 0;
  15284. this.invertU = 0;
  15285. this.invertV = 0;
  15286. this.animations = new Array();
  15287. this._animationStarted = false;
  15288. this._loopAnimation = false;
  15289. this._fromIndex = 0;
  15290. this._toIndex = 0;
  15291. this._delay = 0;
  15292. this._direction = 1;
  15293. this._frameCount = 0;
  15294. this._time = 0;
  15295. this._manager = manager;
  15296. this._manager.sprites.push(this);
  15297. this.position = BABYLON.Vector3.Zero();
  15298. }
  15299. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15300. this._fromIndex = from;
  15301. this._toIndex = to;
  15302. this._loopAnimation = loop;
  15303. this._delay = delay;
  15304. this._animationStarted = true;
  15305. this._direction = from < to ? 1 : -1;
  15306. this.cellIndex = from;
  15307. this._time = 0;
  15308. };
  15309. Sprite.prototype.stopAnimation = function () {
  15310. this._animationStarted = false;
  15311. };
  15312. Sprite.prototype._animate = function (deltaTime) {
  15313. if (!this._animationStarted)
  15314. return;
  15315. this._time += deltaTime;
  15316. if (this._time > this._delay) {
  15317. this._time = this._time % this._delay;
  15318. this.cellIndex += this._direction;
  15319. if (this.cellIndex == this._toIndex) {
  15320. if (this._loopAnimation) {
  15321. this.cellIndex = this._fromIndex;
  15322. }
  15323. else {
  15324. this._animationStarted = false;
  15325. if (this.disposeWhenFinishedAnimating) {
  15326. this.dispose();
  15327. }
  15328. }
  15329. }
  15330. }
  15331. };
  15332. Sprite.prototype.dispose = function () {
  15333. for (var i = 0; i < this._manager.sprites.length; i++) {
  15334. if (this._manager.sprites[i] == this) {
  15335. this._manager.sprites.splice(i, 1);
  15336. }
  15337. }
  15338. };
  15339. return Sprite;
  15340. })();
  15341. BABYLON.Sprite = Sprite;
  15342. })(BABYLON || (BABYLON = {}));
  15343. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15344. (function (BABYLON) {
  15345. var Layer = (function () {
  15346. function Layer(name, imgUrl, scene, isBackground, color) {
  15347. this.name = name;
  15348. this._vertexDeclaration = [2];
  15349. this._vertexStrideSize = 2 * 4;
  15350. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15351. this.isBackground = isBackground === undefined ? true : isBackground;
  15352. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15353. this._scene = scene;
  15354. this._scene.layers.push(this);
  15355. // VBO
  15356. var vertices = [];
  15357. vertices.push(1, 1);
  15358. vertices.push(-1, 1);
  15359. vertices.push(-1, -1);
  15360. vertices.push(1, -1);
  15361. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15362. // Indices
  15363. var indices = [];
  15364. indices.push(0);
  15365. indices.push(1);
  15366. indices.push(2);
  15367. indices.push(0);
  15368. indices.push(2);
  15369. indices.push(3);
  15370. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15371. // Effects
  15372. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15373. }
  15374. Layer.prototype.render = function () {
  15375. // Check
  15376. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15377. return;
  15378. var engine = this._scene.getEngine();
  15379. // Render
  15380. engine.enableEffect(this._effect);
  15381. engine.setState(false);
  15382. // Texture
  15383. this._effect.setTexture("textureSampler", this.texture);
  15384. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15385. // Color
  15386. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15387. // VBOs
  15388. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15389. // Draw order
  15390. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15391. engine.draw(true, 0, 6);
  15392. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15393. };
  15394. Layer.prototype.dispose = function () {
  15395. if (this._vertexBuffer) {
  15396. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15397. this._vertexBuffer = null;
  15398. }
  15399. if (this._indexBuffer) {
  15400. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15401. this._indexBuffer = null;
  15402. }
  15403. if (this.texture) {
  15404. this.texture.dispose();
  15405. this.texture = null;
  15406. }
  15407. // Remove from scene
  15408. var index = this._scene.layers.indexOf(this);
  15409. this._scene.layers.splice(index, 1);
  15410. // Callback
  15411. if (this.onDispose) {
  15412. this.onDispose();
  15413. }
  15414. };
  15415. return Layer;
  15416. })();
  15417. BABYLON.Layer = Layer;
  15418. })(BABYLON || (BABYLON = {}));
  15419. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15420. (function (BABYLON) {
  15421. var Particle = (function () {
  15422. function Particle() {
  15423. this.position = BABYLON.Vector3.Zero();
  15424. this.direction = BABYLON.Vector3.Zero();
  15425. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15426. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15427. this.lifeTime = 1.0;
  15428. this.age = 0;
  15429. this.size = 0;
  15430. this.angle = 0;
  15431. this.angularSpeed = 0;
  15432. }
  15433. Particle.prototype.copyTo = function (other) {
  15434. other.position.copyFrom(this.position);
  15435. other.direction.copyFrom(this.direction);
  15436. other.color.copyFrom(this.color);
  15437. other.colorStep.copyFrom(this.colorStep);
  15438. other.lifeTime = this.lifeTime;
  15439. other.age = this.age;
  15440. other.size = this.size;
  15441. other.angle = this.angle;
  15442. other.angularSpeed = this.angularSpeed;
  15443. };
  15444. return Particle;
  15445. })();
  15446. BABYLON.Particle = Particle;
  15447. })(BABYLON || (BABYLON = {}));
  15448. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15449. (function (BABYLON) {
  15450. var randomNumber = function (min, max) {
  15451. if (min === max) {
  15452. return (min);
  15453. }
  15454. var random = Math.random();
  15455. return ((random * (max - min)) + min);
  15456. };
  15457. var ParticleSystem = (function () {
  15458. function ParticleSystem(name, capacity, scene, customEffect) {
  15459. var _this = this;
  15460. this.name = name;
  15461. this.renderingGroupId = 0;
  15462. this.emitter = null;
  15463. this.emitRate = 10;
  15464. this.manualEmitCount = -1;
  15465. this.updateSpeed = 0.01;
  15466. this.targetStopDuration = 0;
  15467. this.disposeOnStop = false;
  15468. this.minEmitPower = 1;
  15469. this.maxEmitPower = 1;
  15470. this.minLifeTime = 1;
  15471. this.maxLifeTime = 1;
  15472. this.minSize = 1;
  15473. this.maxSize = 1;
  15474. this.minAngularSpeed = 0;
  15475. this.maxAngularSpeed = 0;
  15476. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15477. this.forceDepthWrite = false;
  15478. this.gravity = BABYLON.Vector3.Zero();
  15479. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15480. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15481. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15482. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15483. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15484. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15485. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15486. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15487. this.particles = new Array();
  15488. this._vertexDeclaration = [3, 4, 4];
  15489. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15490. this._stockParticles = new Array();
  15491. this._newPartsExcess = 0;
  15492. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15493. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15494. this._scaledDirection = BABYLON.Vector3.Zero();
  15495. this._scaledGravity = BABYLON.Vector3.Zero();
  15496. this._currentRenderId = -1;
  15497. this._started = false;
  15498. this._stopped = false;
  15499. this._actualFrame = 0;
  15500. this.id = name;
  15501. this._capacity = capacity;
  15502. this._scene = scene;
  15503. this._customEffect = customEffect;
  15504. scene.particleSystems.push(this);
  15505. // VBO
  15506. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15507. var indices = [];
  15508. var index = 0;
  15509. for (var count = 0; count < capacity; count++) {
  15510. indices.push(index);
  15511. indices.push(index + 1);
  15512. indices.push(index + 2);
  15513. indices.push(index);
  15514. indices.push(index + 2);
  15515. indices.push(index + 3);
  15516. index += 4;
  15517. }
  15518. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15519. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15520. // Default behaviors
  15521. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15522. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15523. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15524. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15525. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15526. };
  15527. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15528. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15529. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15530. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15531. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15532. };
  15533. this.updateFunction = function (particles) {
  15534. for (var index = 0; index < particles.length; index++) {
  15535. var particle = particles[index];
  15536. particle.age += _this._scaledUpdateSpeed;
  15537. if (particle.age >= particle.lifeTime) {
  15538. _this.recycleParticle(particle);
  15539. index--;
  15540. continue;
  15541. }
  15542. else {
  15543. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15544. particle.color.addInPlace(_this._scaledColorStep);
  15545. if (particle.color.a < 0)
  15546. particle.color.a = 0;
  15547. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15548. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15549. particle.position.addInPlace(_this._scaledDirection);
  15550. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15551. particle.direction.addInPlace(_this._scaledGravity);
  15552. }
  15553. }
  15554. };
  15555. }
  15556. ParticleSystem.prototype.recycleParticle = function (particle) {
  15557. var lastParticle = this.particles.pop();
  15558. if (lastParticle !== particle) {
  15559. lastParticle.copyTo(particle);
  15560. this._stockParticles.push(lastParticle);
  15561. }
  15562. };
  15563. ParticleSystem.prototype.getCapacity = function () {
  15564. return this._capacity;
  15565. };
  15566. ParticleSystem.prototype.isAlive = function () {
  15567. return this._alive;
  15568. };
  15569. ParticleSystem.prototype.isStarted = function () {
  15570. return this._started;
  15571. };
  15572. ParticleSystem.prototype.start = function () {
  15573. this._started = true;
  15574. this._stopped = false;
  15575. this._actualFrame = 0;
  15576. };
  15577. ParticleSystem.prototype.stop = function () {
  15578. this._stopped = true;
  15579. };
  15580. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15581. var offset = index * 11;
  15582. this._vertices[offset] = particle.position.x;
  15583. this._vertices[offset + 1] = particle.position.y;
  15584. this._vertices[offset + 2] = particle.position.z;
  15585. this._vertices[offset + 3] = particle.color.r;
  15586. this._vertices[offset + 4] = particle.color.g;
  15587. this._vertices[offset + 5] = particle.color.b;
  15588. this._vertices[offset + 6] = particle.color.a;
  15589. this._vertices[offset + 7] = particle.angle;
  15590. this._vertices[offset + 8] = particle.size;
  15591. this._vertices[offset + 9] = offsetX;
  15592. this._vertices[offset + 10] = offsetY;
  15593. };
  15594. ParticleSystem.prototype._update = function (newParticles) {
  15595. // Update current
  15596. this._alive = this.particles.length > 0;
  15597. this.updateFunction(this.particles);
  15598. // Add new ones
  15599. var worldMatrix;
  15600. if (this.emitter.position) {
  15601. worldMatrix = this.emitter.getWorldMatrix();
  15602. }
  15603. else {
  15604. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15605. }
  15606. for (var index = 0; index < newParticles; index++) {
  15607. if (this.particles.length === this._capacity) {
  15608. break;
  15609. }
  15610. if (this._stockParticles.length !== 0) {
  15611. var particle = this._stockParticles.pop();
  15612. particle.age = 0;
  15613. }
  15614. else {
  15615. particle = new BABYLON.Particle();
  15616. }
  15617. this.particles.push(particle);
  15618. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15619. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15620. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15621. particle.size = randomNumber(this.minSize, this.maxSize);
  15622. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15623. this.startPositionFunction(worldMatrix, particle.position);
  15624. var step = randomNumber(0, 1.0);
  15625. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15626. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15627. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15628. }
  15629. };
  15630. ParticleSystem.prototype._getEffect = function () {
  15631. if (this._customEffect) {
  15632. return this._customEffect;
  15633. }
  15634. ;
  15635. var defines = [];
  15636. if (this._scene.clipPlane) {
  15637. defines.push("#define CLIPPLANE");
  15638. }
  15639. // Effect
  15640. var join = defines.join("\n");
  15641. if (this._cachedDefines !== join) {
  15642. this._cachedDefines = join;
  15643. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15644. }
  15645. return this._effect;
  15646. };
  15647. ParticleSystem.prototype.animate = function () {
  15648. if (!this._started)
  15649. return;
  15650. var effect = this._getEffect();
  15651. // Check
  15652. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15653. return;
  15654. if (this._currentRenderId === this._scene.getRenderId()) {
  15655. return;
  15656. }
  15657. this._currentRenderId = this._scene.getRenderId();
  15658. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15659. // determine the number of particles we need to create
  15660. var emitCout;
  15661. if (this.manualEmitCount > -1) {
  15662. emitCout = this.manualEmitCount;
  15663. this.manualEmitCount = 0;
  15664. }
  15665. else {
  15666. emitCout = this.emitRate;
  15667. }
  15668. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15669. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15670. if (this._newPartsExcess > 1.0) {
  15671. newParticles += this._newPartsExcess >> 0;
  15672. this._newPartsExcess -= this._newPartsExcess >> 0;
  15673. }
  15674. this._alive = false;
  15675. if (!this._stopped) {
  15676. this._actualFrame += this._scaledUpdateSpeed;
  15677. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15678. this.stop();
  15679. }
  15680. else {
  15681. newParticles = 0;
  15682. }
  15683. this._update(newParticles);
  15684. // Stopped?
  15685. if (this._stopped) {
  15686. if (!this._alive) {
  15687. this._started = false;
  15688. if (this.disposeOnStop) {
  15689. this._scene._toBeDisposed.push(this);
  15690. }
  15691. }
  15692. }
  15693. // Update VBO
  15694. var offset = 0;
  15695. for (var index = 0; index < this.particles.length; index++) {
  15696. var particle = this.particles[index];
  15697. this._appendParticleVertex(offset++, particle, 0, 0);
  15698. this._appendParticleVertex(offset++, particle, 1, 0);
  15699. this._appendParticleVertex(offset++, particle, 1, 1);
  15700. this._appendParticleVertex(offset++, particle, 0, 1);
  15701. }
  15702. var engine = this._scene.getEngine();
  15703. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15704. };
  15705. ParticleSystem.prototype.render = function () {
  15706. var effect = this._getEffect();
  15707. // Check
  15708. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15709. return 0;
  15710. var engine = this._scene.getEngine();
  15711. // Render
  15712. engine.enableEffect(effect);
  15713. engine.setState(false);
  15714. var viewMatrix = this._scene.getViewMatrix();
  15715. effect.setTexture("diffuseSampler", this.particleTexture);
  15716. effect.setMatrix("view", viewMatrix);
  15717. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15718. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15719. if (this._scene.clipPlane) {
  15720. var clipPlane = this._scene.clipPlane;
  15721. var invView = viewMatrix.clone();
  15722. invView.invert();
  15723. effect.setMatrix("invView", invView);
  15724. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15725. }
  15726. // VBOs
  15727. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15728. // Draw order
  15729. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15730. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15731. }
  15732. else {
  15733. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15734. }
  15735. if (this.forceDepthWrite) {
  15736. engine.setDepthWrite(true);
  15737. }
  15738. engine.draw(true, 0, this.particles.length * 6);
  15739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15740. return this.particles.length;
  15741. };
  15742. ParticleSystem.prototype.dispose = function () {
  15743. if (this._vertexBuffer) {
  15744. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15745. this._vertexBuffer = null;
  15746. }
  15747. if (this._indexBuffer) {
  15748. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15749. this._indexBuffer = null;
  15750. }
  15751. if (this.particleTexture) {
  15752. this.particleTexture.dispose();
  15753. this.particleTexture = null;
  15754. }
  15755. // Remove from scene
  15756. var index = this._scene.particleSystems.indexOf(this);
  15757. this._scene.particleSystems.splice(index, 1);
  15758. // Callback
  15759. if (this.onDispose) {
  15760. this.onDispose();
  15761. }
  15762. };
  15763. // Clone
  15764. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15765. var result = new ParticleSystem(name, this._capacity, this._scene);
  15766. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15767. if (newEmitter === undefined) {
  15768. newEmitter = this.emitter;
  15769. }
  15770. result.emitter = newEmitter;
  15771. if (this.particleTexture) {
  15772. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15773. }
  15774. result.start();
  15775. return result;
  15776. };
  15777. // Statics
  15778. ParticleSystem.BLENDMODE_ONEONE = 0;
  15779. ParticleSystem.BLENDMODE_STANDARD = 1;
  15780. return ParticleSystem;
  15781. })();
  15782. BABYLON.ParticleSystem = ParticleSystem;
  15783. })(BABYLON || (BABYLON = {}));
  15784. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15785. (function (BABYLON) {
  15786. var Animation = (function () {
  15787. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15788. this.name = name;
  15789. this.targetProperty = targetProperty;
  15790. this.framePerSecond = framePerSecond;
  15791. this.dataType = dataType;
  15792. this.loopMode = loopMode;
  15793. this._offsetsCache = {};
  15794. this._highLimitsCache = {};
  15795. this._stopped = false;
  15796. this.targetPropertyPath = targetProperty.split(".");
  15797. this.dataType = dataType;
  15798. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15799. }
  15800. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15801. var dataType = undefined;
  15802. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15803. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15804. }
  15805. else if (from instanceof BABYLON.Quaternion) {
  15806. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15807. }
  15808. else if (from instanceof BABYLON.Vector3) {
  15809. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15810. }
  15811. else if (from instanceof BABYLON.Vector2) {
  15812. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15813. }
  15814. else if (from instanceof BABYLON.Color3) {
  15815. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15816. }
  15817. if (dataType == undefined) {
  15818. return null;
  15819. }
  15820. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15821. var keys = [];
  15822. keys.push({ frame: 0, value: from });
  15823. keys.push({ frame: totalFrame, value: to });
  15824. animation.setKeys(keys);
  15825. mesh.animations.push(animation);
  15826. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15827. };
  15828. // Methods
  15829. Animation.prototype.isStopped = function () {
  15830. return this._stopped;
  15831. };
  15832. Animation.prototype.getKeys = function () {
  15833. return this._keys;
  15834. };
  15835. Animation.prototype.getEasingFunction = function () {
  15836. return this._easingFunction;
  15837. };
  15838. Animation.prototype.setEasingFunction = function (easingFunction) {
  15839. this._easingFunction = easingFunction;
  15840. };
  15841. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15842. return startValue + (endValue - startValue) * gradient;
  15843. };
  15844. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15845. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15846. };
  15847. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15848. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15849. };
  15850. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15851. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15852. };
  15853. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15854. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15855. };
  15856. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15857. var startScale = new BABYLON.Vector3(0, 0, 0);
  15858. var startRotation = new BABYLON.Quaternion();
  15859. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15860. startValue.decompose(startScale, startRotation, startTranslation);
  15861. var endScale = new BABYLON.Vector3(0, 0, 0);
  15862. var endRotation = new BABYLON.Quaternion();
  15863. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15864. endValue.decompose(endScale, endRotation, endTranslation);
  15865. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15866. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15867. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15868. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15869. return result;
  15870. };
  15871. Animation.prototype.clone = function () {
  15872. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15873. clone.setKeys(this._keys);
  15874. return clone;
  15875. };
  15876. Animation.prototype.setKeys = function (values) {
  15877. this._keys = values.slice(0);
  15878. this._offsetsCache = {};
  15879. this._highLimitsCache = {};
  15880. };
  15881. Animation.prototype._getKeyValue = function (value) {
  15882. if (typeof value === "function") {
  15883. return value();
  15884. }
  15885. return value;
  15886. };
  15887. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15888. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15889. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15890. }
  15891. this.currentFrame = currentFrame;
  15892. for (var key = 0; key < this._keys.length; key++) {
  15893. // for each frame, we need the key just before the frame superior
  15894. if (this._keys[key + 1].frame >= currentFrame) {
  15895. var startValue = this._getKeyValue(this._keys[key].value);
  15896. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15897. // gradient : percent of currentFrame between the frame inf and the frame sup
  15898. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15899. // check for easingFunction and correction of gradient
  15900. if (this._easingFunction != null) {
  15901. gradient = this._easingFunction.ease(gradient);
  15902. }
  15903. switch (this.dataType) {
  15904. case Animation.ANIMATIONTYPE_FLOAT:
  15905. switch (loopMode) {
  15906. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15907. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15908. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15909. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15910. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15911. }
  15912. break;
  15913. case Animation.ANIMATIONTYPE_QUATERNION:
  15914. var quaternion = null;
  15915. switch (loopMode) {
  15916. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15917. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15918. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15919. break;
  15920. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15921. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15922. break;
  15923. }
  15924. return quaternion;
  15925. case Animation.ANIMATIONTYPE_VECTOR3:
  15926. switch (loopMode) {
  15927. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15928. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15929. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15930. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15931. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15932. }
  15933. case Animation.ANIMATIONTYPE_VECTOR2:
  15934. switch (loopMode) {
  15935. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15936. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15937. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15938. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15939. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15940. }
  15941. case Animation.ANIMATIONTYPE_COLOR3:
  15942. switch (loopMode) {
  15943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15945. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15947. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15948. }
  15949. case Animation.ANIMATIONTYPE_MATRIX:
  15950. switch (loopMode) {
  15951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15954. return startValue;
  15955. }
  15956. default:
  15957. break;
  15958. }
  15959. break;
  15960. }
  15961. }
  15962. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15963. };
  15964. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15965. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15966. this._stopped = true;
  15967. return false;
  15968. }
  15969. var returnValue = true;
  15970. // Adding a start key at frame 0 if missing
  15971. if (this._keys[0].frame !== 0) {
  15972. var newKey = { frame: 0, value: this._keys[0].value };
  15973. this._keys.splice(0, 0, newKey);
  15974. }
  15975. // Check limits
  15976. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15977. from = this._keys[0].frame;
  15978. }
  15979. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15980. to = this._keys[this._keys.length - 1].frame;
  15981. }
  15982. // Compute ratio
  15983. var range = to - from;
  15984. var offsetValue;
  15985. // ratio represents the frame delta between from and to
  15986. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15987. var highLimitValue = 0;
  15988. if (ratio > range && !loop) {
  15989. returnValue = false;
  15990. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15991. }
  15992. else {
  15993. // Get max value if required
  15994. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15995. var keyOffset = to.toString() + from.toString();
  15996. if (!this._offsetsCache[keyOffset]) {
  15997. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15998. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15999. switch (this.dataType) {
  16000. case Animation.ANIMATIONTYPE_FLOAT:
  16001. this._offsetsCache[keyOffset] = toValue - fromValue;
  16002. break;
  16003. case Animation.ANIMATIONTYPE_QUATERNION:
  16004. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16005. break;
  16006. case Animation.ANIMATIONTYPE_VECTOR3:
  16007. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16008. case Animation.ANIMATIONTYPE_VECTOR2:
  16009. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16010. case Animation.ANIMATIONTYPE_COLOR3:
  16011. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16012. default:
  16013. break;
  16014. }
  16015. this._highLimitsCache[keyOffset] = toValue;
  16016. }
  16017. highLimitValue = this._highLimitsCache[keyOffset];
  16018. offsetValue = this._offsetsCache[keyOffset];
  16019. }
  16020. }
  16021. if (offsetValue === undefined) {
  16022. switch (this.dataType) {
  16023. case Animation.ANIMATIONTYPE_FLOAT:
  16024. offsetValue = 0;
  16025. break;
  16026. case Animation.ANIMATIONTYPE_QUATERNION:
  16027. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16028. break;
  16029. case Animation.ANIMATIONTYPE_VECTOR3:
  16030. offsetValue = BABYLON.Vector3.Zero();
  16031. break;
  16032. case Animation.ANIMATIONTYPE_VECTOR2:
  16033. offsetValue = BABYLON.Vector2.Zero();
  16034. break;
  16035. case Animation.ANIMATIONTYPE_COLOR3:
  16036. offsetValue = BABYLON.Color3.Black();
  16037. }
  16038. }
  16039. // Compute value
  16040. var repeatCount = (ratio / range) >> 0;
  16041. var currentFrame = returnValue ? from + ratio % range : to;
  16042. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16043. // Set value
  16044. if (this.targetPropertyPath.length > 1) {
  16045. var property = this._target[this.targetPropertyPath[0]];
  16046. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16047. property = property[this.targetPropertyPath[index]];
  16048. }
  16049. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16050. }
  16051. else {
  16052. this._target[this.targetPropertyPath[0]] = currentValue;
  16053. }
  16054. if (this._target.markAsDirty) {
  16055. this._target.markAsDirty(this.targetProperty);
  16056. }
  16057. if (!returnValue) {
  16058. this._stopped = true;
  16059. }
  16060. return returnValue;
  16061. };
  16062. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16063. get: function () {
  16064. return Animation._ANIMATIONTYPE_FLOAT;
  16065. },
  16066. enumerable: true,
  16067. configurable: true
  16068. });
  16069. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16070. get: function () {
  16071. return Animation._ANIMATIONTYPE_VECTOR3;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16077. get: function () {
  16078. return Animation._ANIMATIONTYPE_VECTOR2;
  16079. },
  16080. enumerable: true,
  16081. configurable: true
  16082. });
  16083. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16084. get: function () {
  16085. return Animation._ANIMATIONTYPE_QUATERNION;
  16086. },
  16087. enumerable: true,
  16088. configurable: true
  16089. });
  16090. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16091. get: function () {
  16092. return Animation._ANIMATIONTYPE_MATRIX;
  16093. },
  16094. enumerable: true,
  16095. configurable: true
  16096. });
  16097. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16098. get: function () {
  16099. return Animation._ANIMATIONTYPE_COLOR3;
  16100. },
  16101. enumerable: true,
  16102. configurable: true
  16103. });
  16104. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16105. get: function () {
  16106. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16107. },
  16108. enumerable: true,
  16109. configurable: true
  16110. });
  16111. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16112. get: function () {
  16113. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16119. get: function () {
  16120. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16121. },
  16122. enumerable: true,
  16123. configurable: true
  16124. });
  16125. // Statics
  16126. Animation._ANIMATIONTYPE_FLOAT = 0;
  16127. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16128. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16129. Animation._ANIMATIONTYPE_MATRIX = 3;
  16130. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16131. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16132. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16133. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16134. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16135. return Animation;
  16136. })();
  16137. BABYLON.Animation = Animation;
  16138. })(BABYLON || (BABYLON = {}));
  16139. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16140. (function (BABYLON) {
  16141. var Animatable = (function () {
  16142. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16143. if (fromFrame === void 0) { fromFrame = 0; }
  16144. if (toFrame === void 0) { toFrame = 100; }
  16145. if (loopAnimation === void 0) { loopAnimation = false; }
  16146. if (speedRatio === void 0) { speedRatio = 1.0; }
  16147. this.target = target;
  16148. this.fromFrame = fromFrame;
  16149. this.toFrame = toFrame;
  16150. this.loopAnimation = loopAnimation;
  16151. this.speedRatio = speedRatio;
  16152. this.onAnimationEnd = onAnimationEnd;
  16153. this._animations = new Array();
  16154. this._paused = false;
  16155. this.animationStarted = false;
  16156. if (animations) {
  16157. this.appendAnimations(target, animations);
  16158. }
  16159. this._scene = scene;
  16160. scene._activeAnimatables.push(this);
  16161. }
  16162. // Methods
  16163. Animatable.prototype.appendAnimations = function (target, animations) {
  16164. for (var index = 0; index < animations.length; index++) {
  16165. var animation = animations[index];
  16166. animation._target = target;
  16167. this._animations.push(animation);
  16168. }
  16169. };
  16170. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16171. var animations = this._animations;
  16172. for (var index = 0; index < animations.length; index++) {
  16173. if (animations[index].targetProperty === property) {
  16174. return animations[index];
  16175. }
  16176. }
  16177. return null;
  16178. };
  16179. Animatable.prototype.pause = function () {
  16180. if (this._paused) {
  16181. return;
  16182. }
  16183. this._paused = true;
  16184. };
  16185. Animatable.prototype.restart = function () {
  16186. this._paused = false;
  16187. };
  16188. Animatable.prototype.stop = function () {
  16189. var index = this._scene._activeAnimatables.indexOf(this);
  16190. if (index > -1) {
  16191. this._scene._activeAnimatables.splice(index, 1);
  16192. }
  16193. if (this.onAnimationEnd) {
  16194. this.onAnimationEnd();
  16195. }
  16196. };
  16197. Animatable.prototype._animate = function (delay) {
  16198. if (this._paused) {
  16199. if (!this._pausedDelay) {
  16200. this._pausedDelay = delay;
  16201. }
  16202. return true;
  16203. }
  16204. if (!this._localDelayOffset) {
  16205. this._localDelayOffset = delay;
  16206. }
  16207. else if (this._pausedDelay) {
  16208. this._localDelayOffset += delay - this._pausedDelay;
  16209. this._pausedDelay = null;
  16210. }
  16211. // Animating
  16212. var running = false;
  16213. var animations = this._animations;
  16214. for (var index = 0; index < animations.length; index++) {
  16215. var animation = animations[index];
  16216. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16217. running = running || isRunning;
  16218. }
  16219. if (!running && this.onAnimationEnd) {
  16220. this.onAnimationEnd();
  16221. }
  16222. return running;
  16223. };
  16224. return Animatable;
  16225. })();
  16226. BABYLON.Animatable = Animatable;
  16227. })(BABYLON || (BABYLON = {}));
  16228. //# sourceMappingURL=babylon.animatable.js.map
  16229. var BABYLON;
  16230. (function (BABYLON) {
  16231. var EasingFunction = (function () {
  16232. function EasingFunction() {
  16233. // Properties
  16234. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16235. }
  16236. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16237. get: function () {
  16238. return EasingFunction._EASINGMODE_EASEIN;
  16239. },
  16240. enumerable: true,
  16241. configurable: true
  16242. });
  16243. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16244. get: function () {
  16245. return EasingFunction._EASINGMODE_EASEOUT;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16251. get: function () {
  16252. return EasingFunction._EASINGMODE_EASEINOUT;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16258. var n = Math.min(Math.max(easingMode, 0), 2);
  16259. this._easingMode = n;
  16260. };
  16261. EasingFunction.prototype.getEasingMode = function () {
  16262. return this._easingMode;
  16263. };
  16264. EasingFunction.prototype.easeInCore = function (gradient) {
  16265. throw new Error('You must implement this method');
  16266. };
  16267. EasingFunction.prototype.ease = function (gradient) {
  16268. switch (this._easingMode) {
  16269. case EasingFunction.EASINGMODE_EASEIN:
  16270. return this.easeInCore(gradient);
  16271. case EasingFunction.EASINGMODE_EASEOUT:
  16272. return (1 - this.easeInCore(1 - gradient));
  16273. }
  16274. if (gradient >= 0.5) {
  16275. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16276. }
  16277. return (this.easeInCore(gradient * 2) * 0.5);
  16278. };
  16279. //Statics
  16280. EasingFunction._EASINGMODE_EASEIN = 0;
  16281. EasingFunction._EASINGMODE_EASEOUT = 1;
  16282. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16283. return EasingFunction;
  16284. })();
  16285. BABYLON.EasingFunction = EasingFunction;
  16286. var CircleEase = (function (_super) {
  16287. __extends(CircleEase, _super);
  16288. function CircleEase() {
  16289. _super.apply(this, arguments);
  16290. }
  16291. CircleEase.prototype.easeInCore = function (gradient) {
  16292. gradient = Math.max(0, Math.min(1, gradient));
  16293. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16294. };
  16295. return CircleEase;
  16296. })(EasingFunction);
  16297. BABYLON.CircleEase = CircleEase;
  16298. var BackEase = (function (_super) {
  16299. __extends(BackEase, _super);
  16300. function BackEase(amplitude) {
  16301. if (amplitude === void 0) { amplitude = 1; }
  16302. _super.call(this);
  16303. this.amplitude = amplitude;
  16304. }
  16305. BackEase.prototype.easeInCore = function (gradient) {
  16306. var num = Math.max(0, this.amplitude);
  16307. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16308. };
  16309. return BackEase;
  16310. })(EasingFunction);
  16311. BABYLON.BackEase = BackEase;
  16312. var BounceEase = (function (_super) {
  16313. __extends(BounceEase, _super);
  16314. function BounceEase(bounces, bounciness) {
  16315. if (bounces === void 0) { bounces = 3; }
  16316. if (bounciness === void 0) { bounciness = 2; }
  16317. _super.call(this);
  16318. this.bounces = bounces;
  16319. this.bounciness = bounciness;
  16320. }
  16321. BounceEase.prototype.easeInCore = function (gradient) {
  16322. var y = Math.max(0.0, this.bounces);
  16323. var bounciness = this.bounciness;
  16324. if (bounciness <= 1.0) {
  16325. bounciness = 1.001;
  16326. }
  16327. var num9 = Math.pow(bounciness, y);
  16328. var num5 = 1.0 - bounciness;
  16329. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16330. var num15 = gradient * num4;
  16331. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16332. var num3 = Math.floor(num65);
  16333. var num13 = num3 + 1.0;
  16334. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16335. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16336. var num7 = (num8 + num12) * 0.5;
  16337. var num6 = gradient - num7;
  16338. var num2 = num7 - num8;
  16339. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16340. };
  16341. return BounceEase;
  16342. })(EasingFunction);
  16343. BABYLON.BounceEase = BounceEase;
  16344. var CubicEase = (function (_super) {
  16345. __extends(CubicEase, _super);
  16346. function CubicEase() {
  16347. _super.apply(this, arguments);
  16348. }
  16349. CubicEase.prototype.easeInCore = function (gradient) {
  16350. return (gradient * gradient * gradient);
  16351. };
  16352. return CubicEase;
  16353. })(EasingFunction);
  16354. BABYLON.CubicEase = CubicEase;
  16355. var ElasticEase = (function (_super) {
  16356. __extends(ElasticEase, _super);
  16357. function ElasticEase(oscillations, springiness) {
  16358. if (oscillations === void 0) { oscillations = 3; }
  16359. if (springiness === void 0) { springiness = 3; }
  16360. _super.call(this);
  16361. this.oscillations = oscillations;
  16362. this.springiness = springiness;
  16363. }
  16364. ElasticEase.prototype.easeInCore = function (gradient) {
  16365. var num2;
  16366. var num3 = Math.max(0.0, this.oscillations);
  16367. var num = Math.max(0.0, this.springiness);
  16368. if (num == 0) {
  16369. num2 = gradient;
  16370. }
  16371. else {
  16372. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16373. }
  16374. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16375. };
  16376. return ElasticEase;
  16377. })(EasingFunction);
  16378. BABYLON.ElasticEase = ElasticEase;
  16379. var ExponentialEase = (function (_super) {
  16380. __extends(ExponentialEase, _super);
  16381. function ExponentialEase(exponent) {
  16382. if (exponent === void 0) { exponent = 2; }
  16383. _super.call(this);
  16384. this.exponent = exponent;
  16385. }
  16386. ExponentialEase.prototype.easeInCore = function (gradient) {
  16387. if (this.exponent <= 0) {
  16388. return gradient;
  16389. }
  16390. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16391. };
  16392. return ExponentialEase;
  16393. })(EasingFunction);
  16394. BABYLON.ExponentialEase = ExponentialEase;
  16395. var PowerEase = (function (_super) {
  16396. __extends(PowerEase, _super);
  16397. function PowerEase(power) {
  16398. if (power === void 0) { power = 2; }
  16399. _super.call(this);
  16400. this.power = power;
  16401. }
  16402. PowerEase.prototype.easeInCore = function (gradient) {
  16403. var y = Math.max(0.0, this.power);
  16404. return Math.pow(gradient, y);
  16405. };
  16406. return PowerEase;
  16407. })(EasingFunction);
  16408. BABYLON.PowerEase = PowerEase;
  16409. var QuadraticEase = (function (_super) {
  16410. __extends(QuadraticEase, _super);
  16411. function QuadraticEase() {
  16412. _super.apply(this, arguments);
  16413. }
  16414. QuadraticEase.prototype.easeInCore = function (gradient) {
  16415. return (gradient * gradient);
  16416. };
  16417. return QuadraticEase;
  16418. })(EasingFunction);
  16419. BABYLON.QuadraticEase = QuadraticEase;
  16420. var QuarticEase = (function (_super) {
  16421. __extends(QuarticEase, _super);
  16422. function QuarticEase() {
  16423. _super.apply(this, arguments);
  16424. }
  16425. QuarticEase.prototype.easeInCore = function (gradient) {
  16426. return (gradient * gradient * gradient * gradient);
  16427. };
  16428. return QuarticEase;
  16429. })(EasingFunction);
  16430. BABYLON.QuarticEase = QuarticEase;
  16431. var QuinticEase = (function (_super) {
  16432. __extends(QuinticEase, _super);
  16433. function QuinticEase() {
  16434. _super.apply(this, arguments);
  16435. }
  16436. QuinticEase.prototype.easeInCore = function (gradient) {
  16437. return (gradient * gradient * gradient * gradient * gradient);
  16438. };
  16439. return QuinticEase;
  16440. })(EasingFunction);
  16441. BABYLON.QuinticEase = QuinticEase;
  16442. var SineEase = (function (_super) {
  16443. __extends(SineEase, _super);
  16444. function SineEase() {
  16445. _super.apply(this, arguments);
  16446. }
  16447. SineEase.prototype.easeInCore = function (gradient) {
  16448. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16449. };
  16450. return SineEase;
  16451. })(EasingFunction);
  16452. BABYLON.SineEase = SineEase;
  16453. var BezierCurveEase = (function (_super) {
  16454. __extends(BezierCurveEase, _super);
  16455. function BezierCurveEase(x1, y1, x2, y2) {
  16456. if (x1 === void 0) { x1 = 0; }
  16457. if (y1 === void 0) { y1 = 0; }
  16458. if (x2 === void 0) { x2 = 1; }
  16459. if (y2 === void 0) { y2 = 1; }
  16460. _super.call(this);
  16461. this.x1 = x1;
  16462. this.y1 = y1;
  16463. this.x2 = x2;
  16464. this.y2 = y2;
  16465. }
  16466. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16467. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16468. };
  16469. return BezierCurveEase;
  16470. })(EasingFunction);
  16471. BABYLON.BezierCurveEase = BezierCurveEase;
  16472. })(BABYLON || (BABYLON = {}));
  16473. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16474. (function (BABYLON) {
  16475. var Octree = (function () {
  16476. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16477. if (maxDepth === void 0) { maxDepth = 2; }
  16478. this.maxDepth = maxDepth;
  16479. this.dynamicContent = new Array();
  16480. this._maxBlockCapacity = maxBlockCapacity || 64;
  16481. this._selectionContent = new BABYLON.SmartArray(1024);
  16482. this._creationFunc = creationFunc;
  16483. }
  16484. // Methods
  16485. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16486. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16487. };
  16488. Octree.prototype.addMesh = function (entry) {
  16489. for (var index = 0; index < this.blocks.length; index++) {
  16490. var block = this.blocks[index];
  16491. block.addEntry(entry);
  16492. }
  16493. };
  16494. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16495. this._selectionContent.reset();
  16496. for (var index = 0; index < this.blocks.length; index++) {
  16497. var block = this.blocks[index];
  16498. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16499. }
  16500. if (allowDuplicate) {
  16501. this._selectionContent.concat(this.dynamicContent);
  16502. }
  16503. else {
  16504. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16505. }
  16506. return this._selectionContent;
  16507. };
  16508. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16509. this._selectionContent.reset();
  16510. for (var index = 0; index < this.blocks.length; index++) {
  16511. var block = this.blocks[index];
  16512. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16513. }
  16514. if (allowDuplicate) {
  16515. this._selectionContent.concat(this.dynamicContent);
  16516. }
  16517. else {
  16518. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16519. }
  16520. return this._selectionContent;
  16521. };
  16522. Octree.prototype.intersectsRay = function (ray) {
  16523. this._selectionContent.reset();
  16524. for (var index = 0; index < this.blocks.length; index++) {
  16525. var block = this.blocks[index];
  16526. block.intersectsRay(ray, this._selectionContent);
  16527. }
  16528. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16529. return this._selectionContent;
  16530. };
  16531. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16532. target.blocks = new Array();
  16533. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16534. for (var x = 0; x < 2; x++) {
  16535. for (var y = 0; y < 2; y++) {
  16536. for (var z = 0; z < 2; z++) {
  16537. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16538. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16539. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16540. block.addEntries(entries);
  16541. target.blocks.push(block);
  16542. }
  16543. }
  16544. }
  16545. };
  16546. Octree.CreationFuncForMeshes = function (entry, block) {
  16547. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16548. block.entries.push(entry);
  16549. }
  16550. };
  16551. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16552. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16553. block.entries.push(entry);
  16554. }
  16555. };
  16556. return Octree;
  16557. })();
  16558. BABYLON.Octree = Octree;
  16559. })(BABYLON || (BABYLON = {}));
  16560. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16561. (function (BABYLON) {
  16562. var OctreeBlock = (function () {
  16563. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16564. this.entries = new Array();
  16565. this._boundingVectors = new Array();
  16566. this._capacity = capacity;
  16567. this._depth = depth;
  16568. this._maxDepth = maxDepth;
  16569. this._creationFunc = creationFunc;
  16570. this._minPoint = minPoint;
  16571. this._maxPoint = maxPoint;
  16572. this._boundingVectors.push(minPoint.clone());
  16573. this._boundingVectors.push(maxPoint.clone());
  16574. this._boundingVectors.push(minPoint.clone());
  16575. this._boundingVectors[2].x = maxPoint.x;
  16576. this._boundingVectors.push(minPoint.clone());
  16577. this._boundingVectors[3].y = maxPoint.y;
  16578. this._boundingVectors.push(minPoint.clone());
  16579. this._boundingVectors[4].z = maxPoint.z;
  16580. this._boundingVectors.push(maxPoint.clone());
  16581. this._boundingVectors[5].z = minPoint.z;
  16582. this._boundingVectors.push(maxPoint.clone());
  16583. this._boundingVectors[6].x = minPoint.x;
  16584. this._boundingVectors.push(maxPoint.clone());
  16585. this._boundingVectors[7].y = minPoint.y;
  16586. }
  16587. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16588. // Property
  16589. get: function () {
  16590. return this._capacity;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16596. get: function () {
  16597. return this._minPoint;
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16603. get: function () {
  16604. return this._maxPoint;
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. // Methods
  16610. OctreeBlock.prototype.addEntry = function (entry) {
  16611. if (this.blocks) {
  16612. for (var index = 0; index < this.blocks.length; index++) {
  16613. var block = this.blocks[index];
  16614. block.addEntry(entry);
  16615. }
  16616. return;
  16617. }
  16618. this._creationFunc(entry, this);
  16619. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16620. this.createInnerBlocks();
  16621. }
  16622. };
  16623. OctreeBlock.prototype.addEntries = function (entries) {
  16624. for (var index = 0; index < entries.length; index++) {
  16625. var mesh = entries[index];
  16626. this.addEntry(mesh);
  16627. }
  16628. };
  16629. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16630. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16631. if (this.blocks) {
  16632. for (var index = 0; index < this.blocks.length; index++) {
  16633. var block = this.blocks[index];
  16634. block.select(frustumPlanes, selection, allowDuplicate);
  16635. }
  16636. return;
  16637. }
  16638. if (allowDuplicate) {
  16639. selection.concat(this.entries);
  16640. }
  16641. else {
  16642. selection.concatWithNoDuplicate(this.entries);
  16643. }
  16644. }
  16645. };
  16646. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16647. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16648. if (this.blocks) {
  16649. for (var index = 0; index < this.blocks.length; index++) {
  16650. var block = this.blocks[index];
  16651. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16652. }
  16653. return;
  16654. }
  16655. if (allowDuplicate) {
  16656. selection.concat(this.entries);
  16657. }
  16658. else {
  16659. selection.concatWithNoDuplicate(this.entries);
  16660. }
  16661. }
  16662. };
  16663. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16664. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16665. if (this.blocks) {
  16666. for (var index = 0; index < this.blocks.length; index++) {
  16667. var block = this.blocks[index];
  16668. block.intersectsRay(ray, selection);
  16669. }
  16670. return;
  16671. }
  16672. selection.concatWithNoDuplicate(this.entries);
  16673. }
  16674. };
  16675. OctreeBlock.prototype.createInnerBlocks = function () {
  16676. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16677. };
  16678. return OctreeBlock;
  16679. })();
  16680. BABYLON.OctreeBlock = OctreeBlock;
  16681. })(BABYLON || (BABYLON = {}));
  16682. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16683. (function (BABYLON) {
  16684. var Bone = (function () {
  16685. function Bone(name, skeleton, parentBone, matrix) {
  16686. this.name = name;
  16687. this.children = new Array();
  16688. this.animations = new Array();
  16689. this._worldTransform = new BABYLON.Matrix();
  16690. this._absoluteTransform = new BABYLON.Matrix();
  16691. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16692. this._skeleton = skeleton;
  16693. this._matrix = matrix;
  16694. this._baseMatrix = matrix;
  16695. skeleton.bones.push(this);
  16696. if (parentBone) {
  16697. this._parent = parentBone;
  16698. parentBone.children.push(this);
  16699. }
  16700. else {
  16701. this._parent = null;
  16702. }
  16703. this._updateDifferenceMatrix();
  16704. }
  16705. // Members
  16706. Bone.prototype.getParent = function () {
  16707. return this._parent;
  16708. };
  16709. Bone.prototype.getLocalMatrix = function () {
  16710. return this._matrix;
  16711. };
  16712. Bone.prototype.getBaseMatrix = function () {
  16713. return this._baseMatrix;
  16714. };
  16715. Bone.prototype.getWorldMatrix = function () {
  16716. return this._worldTransform;
  16717. };
  16718. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16719. return this._invertedAbsoluteTransform;
  16720. };
  16721. Bone.prototype.getAbsoluteMatrix = function () {
  16722. var matrix = this._matrix.clone();
  16723. var parent = this._parent;
  16724. while (parent) {
  16725. matrix = matrix.multiply(parent.getLocalMatrix());
  16726. parent = parent.getParent();
  16727. }
  16728. return matrix;
  16729. };
  16730. // Methods
  16731. Bone.prototype.updateMatrix = function (matrix) {
  16732. this._matrix = matrix;
  16733. this._skeleton._markAsDirty();
  16734. this._updateDifferenceMatrix();
  16735. };
  16736. Bone.prototype._updateDifferenceMatrix = function () {
  16737. if (this._parent) {
  16738. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16739. }
  16740. else {
  16741. this._absoluteTransform.copyFrom(this._matrix);
  16742. }
  16743. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16744. for (var index = 0; index < this.children.length; index++) {
  16745. this.children[index]._updateDifferenceMatrix();
  16746. }
  16747. };
  16748. Bone.prototype.markAsDirty = function () {
  16749. this._skeleton._markAsDirty();
  16750. };
  16751. return Bone;
  16752. })();
  16753. BABYLON.Bone = Bone;
  16754. })(BABYLON || (BABYLON = {}));
  16755. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16756. (function (BABYLON) {
  16757. var Skeleton = (function () {
  16758. function Skeleton(name, id, scene) {
  16759. this.name = name;
  16760. this.id = id;
  16761. this.bones = new Array();
  16762. this._isDirty = true;
  16763. this._identity = BABYLON.Matrix.Identity();
  16764. this.bones = [];
  16765. this._scene = scene;
  16766. scene.skeletons.push(this);
  16767. }
  16768. // Members
  16769. Skeleton.prototype.getTransformMatrices = function () {
  16770. return this._transformMatrices;
  16771. };
  16772. // Methods
  16773. Skeleton.prototype._markAsDirty = function () {
  16774. this._isDirty = true;
  16775. };
  16776. Skeleton.prototype.prepare = function () {
  16777. if (!this._isDirty) {
  16778. return;
  16779. }
  16780. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16781. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16782. }
  16783. for (var index = 0; index < this.bones.length; index++) {
  16784. var bone = this.bones[index];
  16785. var parentBone = bone.getParent();
  16786. if (parentBone) {
  16787. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16788. }
  16789. else {
  16790. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16791. }
  16792. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16793. }
  16794. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16795. this._isDirty = false;
  16796. this._scene._activeBones += this.bones.length;
  16797. };
  16798. Skeleton.prototype.getAnimatables = function () {
  16799. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16800. this._animatables = [];
  16801. for (var index = 0; index < this.bones.length; index++) {
  16802. this._animatables.push(this.bones[index]);
  16803. }
  16804. }
  16805. return this._animatables;
  16806. };
  16807. Skeleton.prototype.clone = function (name, id) {
  16808. var result = new Skeleton(name, id || name, this._scene);
  16809. for (var index = 0; index < this.bones.length; index++) {
  16810. var source = this.bones[index];
  16811. var parentBone = null;
  16812. if (source.getParent()) {
  16813. var parentIndex = this.bones.indexOf(source.getParent());
  16814. parentBone = result.bones[parentIndex];
  16815. }
  16816. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16817. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16818. }
  16819. return result;
  16820. };
  16821. return Skeleton;
  16822. })();
  16823. BABYLON.Skeleton = Skeleton;
  16824. })(BABYLON || (BABYLON = {}));
  16825. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16826. (function (BABYLON) {
  16827. var PostProcess = (function () {
  16828. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16830. this.name = name;
  16831. this.width = -1;
  16832. this.height = -1;
  16833. this._reusable = false;
  16834. this._textures = new BABYLON.SmartArray(2);
  16835. this._currentRenderTextureInd = 0;
  16836. if (camera != null) {
  16837. this._camera = camera;
  16838. this._scene = camera.getScene();
  16839. camera.attachPostProcess(this);
  16840. this._engine = this._scene.getEngine();
  16841. }
  16842. else {
  16843. this._engine = engine;
  16844. }
  16845. this._renderRatio = ratio;
  16846. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16847. this._reusable = reusable || false;
  16848. samplers = samplers || [];
  16849. samplers.push("textureSampler");
  16850. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16851. }
  16852. PostProcess.prototype.isReusable = function () {
  16853. return this._reusable;
  16854. };
  16855. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16856. camera = camera || this._camera;
  16857. var scene = camera.getScene();
  16858. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16859. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16860. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16861. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16862. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16863. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16864. if (this._textures.length > 0) {
  16865. for (var i = 0; i < this._textures.length; i++) {
  16866. this._engine._releaseTexture(this._textures.data[i]);
  16867. }
  16868. this._textures.reset();
  16869. }
  16870. this.width = desiredWidth;
  16871. this.height = desiredHeight;
  16872. 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 }));
  16873. if (this._reusable) {
  16874. 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 }));
  16875. }
  16876. if (this.onSizeChanged) {
  16877. this.onSizeChanged();
  16878. }
  16879. }
  16880. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16881. if (this.onActivate) {
  16882. this.onActivate(camera);
  16883. }
  16884. // Clear
  16885. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16886. if (this._reusable) {
  16887. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16888. }
  16889. };
  16890. PostProcess.prototype.apply = function () {
  16891. // Check
  16892. if (!this._effect.isReady())
  16893. return null;
  16894. // States
  16895. this._engine.enableEffect(this._effect);
  16896. this._engine.setState(false);
  16897. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16898. this._engine.setDepthBuffer(false);
  16899. this._engine.setDepthWrite(false);
  16900. // Texture
  16901. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16902. // Parameters
  16903. if (this.onApply) {
  16904. this.onApply(this._effect);
  16905. }
  16906. return this._effect;
  16907. };
  16908. PostProcess.prototype.dispose = function (camera) {
  16909. camera = camera || this._camera;
  16910. if (this._textures.length > 0) {
  16911. for (var i = 0; i < this._textures.length; i++) {
  16912. this._engine._releaseTexture(this._textures.data[i]);
  16913. }
  16914. this._textures.reset();
  16915. }
  16916. if (!camera) {
  16917. return;
  16918. }
  16919. camera.detachPostProcess(this);
  16920. var index = camera._postProcesses.indexOf(this);
  16921. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16922. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16923. }
  16924. };
  16925. return PostProcess;
  16926. })();
  16927. BABYLON.PostProcess = PostProcess;
  16928. })(BABYLON || (BABYLON = {}));
  16929. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16930. (function (BABYLON) {
  16931. var PostProcessManager = (function () {
  16932. function PostProcessManager(scene) {
  16933. this._vertexDeclaration = [2];
  16934. this._vertexStrideSize = 2 * 4;
  16935. this._scene = scene;
  16936. // VBO
  16937. var vertices = [];
  16938. vertices.push(1, 1);
  16939. vertices.push(-1, 1);
  16940. vertices.push(-1, -1);
  16941. vertices.push(1, -1);
  16942. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16943. // Indices
  16944. var indices = [];
  16945. indices.push(0);
  16946. indices.push(1);
  16947. indices.push(2);
  16948. indices.push(0);
  16949. indices.push(2);
  16950. indices.push(3);
  16951. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16952. }
  16953. // Methods
  16954. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16955. var postProcesses = this._scene.activeCamera._postProcesses;
  16956. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16957. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16958. return false;
  16959. }
  16960. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16961. return true;
  16962. };
  16963. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16964. var engine = this._scene.getEngine();
  16965. for (var index = 0; index < postProcesses.length; index++) {
  16966. if (index < postProcesses.length - 1) {
  16967. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16968. }
  16969. else {
  16970. if (targetTexture) {
  16971. engine.bindFramebuffer(targetTexture);
  16972. }
  16973. else {
  16974. engine.restoreDefaultFramebuffer();
  16975. }
  16976. }
  16977. var pp = postProcesses[index];
  16978. var effect = pp.apply();
  16979. if (effect) {
  16980. if (pp.onBeforeRender) {
  16981. pp.onBeforeRender(effect);
  16982. }
  16983. // VBOs
  16984. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16985. // Draw order
  16986. engine.draw(true, 0, 6);
  16987. }
  16988. }
  16989. // Restore depth buffer
  16990. engine.setDepthBuffer(true);
  16991. engine.setDepthWrite(true);
  16992. };
  16993. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  16994. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  16995. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16996. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16997. return;
  16998. }
  16999. var engine = this._scene.getEngine();
  17000. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17001. if (index < postProcessesTakenIndices.length - 1) {
  17002. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17003. }
  17004. else {
  17005. if (targetTexture) {
  17006. engine.bindFramebuffer(targetTexture);
  17007. }
  17008. else {
  17009. engine.restoreDefaultFramebuffer();
  17010. }
  17011. }
  17012. if (doNotPresent) {
  17013. break;
  17014. }
  17015. var pp = postProcesses[postProcessesTakenIndices[index]];
  17016. var effect = pp.apply();
  17017. if (effect) {
  17018. if (pp.onBeforeRender) {
  17019. pp.onBeforeRender(effect);
  17020. }
  17021. // VBOs
  17022. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17023. // Draw order
  17024. engine.draw(true, 0, 6);
  17025. }
  17026. }
  17027. // Restore depth buffer
  17028. engine.setDepthBuffer(true);
  17029. engine.setDepthWrite(true);
  17030. };
  17031. PostProcessManager.prototype.dispose = function () {
  17032. if (this._vertexBuffer) {
  17033. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17034. this._vertexBuffer = null;
  17035. }
  17036. if (this._indexBuffer) {
  17037. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17038. this._indexBuffer = null;
  17039. }
  17040. };
  17041. return PostProcessManager;
  17042. })();
  17043. BABYLON.PostProcessManager = PostProcessManager;
  17044. })(BABYLON || (BABYLON = {}));
  17045. //# sourceMappingURL=babylon.postProcessManager.js.map
  17046. var BABYLON;
  17047. (function (BABYLON) {
  17048. var PassPostProcess = (function (_super) {
  17049. __extends(PassPostProcess, _super);
  17050. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17051. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17052. }
  17053. return PassPostProcess;
  17054. })(BABYLON.PostProcess);
  17055. BABYLON.PassPostProcess = PassPostProcess;
  17056. })(BABYLON || (BABYLON = {}));
  17057. //# sourceMappingURL=babylon.passPostProcess.js.map
  17058. var BABYLON;
  17059. (function (BABYLON) {
  17060. var BlurPostProcess = (function (_super) {
  17061. __extends(BlurPostProcess, _super);
  17062. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17063. var _this = this;
  17064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17065. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17066. this.direction = direction;
  17067. this.blurWidth = blurWidth;
  17068. this.onApply = function (effect) {
  17069. effect.setFloat2("screenSize", _this.width, _this.height);
  17070. effect.setVector2("direction", _this.direction);
  17071. effect.setFloat("blurWidth", _this.blurWidth);
  17072. };
  17073. }
  17074. return BlurPostProcess;
  17075. })(BABYLON.PostProcess);
  17076. BABYLON.BlurPostProcess = BlurPostProcess;
  17077. })(BABYLON || (BABYLON = {}));
  17078. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17079. var BABYLON;
  17080. (function (BABYLON) {
  17081. var FilterPostProcess = (function (_super) {
  17082. __extends(FilterPostProcess, _super);
  17083. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17084. var _this = this;
  17085. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17086. this.kernelMatrix = kernelMatrix;
  17087. this.onApply = function (effect) {
  17088. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17089. };
  17090. }
  17091. return FilterPostProcess;
  17092. })(BABYLON.PostProcess);
  17093. BABYLON.FilterPostProcess = FilterPostProcess;
  17094. })(BABYLON || (BABYLON = {}));
  17095. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17096. var BABYLON;
  17097. (function (BABYLON) {
  17098. var RefractionPostProcess = (function (_super) {
  17099. __extends(RefractionPostProcess, _super);
  17100. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17101. var _this = this;
  17102. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17103. this.color = color;
  17104. this.depth = depth;
  17105. this.colorLevel = colorLevel;
  17106. this.onActivate = function (cam) {
  17107. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17108. };
  17109. this.onApply = function (effect) {
  17110. effect.setColor3("baseColor", _this.color);
  17111. effect.setFloat("depth", _this.depth);
  17112. effect.setFloat("colorLevel", _this.colorLevel);
  17113. effect.setTexture("refractionSampler", _this._refRexture);
  17114. };
  17115. }
  17116. // Methods
  17117. RefractionPostProcess.prototype.dispose = function (camera) {
  17118. if (this._refRexture) {
  17119. this._refRexture.dispose();
  17120. }
  17121. _super.prototype.dispose.call(this, camera);
  17122. };
  17123. return RefractionPostProcess;
  17124. })(BABYLON.PostProcess);
  17125. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17126. })(BABYLON || (BABYLON = {}));
  17127. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17128. var BABYLON;
  17129. (function (BABYLON) {
  17130. var BlackAndWhitePostProcess = (function (_super) {
  17131. __extends(BlackAndWhitePostProcess, _super);
  17132. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17133. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17134. }
  17135. return BlackAndWhitePostProcess;
  17136. })(BABYLON.PostProcess);
  17137. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17138. })(BABYLON || (BABYLON = {}));
  17139. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17140. var BABYLON;
  17141. (function (BABYLON) {
  17142. var ConvolutionPostProcess = (function (_super) {
  17143. __extends(ConvolutionPostProcess, _super);
  17144. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17145. var _this = this;
  17146. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17147. this.kernel = kernel;
  17148. this.onApply = function (effect) {
  17149. effect.setFloat2("screenSize", _this.width, _this.height);
  17150. effect.setArray("kernel", _this.kernel);
  17151. };
  17152. }
  17153. // Statics
  17154. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17155. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17156. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17157. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17158. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17159. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17160. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17161. return ConvolutionPostProcess;
  17162. })(BABYLON.PostProcess);
  17163. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17164. })(BABYLON || (BABYLON = {}));
  17165. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17166. var BABYLON;
  17167. (function (BABYLON) {
  17168. var FxaaPostProcess = (function (_super) {
  17169. __extends(FxaaPostProcess, _super);
  17170. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17171. var _this = this;
  17172. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17173. this.onSizeChanged = function () {
  17174. _this.texelWidth = 1.0 / _this.width;
  17175. _this.texelHeight = 1.0 / _this.height;
  17176. };
  17177. this.onApply = function (effect) {
  17178. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17179. };
  17180. }
  17181. return FxaaPostProcess;
  17182. })(BABYLON.PostProcess);
  17183. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17184. })(BABYLON || (BABYLON = {}));
  17185. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17186. (function (BABYLON) {
  17187. var LensFlare = (function () {
  17188. function LensFlare(size, position, color, imgUrl, system) {
  17189. this.size = size;
  17190. this.position = position;
  17191. this.dispose = function () {
  17192. if (this.texture) {
  17193. this.texture.dispose();
  17194. }
  17195. // Remove from scene
  17196. var index = this._system.lensFlares.indexOf(this);
  17197. this._system.lensFlares.splice(index, 1);
  17198. };
  17199. this.color = color || new BABYLON.Color3(1, 1, 1);
  17200. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17201. this._system = system;
  17202. system.lensFlares.push(this);
  17203. }
  17204. return LensFlare;
  17205. })();
  17206. BABYLON.LensFlare = LensFlare;
  17207. })(BABYLON || (BABYLON = {}));
  17208. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17209. (function (BABYLON) {
  17210. var LensFlareSystem = (function () {
  17211. function LensFlareSystem(name, emitter, scene) {
  17212. this.name = name;
  17213. this.lensFlares = new Array();
  17214. this.borderLimit = 300;
  17215. this._vertexDeclaration = [2];
  17216. this._vertexStrideSize = 2 * 4;
  17217. this._isEnabled = true;
  17218. this._scene = scene;
  17219. this._emitter = emitter;
  17220. scene.lensFlareSystems.push(this);
  17221. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17222. // VBO
  17223. var vertices = [];
  17224. vertices.push(1, 1);
  17225. vertices.push(-1, 1);
  17226. vertices.push(-1, -1);
  17227. vertices.push(1, -1);
  17228. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17229. // Indices
  17230. var indices = [];
  17231. indices.push(0);
  17232. indices.push(1);
  17233. indices.push(2);
  17234. indices.push(0);
  17235. indices.push(2);
  17236. indices.push(3);
  17237. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17238. // Effects
  17239. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17240. }
  17241. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17242. get: function () {
  17243. return this._isEnabled;
  17244. },
  17245. set: function (value) {
  17246. this._isEnabled = value;
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. LensFlareSystem.prototype.getScene = function () {
  17252. return this._scene;
  17253. };
  17254. LensFlareSystem.prototype.getEmitter = function () {
  17255. return this._emitter;
  17256. };
  17257. LensFlareSystem.prototype.getEmitterPosition = function () {
  17258. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17259. };
  17260. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17261. var position = this.getEmitterPosition();
  17262. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17263. this._positionX = position.x;
  17264. this._positionY = position.y;
  17265. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17266. if (position.z > 0) {
  17267. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17268. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17269. return true;
  17270. }
  17271. }
  17272. return false;
  17273. };
  17274. LensFlareSystem.prototype._isVisible = function () {
  17275. if (!this._isEnabled) {
  17276. return false;
  17277. }
  17278. var emitterPosition = this.getEmitterPosition();
  17279. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17280. var distance = direction.length();
  17281. direction.normalize();
  17282. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17283. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17284. return !pickInfo.hit || pickInfo.distance > distance;
  17285. };
  17286. LensFlareSystem.prototype.render = function () {
  17287. if (!this._effect.isReady())
  17288. return false;
  17289. var engine = this._scene.getEngine();
  17290. var viewport = this._scene.activeCamera.viewport;
  17291. var globalViewport = viewport.toGlobal(engine);
  17292. // Position
  17293. if (!this.computeEffectivePosition(globalViewport)) {
  17294. return false;
  17295. }
  17296. // Visibility
  17297. if (!this._isVisible()) {
  17298. return false;
  17299. }
  17300. // Intensity
  17301. var awayX;
  17302. var awayY;
  17303. if (this._positionX < this.borderLimit + globalViewport.x) {
  17304. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17305. }
  17306. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17307. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17308. }
  17309. else {
  17310. awayX = 0;
  17311. }
  17312. if (this._positionY < this.borderLimit + globalViewport.y) {
  17313. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17314. }
  17315. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17316. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17317. }
  17318. else {
  17319. awayY = 0;
  17320. }
  17321. var away = (awayX > awayY) ? awayX : awayY;
  17322. if (away > this.borderLimit) {
  17323. away = this.borderLimit;
  17324. }
  17325. var intensity = 1.0 - (away / this.borderLimit);
  17326. if (intensity < 0) {
  17327. return false;
  17328. }
  17329. if (intensity > 1.0) {
  17330. intensity = 1.0;
  17331. }
  17332. // Position
  17333. var centerX = globalViewport.x + globalViewport.width / 2;
  17334. var centerY = globalViewport.y + globalViewport.height / 2;
  17335. var distX = centerX - this._positionX;
  17336. var distY = centerY - this._positionY;
  17337. // Effects
  17338. engine.enableEffect(this._effect);
  17339. engine.setState(false);
  17340. engine.setDepthBuffer(false);
  17341. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17342. // VBOs
  17343. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17344. for (var index = 0; index < this.lensFlares.length; index++) {
  17345. var flare = this.lensFlares[index];
  17346. var x = centerX - (distX * flare.position);
  17347. var y = centerY - (distY * flare.position);
  17348. var cw = flare.size;
  17349. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17350. var cx = 2 * (x / globalViewport.width) - 1.0;
  17351. var cy = 1.0 - 2 * (y / globalViewport.height);
  17352. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17353. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17354. // Texture
  17355. this._effect.setTexture("textureSampler", flare.texture);
  17356. // Color
  17357. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17358. // Draw order
  17359. engine.draw(true, 0, 6);
  17360. }
  17361. engine.setDepthBuffer(true);
  17362. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17363. return true;
  17364. };
  17365. LensFlareSystem.prototype.dispose = function () {
  17366. if (this._vertexBuffer) {
  17367. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17368. this._vertexBuffer = null;
  17369. }
  17370. if (this._indexBuffer) {
  17371. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17372. this._indexBuffer = null;
  17373. }
  17374. while (this.lensFlares.length) {
  17375. this.lensFlares[0].dispose();
  17376. }
  17377. // Remove from scene
  17378. var index = this._scene.lensFlareSystems.indexOf(this);
  17379. this._scene.lensFlareSystems.splice(index, 1);
  17380. };
  17381. return LensFlareSystem;
  17382. })();
  17383. BABYLON.LensFlareSystem = LensFlareSystem;
  17384. })(BABYLON || (BABYLON = {}));
  17385. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17386. (function (BABYLON) {
  17387. var IntersectionInfo = (function () {
  17388. function IntersectionInfo(bu, bv, distance) {
  17389. this.bu = bu;
  17390. this.bv = bv;
  17391. this.distance = distance;
  17392. this.faceId = 0;
  17393. this.subMeshId = 0;
  17394. }
  17395. return IntersectionInfo;
  17396. })();
  17397. BABYLON.IntersectionInfo = IntersectionInfo;
  17398. var PickingInfo = (function () {
  17399. function PickingInfo() {
  17400. this.hit = false;
  17401. this.distance = 0;
  17402. this.pickedPoint = null;
  17403. this.pickedMesh = null;
  17404. this.bu = 0;
  17405. this.bv = 0;
  17406. this.faceId = -1;
  17407. this.subMeshId = 0;
  17408. }
  17409. // Methods
  17410. PickingInfo.prototype.getNormal = function () {
  17411. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17412. return null;
  17413. }
  17414. var indices = this.pickedMesh.getIndices();
  17415. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17416. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17417. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17418. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17419. normal0 = normal0.scale(this.bu);
  17420. normal1 = normal1.scale(this.bv);
  17421. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17422. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17423. };
  17424. PickingInfo.prototype.getTextureCoordinates = function () {
  17425. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17426. return null;
  17427. }
  17428. var indices = this.pickedMesh.getIndices();
  17429. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17430. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17431. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17432. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17433. uv0 = uv0.scale(this.bu);
  17434. uv1 = uv1.scale(this.bv);
  17435. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17436. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17437. };
  17438. return PickingInfo;
  17439. })();
  17440. BABYLON.PickingInfo = PickingInfo;
  17441. })(BABYLON || (BABYLON = {}));
  17442. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17443. (function (BABYLON) {
  17444. var FilesInput = (function () {
  17445. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17446. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17447. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17448. this._engine = p_engine;
  17449. this._canvas = p_canvas;
  17450. this._currentScene = p_scene;
  17451. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17452. this._progressCallback = p_progressCallback;
  17453. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17454. this._textureLoadingCallback = p_textureLoadingCallback;
  17455. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17456. }
  17457. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17458. var _this = this;
  17459. if (p_elementToMonitor) {
  17460. this._elementToMonitor = p_elementToMonitor;
  17461. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17462. _this.drag(e);
  17463. }, false);
  17464. this._elementToMonitor.addEventListener("dragover", function (e) {
  17465. _this.drag(e);
  17466. }, false);
  17467. this._elementToMonitor.addEventListener("drop", function (e) {
  17468. _this.drop(e);
  17469. }, false);
  17470. }
  17471. };
  17472. FilesInput.prototype.renderFunction = function () {
  17473. if (this._additionnalRenderLoopLogicCallback) {
  17474. this._additionnalRenderLoopLogicCallback();
  17475. }
  17476. if (this._currentScene) {
  17477. if (this._textureLoadingCallback) {
  17478. var remaining = this._currentScene.getWaitingItemsCount();
  17479. if (remaining > 0) {
  17480. this._textureLoadingCallback(remaining);
  17481. }
  17482. }
  17483. this._currentScene.render();
  17484. }
  17485. };
  17486. FilesInput.prototype.drag = function (e) {
  17487. e.stopPropagation();
  17488. e.preventDefault();
  17489. };
  17490. FilesInput.prototype.drop = function (eventDrop) {
  17491. eventDrop.stopPropagation();
  17492. eventDrop.preventDefault();
  17493. this.loadFiles(eventDrop);
  17494. };
  17495. FilesInput.prototype.loadFiles = function (event) {
  17496. if (this._startingProcessingFilesCallback)
  17497. this._startingProcessingFilesCallback();
  17498. // Handling data transfer via drag'n'drop
  17499. if (event && event.dataTransfer && event.dataTransfer.files) {
  17500. this._filesToLoad = event.dataTransfer.files;
  17501. }
  17502. // Handling files from input files
  17503. if (event && event.target && event.target.files) {
  17504. this._filesToLoad = event.target.files;
  17505. }
  17506. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17507. for (var i = 0; i < this._filesToLoad.length; i++) {
  17508. switch (this._filesToLoad[i].type) {
  17509. case "image/jpeg":
  17510. case "image/png":
  17511. case "image/bmp":
  17512. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17513. break;
  17514. case "image/targa":
  17515. case "image/vnd.ms-dds":
  17516. case "audio/wav":
  17517. case "audio/x-wav":
  17518. case "audio/mp3":
  17519. case "audio/mpeg":
  17520. case "audio/mpeg3":
  17521. case "audio/x-mpeg-3":
  17522. case "audio/ogg":
  17523. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17524. break;
  17525. default:
  17526. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17527. this._sceneFileToLoad = this._filesToLoad[i];
  17528. }
  17529. break;
  17530. }
  17531. }
  17532. this.reload();
  17533. }
  17534. };
  17535. FilesInput.prototype.reload = function () {
  17536. var _this = this;
  17537. var that = this;
  17538. // If a ".babylon" file has been provided
  17539. if (this._sceneFileToLoad) {
  17540. if (this._currentScene) {
  17541. this._engine.stopRenderLoop();
  17542. this._currentScene.dispose();
  17543. }
  17544. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17545. that._currentScene = newScene;
  17546. // Wait for textures and shaders to be ready
  17547. that._currentScene.executeWhenReady(function () {
  17548. // Attach camera to canvas inputs
  17549. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17550. that._currentScene.createDefaultCameraOrLight();
  17551. }
  17552. that._currentScene.activeCamera.attachControl(that._canvas);
  17553. if (that._sceneLoadedCallback) {
  17554. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17555. }
  17556. that._engine.runRenderLoop(function () {
  17557. that.renderFunction();
  17558. });
  17559. });
  17560. }, function (progress) {
  17561. if (_this._progressCallback) {
  17562. _this._progressCallback(progress);
  17563. }
  17564. });
  17565. }
  17566. else {
  17567. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17568. }
  17569. };
  17570. FilesInput.FilesTextures = new Array();
  17571. FilesInput.FilesToLoad = new Array();
  17572. return FilesInput;
  17573. })();
  17574. BABYLON.FilesInput = FilesInput;
  17575. })(BABYLON || (BABYLON = {}));
  17576. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17577. (function (BABYLON) {
  17578. var OimoJSPlugin = (function () {
  17579. function OimoJSPlugin() {
  17580. this._registeredMeshes = [];
  17581. /**
  17582. * Update the body position according to the mesh position
  17583. * @param mesh
  17584. */
  17585. this.updateBodyPosition = function (mesh) {
  17586. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17587. var registeredMesh = this._registeredMeshes[index];
  17588. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17589. var body = registeredMesh.body.body;
  17590. mesh.computeWorldMatrix(true);
  17591. var center = mesh.getBoundingInfo().boundingBox.center;
  17592. body.setPosition(center.x, center.y, center.z);
  17593. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17594. return;
  17595. }
  17596. // Case where the parent has been updated
  17597. if (registeredMesh.mesh.parent === mesh) {
  17598. mesh.computeWorldMatrix(true);
  17599. registeredMesh.mesh.computeWorldMatrix(true);
  17600. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17601. var absoluteRotation = mesh.rotation;
  17602. body = registeredMesh.body.body;
  17603. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17604. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17605. return;
  17606. }
  17607. }
  17608. };
  17609. }
  17610. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17611. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17612. };
  17613. OimoJSPlugin.prototype.initialize = function (iterations) {
  17614. this._world = new OIMO.World();
  17615. this._world.clear();
  17616. };
  17617. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17618. this._world.gravity = gravity;
  17619. };
  17620. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17621. var body = null;
  17622. this.unregisterMesh(mesh);
  17623. mesh.computeWorldMatrix(true);
  17624. var initialRotation = null;
  17625. if (mesh.rotationQuaternion) {
  17626. initialRotation = mesh.rotationQuaternion.clone();
  17627. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17628. mesh.computeWorldMatrix(true);
  17629. }
  17630. var bbox = mesh.getBoundingInfo().boundingBox;
  17631. // The delta between the mesh position and the mesh bounding box center
  17632. var deltaPosition = mesh.position.subtract(bbox.center);
  17633. // Transform delta position with the rotation
  17634. if (initialRotation) {
  17635. var m = new BABYLON.Matrix();
  17636. initialRotation.toRotationMatrix(m);
  17637. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17638. }
  17639. switch (impostor) {
  17640. case BABYLON.PhysicsEngine.SphereImpostor:
  17641. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17642. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17643. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17644. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17645. body = new OIMO.Body({
  17646. type: 'sphere',
  17647. size: [size],
  17648. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17649. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17650. move: options.mass != 0,
  17651. config: [options.mass, options.friction, options.restitution],
  17652. world: this._world
  17653. });
  17654. break;
  17655. case BABYLON.PhysicsEngine.PlaneImpostor:
  17656. case BABYLON.PhysicsEngine.CylinderImpostor:
  17657. case BABYLON.PhysicsEngine.BoxImpostor:
  17658. var min = bbox.minimumWorld;
  17659. var max = bbox.maximumWorld;
  17660. var box = max.subtract(min);
  17661. var sizeX = this._checkWithEpsilon(box.x);
  17662. var sizeY = this._checkWithEpsilon(box.y);
  17663. var sizeZ = this._checkWithEpsilon(box.z);
  17664. body = new OIMO.Body({
  17665. type: 'box',
  17666. size: [sizeX, sizeY, sizeZ],
  17667. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17668. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17669. move: options.mass != 0,
  17670. config: [options.mass, options.friction, options.restitution],
  17671. world: this._world
  17672. });
  17673. break;
  17674. }
  17675. //If quaternion was set as the rotation of the object
  17676. if (initialRotation) {
  17677. //We have to access the rigid body's properties to set the quaternion.
  17678. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17679. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17680. //update the internal rotation matrix
  17681. body.body.syncShapes();
  17682. }
  17683. this._registeredMeshes.push({
  17684. mesh: mesh,
  17685. body: body,
  17686. delta: deltaPosition
  17687. });
  17688. return body;
  17689. };
  17690. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17691. var types = [], sizes = [], positions = [], rotations = [];
  17692. var initialMesh = parts[0].mesh;
  17693. for (var index = 0; index < parts.length; index++) {
  17694. var part = parts[index];
  17695. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17696. types.push(bodyParameters.type);
  17697. sizes.push.apply(sizes, bodyParameters.size);
  17698. positions.push.apply(positions, bodyParameters.pos);
  17699. rotations.push.apply(rotations, bodyParameters.rot);
  17700. }
  17701. var body = new OIMO.Body({
  17702. type: types,
  17703. size: sizes,
  17704. pos: positions,
  17705. rot: rotations,
  17706. move: options.mass != 0,
  17707. config: [options.mass, options.friction, options.restitution],
  17708. world: this._world
  17709. });
  17710. this._registeredMeshes.push({
  17711. mesh: initialMesh,
  17712. body: body
  17713. });
  17714. return body;
  17715. };
  17716. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17717. var bodyParameters = null;
  17718. var mesh = part.mesh;
  17719. // We need the bounding box/sphere info to compute the physics body
  17720. mesh.computeWorldMatrix();
  17721. switch (part.impostor) {
  17722. case BABYLON.PhysicsEngine.SphereImpostor:
  17723. var bbox = mesh.getBoundingInfo().boundingBox;
  17724. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17725. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17726. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17727. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17728. bodyParameters = {
  17729. type: 'sphere',
  17730. /* bug with oimo : sphere needs 3 sizes in this case */
  17731. size: [size, -1, -1],
  17732. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17733. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17734. };
  17735. break;
  17736. case BABYLON.PhysicsEngine.PlaneImpostor:
  17737. case BABYLON.PhysicsEngine.BoxImpostor:
  17738. bbox = mesh.getBoundingInfo().boundingBox;
  17739. var min = bbox.minimumWorld;
  17740. var max = bbox.maximumWorld;
  17741. var box = max.subtract(min);
  17742. var sizeX = this._checkWithEpsilon(box.x);
  17743. var sizeY = this._checkWithEpsilon(box.y);
  17744. var sizeZ = this._checkWithEpsilon(box.z);
  17745. var relativePosition = mesh.position;
  17746. bodyParameters = {
  17747. type: 'box',
  17748. size: [sizeX, sizeY, sizeZ],
  17749. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17750. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17751. };
  17752. break;
  17753. }
  17754. return bodyParameters;
  17755. };
  17756. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17757. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17758. var registeredMesh = this._registeredMeshes[index];
  17759. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17760. if (registeredMesh.body) {
  17761. this._world.removeRigidBody(registeredMesh.body.body);
  17762. this._unbindBody(registeredMesh.body);
  17763. }
  17764. this._registeredMeshes.splice(index, 1);
  17765. return;
  17766. }
  17767. }
  17768. };
  17769. OimoJSPlugin.prototype._unbindBody = function (body) {
  17770. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17771. var registeredMesh = this._registeredMeshes[index];
  17772. if (registeredMesh.body === body) {
  17773. registeredMesh.body = null;
  17774. }
  17775. }
  17776. };
  17777. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17778. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17779. var registeredMesh = this._registeredMeshes[index];
  17780. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17781. // Get object mass to have a behaviour similar to cannon.js
  17782. var mass = registeredMesh.body.body.massInfo.mass;
  17783. // The force is scaled with the mass of object
  17784. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17785. return;
  17786. }
  17787. }
  17788. };
  17789. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17790. var body1 = null, body2 = null;
  17791. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17792. var registeredMesh = this._registeredMeshes[index];
  17793. if (registeredMesh.mesh === mesh1) {
  17794. body1 = registeredMesh.body.body;
  17795. }
  17796. else if (registeredMesh.mesh === mesh2) {
  17797. body2 = registeredMesh.body.body;
  17798. }
  17799. }
  17800. if (!body1 || !body2) {
  17801. return false;
  17802. }
  17803. if (!options) {
  17804. options = {};
  17805. }
  17806. new OIMO.Link({
  17807. type: options.type,
  17808. body1: body1,
  17809. body2: body2,
  17810. min: options.min,
  17811. max: options.max,
  17812. axe1: options.axe1,
  17813. axe2: options.axe2,
  17814. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17815. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17816. collision: options.collision,
  17817. spring: options.spring,
  17818. world: this._world
  17819. });
  17820. return true;
  17821. };
  17822. OimoJSPlugin.prototype.dispose = function () {
  17823. this._world.clear();
  17824. while (this._registeredMeshes.length) {
  17825. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17826. }
  17827. };
  17828. OimoJSPlugin.prototype.isSupported = function () {
  17829. return OIMO !== undefined;
  17830. };
  17831. OimoJSPlugin.prototype._getLastShape = function (body) {
  17832. var lastShape = body.shapes;
  17833. while (lastShape.next) {
  17834. lastShape = lastShape.next;
  17835. }
  17836. return lastShape;
  17837. };
  17838. OimoJSPlugin.prototype.runOneStep = function (time) {
  17839. this._world.step();
  17840. // Update the position of all registered meshes
  17841. var i = this._registeredMeshes.length;
  17842. var m;
  17843. while (i--) {
  17844. var body = this._registeredMeshes[i].body.body;
  17845. var mesh = this._registeredMeshes[i].mesh;
  17846. var delta = this._registeredMeshes[i].delta;
  17847. if (!body.sleeping) {
  17848. if (body.shapes.next) {
  17849. var parentShape = this._getLastShape(body);
  17850. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17851. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17852. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17853. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17854. if (!mesh.rotationQuaternion) {
  17855. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17856. }
  17857. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17858. mesh.computeWorldMatrix();
  17859. }
  17860. else {
  17861. m = body.getMatrix();
  17862. mtx = BABYLON.Matrix.FromArray(m);
  17863. // Body position
  17864. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17865. if (!delta) {
  17866. mesh.position.x = bodyX;
  17867. mesh.position.y = bodyY;
  17868. mesh.position.z = bodyZ;
  17869. }
  17870. else {
  17871. mesh.position.x = bodyX + delta.x;
  17872. mesh.position.y = bodyY + delta.y;
  17873. mesh.position.z = bodyZ + delta.z;
  17874. }
  17875. if (!mesh.rotationQuaternion) {
  17876. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17877. }
  17878. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17879. mesh.computeWorldMatrix();
  17880. }
  17881. }
  17882. }
  17883. };
  17884. return OimoJSPlugin;
  17885. })();
  17886. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17887. })(BABYLON || (BABYLON = {}));
  17888. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17889. (function (BABYLON) {
  17890. var PhysicsEngine = (function () {
  17891. function PhysicsEngine(plugin) {
  17892. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17893. }
  17894. PhysicsEngine.prototype._initialize = function (gravity) {
  17895. this._currentPlugin.initialize();
  17896. this._setGravity(gravity);
  17897. };
  17898. PhysicsEngine.prototype._runOneStep = function (delta) {
  17899. if (delta > 0.1) {
  17900. delta = 0.1;
  17901. }
  17902. else if (delta <= 0) {
  17903. delta = 1.0 / 60.0;
  17904. }
  17905. this._currentPlugin.runOneStep(delta);
  17906. };
  17907. PhysicsEngine.prototype._setGravity = function (gravity) {
  17908. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17909. this._currentPlugin.setGravity(this.gravity);
  17910. };
  17911. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17912. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17913. };
  17914. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17915. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17916. };
  17917. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17918. this._currentPlugin.unregisterMesh(mesh);
  17919. };
  17920. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17921. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17922. };
  17923. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17924. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17925. };
  17926. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17927. this._currentPlugin.updateBodyPosition(mesh);
  17928. };
  17929. PhysicsEngine.prototype.dispose = function () {
  17930. this._currentPlugin.dispose();
  17931. };
  17932. PhysicsEngine.prototype.isSupported = function () {
  17933. return this._currentPlugin.isSupported();
  17934. };
  17935. // Statics
  17936. PhysicsEngine.NoImpostor = 0;
  17937. PhysicsEngine.SphereImpostor = 1;
  17938. PhysicsEngine.BoxImpostor = 2;
  17939. PhysicsEngine.PlaneImpostor = 3;
  17940. PhysicsEngine.MeshImpostor = 4;
  17941. PhysicsEngine.CapsuleImpostor = 5;
  17942. PhysicsEngine.ConeImpostor = 6;
  17943. PhysicsEngine.CylinderImpostor = 7;
  17944. PhysicsEngine.ConvexHullImpostor = 8;
  17945. PhysicsEngine.Epsilon = 0.001;
  17946. return PhysicsEngine;
  17947. })();
  17948. BABYLON.PhysicsEngine = PhysicsEngine;
  17949. })(BABYLON || (BABYLON = {}));
  17950. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17951. (function (BABYLON) {
  17952. var serializeLight = function (light) {
  17953. var serializationObject = {};
  17954. serializationObject.name = light.name;
  17955. serializationObject.id = light.id;
  17956. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17957. if (light instanceof BABYLON.PointLight) {
  17958. serializationObject.type = 0;
  17959. serializationObject.position = light.position.asArray();
  17960. }
  17961. else if (light instanceof BABYLON.DirectionalLight) {
  17962. serializationObject.type = 1;
  17963. var directionalLight = light;
  17964. serializationObject.position = directionalLight.position.asArray();
  17965. serializationObject.direction = directionalLight.direction.asArray();
  17966. }
  17967. else if (light instanceof BABYLON.SpotLight) {
  17968. serializationObject.type = 2;
  17969. var spotLight = light;
  17970. serializationObject.position = spotLight.position.asArray();
  17971. serializationObject.direction = spotLight.position.asArray();
  17972. serializationObject.angle = spotLight.angle;
  17973. serializationObject.exponent = spotLight.exponent;
  17974. }
  17975. else if (light instanceof BABYLON.HemisphericLight) {
  17976. serializationObject.type = 3;
  17977. var hemisphericLight = light;
  17978. serializationObject.direction = hemisphericLight.direction.asArray();
  17979. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17980. }
  17981. if (light.intensity) {
  17982. serializationObject.intensity = light.intensity;
  17983. }
  17984. serializationObject.range = light.range;
  17985. serializationObject.diffuse = light.diffuse.asArray();
  17986. serializationObject.specular = light.specular.asArray();
  17987. return serializationObject;
  17988. };
  17989. var serializeFresnelParameter = function (fresnelParameter) {
  17990. var serializationObject = {};
  17991. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17992. serializationObject.leftColor = fresnelParameter.leftColor;
  17993. serializationObject.rightColor = fresnelParameter.rightColor;
  17994. serializationObject.bias = fresnelParameter.bias;
  17995. serializationObject.power = fresnelParameter.power;
  17996. return serializationObject;
  17997. };
  17998. var serializeCamera = function (camera) {
  17999. var serializationObject = {};
  18000. serializationObject.name = camera.name;
  18001. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18002. serializationObject.id = camera.id;
  18003. serializationObject.position = camera.position.asArray();
  18004. // Parent
  18005. if (camera.parent) {
  18006. serializationObject.parentId = camera.parent.id;
  18007. }
  18008. serializationObject.fov = camera.fov;
  18009. serializationObject.minZ = camera.minZ;
  18010. serializationObject.maxZ = camera.maxZ;
  18011. serializationObject.inertia = camera.inertia;
  18012. //setting the type
  18013. if (camera instanceof BABYLON.FreeCamera) {
  18014. serializationObject.type = "FreeCamera";
  18015. }
  18016. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18017. serializationObject.type = "ArcRotateCamera";
  18018. }
  18019. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18020. serializationObject.type = "AnaglyphArcRotateCamera";
  18021. }
  18022. else if (camera instanceof BABYLON.GamepadCamera) {
  18023. serializationObject.type = "GamepadCamera";
  18024. }
  18025. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18026. serializationObject.type = "AnaglyphFreeCamera";
  18027. }
  18028. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18029. serializationObject.type = "DeviceOrientationCamera";
  18030. }
  18031. else if (camera instanceof BABYLON.FollowCamera) {
  18032. serializationObject.type = "FollowCamera";
  18033. }
  18034. else if (camera instanceof BABYLON.OculusCamera) {
  18035. serializationObject.type = "OculusCamera";
  18036. }
  18037. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18038. serializationObject.type = "OculusGamepadCamera";
  18039. }
  18040. else if (camera instanceof BABYLON.TouchCamera) {
  18041. serializationObject.type = "TouchCamera";
  18042. }
  18043. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18044. serializationObject.type = "VirtualJoysticksCamera";
  18045. }
  18046. else if (camera instanceof BABYLON.WebVRCamera) {
  18047. serializationObject.type = "WebVRCamera";
  18048. }
  18049. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18050. serializationObject.type = "VRDeviceOrientationCamera";
  18051. }
  18052. //special properties of specific cameras
  18053. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18054. var arcCamera = camera;
  18055. serializationObject.alpha = arcCamera.alpha;
  18056. serializationObject.beta = arcCamera.beta;
  18057. serializationObject.radius = arcCamera.radius;
  18058. }
  18059. else if (camera instanceof BABYLON.FollowCamera) {
  18060. var followCam = camera;
  18061. serializationObject.radius = followCam.radius;
  18062. serializationObject.heightOffset = followCam.heightOffset;
  18063. serializationObject.rotationOffset = followCam.rotationOffset;
  18064. }
  18065. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18066. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18067. if (camera['_eyeSpace'] !== undefined) {
  18068. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18069. }
  18070. }
  18071. //general properties that not all cameras have. The [] is due to typescript's type safety
  18072. if (camera['speed'] !== undefined) {
  18073. serializationObject.speed = camera['speed'];
  18074. }
  18075. // Target
  18076. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18077. serializationObject.rotation = camera['rotation'].asArray();
  18078. }
  18079. // Locked target
  18080. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18081. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18082. }
  18083. if (camera['checkCollisions'] !== undefined) {
  18084. serializationObject.checkCollisions = camera['checkCollisions'];
  18085. }
  18086. if (camera['applyGravity'] !== undefined) {
  18087. serializationObject.applyGravity = camera['applyGravity'];
  18088. }
  18089. if (camera['ellipsoid']) {
  18090. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18091. }
  18092. // Animations
  18093. appendAnimations(camera, serializationObject);
  18094. // Layer mask
  18095. serializationObject.layerMask = camera.layerMask;
  18096. return serializationObject;
  18097. };
  18098. var appendAnimations = function (source, destination) {
  18099. if (source.animations) {
  18100. destination.animations = [];
  18101. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18102. var animation = source.animations[animationIndex];
  18103. destination.animations.push(serializeAnimation(animation));
  18104. }
  18105. }
  18106. };
  18107. var serializeAnimation = function (animation) {
  18108. var serializationObject = {};
  18109. serializationObject.name = animation.name;
  18110. serializationObject.property = animation.targetProperty;
  18111. serializationObject.framePerSecond = animation.framePerSecond;
  18112. serializationObject.dataType = animation.dataType;
  18113. serializationObject.loopBehavior = animation.loopMode;
  18114. var dataType = animation.dataType;
  18115. serializationObject.keys = [];
  18116. var keys = animation.getKeys();
  18117. for (var index = 0; index < keys.length; index++) {
  18118. var animationKey = keys[index];
  18119. var key = {};
  18120. key.frame = animationKey.frame;
  18121. switch (dataType) {
  18122. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18123. key.values = [animationKey.value];
  18124. break;
  18125. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18126. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18127. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18128. key.values = animationKey.value.asArray();
  18129. break;
  18130. }
  18131. serializationObject.keys.push(key);
  18132. }
  18133. return serializationObject;
  18134. };
  18135. var serializeMultiMaterial = function (material) {
  18136. var serializationObject = {};
  18137. serializationObject.name = material.name;
  18138. serializationObject.id = material.id;
  18139. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18140. serializationObject.materials = [];
  18141. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18142. var subMat = material.subMaterials[matIndex];
  18143. if (subMat) {
  18144. serializationObject.materials.push(subMat.id);
  18145. }
  18146. else {
  18147. serializationObject.materials.push(null);
  18148. }
  18149. }
  18150. return serializationObject;
  18151. };
  18152. var serializeMaterial = function (material) {
  18153. var serializationObject = {};
  18154. serializationObject.name = material.name;
  18155. serializationObject.ambient = material.ambientColor.asArray();
  18156. serializationObject.diffuse = material.diffuseColor.asArray();
  18157. serializationObject.specular = material.specularColor.asArray();
  18158. serializationObject.specularPower = material.specularPower;
  18159. serializationObject.emissive = material.emissiveColor.asArray();
  18160. serializationObject.alpha = material.alpha;
  18161. serializationObject.id = material.id;
  18162. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18163. serializationObject.backFaceCulling = material.backFaceCulling;
  18164. if (material.diffuseTexture) {
  18165. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18166. }
  18167. if (material.diffuseFresnelParameters) {
  18168. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18169. }
  18170. if (material.ambientTexture) {
  18171. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18172. }
  18173. if (material.opacityTexture) {
  18174. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18175. }
  18176. if (material.opacityFresnelParameters) {
  18177. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18178. }
  18179. if (material.reflectionTexture) {
  18180. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18181. }
  18182. if (material.reflectionFresnelParameters) {
  18183. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18184. }
  18185. if (material.emissiveTexture) {
  18186. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18187. }
  18188. if (material.emissiveFresnelParameters) {
  18189. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18190. }
  18191. if (material.specularTexture) {
  18192. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18193. }
  18194. if (material.bumpTexture) {
  18195. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18196. }
  18197. return serializationObject;
  18198. };
  18199. var serializeTexture = function (texture) {
  18200. var serializationObject = {};
  18201. if (!texture.name) {
  18202. return null;
  18203. }
  18204. if (texture instanceof BABYLON.CubeTexture) {
  18205. serializationObject.name = texture.name;
  18206. serializationObject.hasAlpha = texture.hasAlpha;
  18207. serializationObject.level = texture.level;
  18208. serializationObject.coordinatesMode = texture.coordinatesMode;
  18209. return serializationObject;
  18210. }
  18211. if (texture instanceof BABYLON.MirrorTexture) {
  18212. var mirrorTexture = texture;
  18213. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18214. serializationObject.renderList = [];
  18215. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18216. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18217. }
  18218. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18219. }
  18220. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18221. var renderTargetTexture = texture;
  18222. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18223. serializationObject.renderList = [];
  18224. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18225. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18226. }
  18227. }
  18228. var regularTexture = texture;
  18229. serializationObject.name = texture.name;
  18230. serializationObject.hasAlpha = texture.hasAlpha;
  18231. serializationObject.level = texture.level;
  18232. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18233. serializationObject.coordinatesMode = texture.coordinatesMode;
  18234. serializationObject.uOffset = regularTexture.uOffset;
  18235. serializationObject.vOffset = regularTexture.vOffset;
  18236. serializationObject.uScale = regularTexture.uScale;
  18237. serializationObject.vScale = regularTexture.vScale;
  18238. serializationObject.uAng = regularTexture.uAng;
  18239. serializationObject.vAng = regularTexture.vAng;
  18240. serializationObject.wAng = regularTexture.wAng;
  18241. serializationObject.wrapU = texture.wrapU;
  18242. serializationObject.wrapV = texture.wrapV;
  18243. // Animations
  18244. appendAnimations(texture, serializationObject);
  18245. return serializationObject;
  18246. };
  18247. var serializeSkeleton = function (skeleton) {
  18248. var serializationObject = {};
  18249. serializationObject.name = skeleton.name;
  18250. serializationObject.id = skeleton.id;
  18251. serializationObject.bones = [];
  18252. for (var index = 0; index < skeleton.bones.length; index++) {
  18253. var bone = skeleton.bones[index];
  18254. var serializedBone = {
  18255. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18256. name: bone.name,
  18257. matrix: bone.getLocalMatrix().toArray()
  18258. };
  18259. serializationObject.bones.push(serializedBone);
  18260. if (bone.animations && bone.animations.length > 0) {
  18261. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18262. }
  18263. }
  18264. return serializationObject;
  18265. };
  18266. var serializeParticleSystem = function (particleSystem) {
  18267. var serializationObject = {};
  18268. serializationObject.emitterId = particleSystem.emitter.id;
  18269. serializationObject.capacity = particleSystem.getCapacity();
  18270. if (particleSystem.particleTexture) {
  18271. serializationObject.textureName = particleSystem.particleTexture.name;
  18272. }
  18273. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18274. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18275. serializationObject.minSize = particleSystem.minSize;
  18276. serializationObject.maxSize = particleSystem.maxSize;
  18277. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18278. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18279. serializationObject.emitRate = particleSystem.emitRate;
  18280. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18281. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18282. serializationObject.gravity = particleSystem.gravity.asArray();
  18283. serializationObject.direction1 = particleSystem.direction1.asArray();
  18284. serializationObject.direction2 = particleSystem.direction2.asArray();
  18285. serializationObject.color1 = particleSystem.color1.asArray();
  18286. serializationObject.color2 = particleSystem.color2.asArray();
  18287. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18288. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18289. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18290. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18291. serializationObject.blendMode = particleSystem.blendMode;
  18292. return serializationObject;
  18293. };
  18294. var serializeLensFlareSystem = function (lensFlareSystem) {
  18295. var serializationObject = {};
  18296. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18297. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18298. serializationObject.flares = [];
  18299. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18300. var flare = lensFlareSystem.lensFlares[index];
  18301. serializationObject.flares.push({
  18302. size: flare.size,
  18303. position: flare.position,
  18304. color: flare.color.asArray(),
  18305. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18306. });
  18307. }
  18308. return serializationObject;
  18309. };
  18310. var serializeShadowGenerator = function (light) {
  18311. var serializationObject = {};
  18312. var shadowGenerator = light.getShadowGenerator();
  18313. serializationObject.lightId = light.id;
  18314. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18315. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18316. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18317. serializationObject.renderList = [];
  18318. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18319. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18320. serializationObject.renderList.push(mesh.id);
  18321. }
  18322. return serializationObject;
  18323. };
  18324. var serializedGeometries = [];
  18325. var serializeGeometry = function (geometry, serializationGeometries) {
  18326. if (serializedGeometries[geometry.id]) {
  18327. return;
  18328. }
  18329. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18330. serializationGeometries.boxes.push(serializeBox(geometry));
  18331. }
  18332. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18333. serializationGeometries.spheres.push(serializeSphere(geometry));
  18334. }
  18335. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18336. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18337. }
  18338. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18339. serializationGeometries.toruses.push(serializeTorus(geometry));
  18340. }
  18341. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18342. serializationGeometries.grounds.push(serializeGround(geometry));
  18343. }
  18344. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18345. serializationGeometries.planes.push(serializePlane(geometry));
  18346. }
  18347. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18348. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18349. }
  18350. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18351. throw new Error("Unknow primitive type");
  18352. }
  18353. else {
  18354. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18355. }
  18356. serializedGeometries[geometry.id] = true;
  18357. };
  18358. var serializeGeometryBase = function (geometry) {
  18359. var serializationObject = {};
  18360. serializationObject.id = geometry.id;
  18361. if (BABYLON.Tags.HasTags(geometry)) {
  18362. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18363. }
  18364. return serializationObject;
  18365. };
  18366. var serializeVertexData = function (vertexData) {
  18367. var serializationObject = serializeGeometryBase(vertexData);
  18368. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18369. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18370. }
  18371. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18372. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18373. }
  18374. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18375. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18376. }
  18377. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18378. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18379. }
  18380. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18381. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18382. }
  18383. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18384. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18385. serializationObject.matricesIndices._isExpanded = true;
  18386. }
  18387. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18388. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18389. }
  18390. serializationObject.indices = vertexData.getIndices();
  18391. return serializationObject;
  18392. };
  18393. var serializePrimitive = function (primitive) {
  18394. var serializationObject = serializeGeometryBase(primitive);
  18395. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18396. return serializationObject;
  18397. };
  18398. var serializeBox = function (box) {
  18399. var serializationObject = serializePrimitive(box);
  18400. serializationObject.size = box.size;
  18401. return serializationObject;
  18402. };
  18403. var serializeSphere = function (sphere) {
  18404. var serializationObject = serializePrimitive(sphere);
  18405. serializationObject.segments = sphere.segments;
  18406. serializationObject.diameter = sphere.diameter;
  18407. return serializationObject;
  18408. };
  18409. var serializeCylinder = function (cylinder) {
  18410. var serializationObject = serializePrimitive(cylinder);
  18411. serializationObject.height = cylinder.height;
  18412. serializationObject.diameterTop = cylinder.diameterTop;
  18413. serializationObject.diameterBottom = cylinder.diameterBottom;
  18414. serializationObject.tessellation = cylinder.tessellation;
  18415. return serializationObject;
  18416. };
  18417. var serializeTorus = function (torus) {
  18418. var serializationObject = serializePrimitive(torus);
  18419. serializationObject.diameter = torus.diameter;
  18420. serializationObject.thickness = torus.thickness;
  18421. serializationObject.tessellation = torus.tessellation;
  18422. return serializationObject;
  18423. };
  18424. var serializeGround = function (ground) {
  18425. var serializationObject = serializePrimitive(ground);
  18426. serializationObject.width = ground.width;
  18427. serializationObject.height = ground.height;
  18428. serializationObject.subdivisions = ground.subdivisions;
  18429. return serializationObject;
  18430. };
  18431. var serializePlane = function (plane) {
  18432. var serializationObject = serializePrimitive(plane);
  18433. serializationObject.size = plane.size;
  18434. return serializationObject;
  18435. };
  18436. var serializeTorusKnot = function (torusKnot) {
  18437. var serializationObject = serializePrimitive(torusKnot);
  18438. serializationObject.radius = torusKnot.radius;
  18439. serializationObject.tube = torusKnot.tube;
  18440. serializationObject.radialSegments = torusKnot.radialSegments;
  18441. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18442. serializationObject.p = torusKnot.p;
  18443. serializationObject.q = torusKnot.q;
  18444. return serializationObject;
  18445. };
  18446. var serializeMesh = function (mesh, serializationScene) {
  18447. var serializationObject = {};
  18448. serializationObject.name = mesh.name;
  18449. serializationObject.id = mesh.id;
  18450. if (BABYLON.Tags.HasTags(mesh)) {
  18451. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18452. }
  18453. serializationObject.position = mesh.position.asArray();
  18454. if (mesh.rotationQuaternion) {
  18455. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18456. }
  18457. else if (mesh.rotation) {
  18458. serializationObject.rotation = mesh.rotation.asArray();
  18459. }
  18460. serializationObject.scaling = mesh.scaling.asArray();
  18461. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18462. serializationObject.isEnabled = mesh.isEnabled();
  18463. serializationObject.isVisible = mesh.isVisible;
  18464. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18465. serializationObject.pickable = mesh.isPickable;
  18466. serializationObject.receiveShadows = mesh.receiveShadows;
  18467. serializationObject.billboardMode = mesh.billboardMode;
  18468. serializationObject.visibility = mesh.visibility;
  18469. serializationObject.checkCollisions = mesh.checkCollisions;
  18470. // Parent
  18471. if (mesh.parent) {
  18472. serializationObject.parentId = mesh.parent.id;
  18473. }
  18474. // Geometry
  18475. var geometry = mesh._geometry;
  18476. if (geometry) {
  18477. var geometryId = geometry.id;
  18478. serializationObject.geometryId = geometryId;
  18479. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18480. // 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
  18481. serializeGeometry(geometry, serializationScene.geometries);
  18482. }
  18483. // SubMeshes
  18484. serializationObject.subMeshes = [];
  18485. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18486. var subMesh = mesh.subMeshes[subIndex];
  18487. serializationObject.subMeshes.push({
  18488. materialIndex: subMesh.materialIndex,
  18489. verticesStart: subMesh.verticesStart,
  18490. verticesCount: subMesh.verticesCount,
  18491. indexStart: subMesh.indexStart,
  18492. indexCount: subMesh.indexCount
  18493. });
  18494. }
  18495. }
  18496. // Material
  18497. if (mesh.material) {
  18498. serializationObject.materialId = mesh.material.id;
  18499. }
  18500. else {
  18501. mesh.material = null;
  18502. }
  18503. // Skeleton
  18504. if (mesh.skeleton) {
  18505. serializationObject.skeletonId = mesh.skeleton.id;
  18506. }
  18507. // Physics
  18508. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18509. serializationObject.physicsMass = mesh.getPhysicsMass();
  18510. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18511. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18512. switch (mesh.getPhysicsImpostor()) {
  18513. case BABYLON.PhysicsEngine.BoxImpostor:
  18514. serializationObject.physicsImpostor = 1;
  18515. break;
  18516. case BABYLON.PhysicsEngine.SphereImpostor:
  18517. serializationObject.physicsImpostor = 2;
  18518. break;
  18519. }
  18520. }
  18521. // Instances
  18522. serializationObject.instances = [];
  18523. for (var index = 0; index < mesh.instances.length; index++) {
  18524. var instance = mesh.instances[index];
  18525. var serializationInstance = {
  18526. name: instance.name,
  18527. position: instance.position,
  18528. rotation: instance.rotation,
  18529. rotationQuaternion: instance.rotationQuaternion,
  18530. scaling: instance.scaling
  18531. };
  18532. serializationObject.instances.push(serializationInstance);
  18533. // Animations
  18534. appendAnimations(instance, serializationInstance);
  18535. }
  18536. // Animations
  18537. appendAnimations(mesh, serializationObject);
  18538. // Layer mask
  18539. serializationObject.layerMask = mesh.layerMask;
  18540. return serializationObject;
  18541. };
  18542. var SceneSerializer = (function () {
  18543. function SceneSerializer() {
  18544. }
  18545. SceneSerializer.Serialize = function (scene) {
  18546. var serializationObject = {};
  18547. // Scene
  18548. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18549. serializationObject.autoClear = scene.autoClear;
  18550. serializationObject.clearColor = scene.clearColor.asArray();
  18551. serializationObject.ambientColor = scene.ambientColor.asArray();
  18552. serializationObject.gravity = scene.gravity.asArray();
  18553. // Fog
  18554. if (scene.fogMode && scene.fogMode !== 0) {
  18555. serializationObject.fogMode = scene.fogMode;
  18556. serializationObject.fogColor = scene.fogColor.asArray();
  18557. serializationObject.fogStart = scene.fogStart;
  18558. serializationObject.fogEnd = scene.fogEnd;
  18559. serializationObject.fogDensity = scene.fogDensity;
  18560. }
  18561. // Lights
  18562. serializationObject.lights = [];
  18563. for (var index = 0; index < scene.lights.length; index++) {
  18564. var light = scene.lights[index];
  18565. serializationObject.lights.push(serializeLight(light));
  18566. }
  18567. // Cameras
  18568. serializationObject.cameras = [];
  18569. for (index = 0; index < scene.cameras.length; index++) {
  18570. var camera = scene.cameras[index];
  18571. serializationObject.cameras.push(serializeCamera(camera));
  18572. }
  18573. if (scene.activeCamera) {
  18574. serializationObject.activeCameraID = scene.activeCamera.id;
  18575. }
  18576. // Materials
  18577. serializationObject.materials = [];
  18578. serializationObject.multiMaterials = [];
  18579. for (index = 0; index < scene.materials.length; index++) {
  18580. var material = scene.materials[index];
  18581. if (material instanceof BABYLON.StandardMaterial) {
  18582. serializationObject.materials.push(serializeMaterial(material));
  18583. }
  18584. else if (material instanceof BABYLON.MultiMaterial) {
  18585. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18586. }
  18587. }
  18588. // Skeletons
  18589. serializationObject.skeletons = [];
  18590. for (index = 0; index < scene.skeletons.length; index++) {
  18591. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18592. }
  18593. // Geometries
  18594. serializationObject.geometries = {};
  18595. serializationObject.geometries.boxes = [];
  18596. serializationObject.geometries.spheres = [];
  18597. serializationObject.geometries.cylinders = [];
  18598. serializationObject.geometries.toruses = [];
  18599. serializationObject.geometries.grounds = [];
  18600. serializationObject.geometries.planes = [];
  18601. serializationObject.geometries.torusKnots = [];
  18602. serializationObject.geometries.vertexData = [];
  18603. serializedGeometries = [];
  18604. var geometries = scene.getGeometries();
  18605. for (var index = 0; index < geometries.length; index++) {
  18606. var geometry = geometries[index];
  18607. if (geometry.isReady()) {
  18608. serializeGeometry(geometry, serializationObject.geometries);
  18609. }
  18610. }
  18611. // Meshes
  18612. serializationObject.meshes = [];
  18613. for (index = 0; index < scene.meshes.length; index++) {
  18614. var abstractMesh = scene.meshes[index];
  18615. if (abstractMesh instanceof BABYLON.Mesh) {
  18616. var mesh = abstractMesh;
  18617. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18618. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18619. }
  18620. }
  18621. }
  18622. // Particles Systems
  18623. serializationObject.particleSystems = [];
  18624. for (index = 0; index < scene.particleSystems.length; index++) {
  18625. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18626. }
  18627. // Lens flares
  18628. serializationObject.lensFlareSystems = [];
  18629. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18630. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18631. }
  18632. // Shadows
  18633. serializationObject.shadowGenerators = [];
  18634. for (index = 0; index < scene.lights.length; index++) {
  18635. light = scene.lights[index];
  18636. if (light.getShadowGenerator()) {
  18637. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18638. }
  18639. }
  18640. return serializationObject;
  18641. };
  18642. return SceneSerializer;
  18643. })();
  18644. BABYLON.SceneSerializer = SceneSerializer;
  18645. })(BABYLON || (BABYLON = {}));
  18646. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18647. (function (BABYLON) {
  18648. var SceneLoader = (function () {
  18649. function SceneLoader() {
  18650. }
  18651. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18652. get: function () {
  18653. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18654. },
  18655. set: function (value) {
  18656. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18657. },
  18658. enumerable: true,
  18659. configurable: true
  18660. });
  18661. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18662. get: function () {
  18663. return SceneLoader._ShowLoadingScreen;
  18664. },
  18665. set: function (value) {
  18666. SceneLoader._ShowLoadingScreen = value;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18672. var dotPosition = sceneFilename.lastIndexOf(".");
  18673. var queryStringPosition = sceneFilename.indexOf("?");
  18674. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18675. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18676. var plugin = this._registeredPlugins[index];
  18677. if (plugin.extensions.indexOf(extension) !== -1) {
  18678. return plugin;
  18679. }
  18680. }
  18681. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18682. };
  18683. // Public functions
  18684. SceneLoader.RegisterPlugin = function (plugin) {
  18685. plugin.extensions = plugin.extensions.toLowerCase();
  18686. SceneLoader._registeredPlugins.push(plugin);
  18687. };
  18688. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18689. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18690. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18691. return;
  18692. }
  18693. var manifestChecked = function (success) {
  18694. scene.database = database;
  18695. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18696. var importMeshFromData = function (data) {
  18697. var meshes = [];
  18698. var particleSystems = [];
  18699. var skeletons = [];
  18700. try {
  18701. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18702. if (onerror) {
  18703. onerror(scene, 'unable to load the scene');
  18704. }
  18705. return;
  18706. }
  18707. }
  18708. catch (e) {
  18709. if (onerror) {
  18710. onerror(scene, e);
  18711. }
  18712. return;
  18713. }
  18714. if (onsuccess) {
  18715. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18716. onsuccess(meshes, particleSystems, skeletons);
  18717. }
  18718. };
  18719. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18720. // Direct load
  18721. importMeshFromData(sceneFilename.substr(5));
  18722. return;
  18723. }
  18724. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18725. importMeshFromData(data);
  18726. }, progressCallBack, database);
  18727. };
  18728. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18729. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18730. };
  18731. /**
  18732. * Load a scene
  18733. * @param rootUrl a string that defines the root url for scene and resources
  18734. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18735. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18736. */
  18737. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18738. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18739. };
  18740. /**
  18741. * Append a scene
  18742. * @param rootUrl a string that defines the root url for scene and resources
  18743. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18744. * @param scene is the instance of BABYLON.Scene to append to
  18745. */
  18746. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18747. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18748. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18749. return;
  18750. }
  18751. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18752. var database;
  18753. if (SceneLoader.ShowLoadingScreen) {
  18754. scene.getEngine().displayLoadingUI();
  18755. }
  18756. var loadSceneFromData = function (data) {
  18757. scene.database = database;
  18758. if (!plugin.load(scene, data, rootUrl)) {
  18759. if (onerror) {
  18760. onerror(scene);
  18761. }
  18762. scene.getEngine().hideLoadingUI();
  18763. return;
  18764. }
  18765. if (onsuccess) {
  18766. onsuccess(scene);
  18767. }
  18768. if (SceneLoader.ShowLoadingScreen) {
  18769. scene.executeWhenReady(function () {
  18770. scene.getEngine().hideLoadingUI();
  18771. });
  18772. }
  18773. };
  18774. var manifestChecked = function (success) {
  18775. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18776. };
  18777. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18778. // Direct load
  18779. loadSceneFromData(sceneFilename.substr(5));
  18780. return;
  18781. }
  18782. if (rootUrl.indexOf("file:") === -1) {
  18783. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18784. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18785. }
  18786. else {
  18787. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18788. }
  18789. };
  18790. // Flags
  18791. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18792. SceneLoader._ShowLoadingScreen = true;
  18793. // Members
  18794. SceneLoader._registeredPlugins = new Array();
  18795. return SceneLoader;
  18796. })();
  18797. BABYLON.SceneLoader = SceneLoader;
  18798. ;
  18799. })(BABYLON || (BABYLON = {}));
  18800. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18801. (function (BABYLON) {
  18802. var Internals;
  18803. (function (Internals) {
  18804. var checkColors4 = function (colors, count) {
  18805. // Check if color3 was used
  18806. if (colors.length === count * 3) {
  18807. var colors4 = [];
  18808. for (var index = 0; index < colors.length; index += 3) {
  18809. var newIndex = (index / 3) * 4;
  18810. colors4[newIndex] = colors[index];
  18811. colors4[newIndex + 1] = colors[index + 1];
  18812. colors4[newIndex + 2] = colors[index + 2];
  18813. colors4[newIndex + 3] = 1.0;
  18814. }
  18815. return colors4;
  18816. }
  18817. return colors;
  18818. };
  18819. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18820. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18821. texture.name = parsedTexture.name;
  18822. texture.hasAlpha = parsedTexture.hasAlpha;
  18823. texture.level = parsedTexture.level;
  18824. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18825. return texture;
  18826. };
  18827. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18828. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18829. return null;
  18830. }
  18831. if (parsedTexture.isCube) {
  18832. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18833. }
  18834. var texture;
  18835. if (parsedTexture.mirrorPlane) {
  18836. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18837. texture._waitingRenderList = parsedTexture.renderList;
  18838. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18839. }
  18840. else if (parsedTexture.isRenderTarget) {
  18841. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18842. texture._waitingRenderList = parsedTexture.renderList;
  18843. }
  18844. else {
  18845. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18846. }
  18847. texture.name = parsedTexture.name;
  18848. texture.hasAlpha = parsedTexture.hasAlpha;
  18849. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18850. texture.level = parsedTexture.level;
  18851. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18852. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18853. texture.uOffset = parsedTexture.uOffset;
  18854. texture.vOffset = parsedTexture.vOffset;
  18855. texture.uScale = parsedTexture.uScale;
  18856. texture.vScale = parsedTexture.vScale;
  18857. texture.uAng = parsedTexture.uAng;
  18858. texture.vAng = parsedTexture.vAng;
  18859. texture.wAng = parsedTexture.wAng;
  18860. texture.wrapU = parsedTexture.wrapU;
  18861. texture.wrapV = parsedTexture.wrapV;
  18862. // Animations
  18863. if (parsedTexture.animations) {
  18864. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18865. var parsedAnimation = parsedTexture.animations[animationIndex];
  18866. texture.animations.push(parseAnimation(parsedAnimation));
  18867. }
  18868. }
  18869. return texture;
  18870. };
  18871. var parseSkeleton = function (parsedSkeleton, scene) {
  18872. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18873. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18874. var parsedBone = parsedSkeleton.bones[index];
  18875. var parentBone = null;
  18876. if (parsedBone.parentBoneIndex > -1) {
  18877. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18878. }
  18879. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18880. if (parsedBone.animation) {
  18881. bone.animations.push(parseAnimation(parsedBone.animation));
  18882. }
  18883. }
  18884. return skeleton;
  18885. };
  18886. var parseFresnelParameters = function (parsedFresnelParameters) {
  18887. var fresnelParameters = new BABYLON.FresnelParameters();
  18888. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18889. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18890. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18891. fresnelParameters.bias = parsedFresnelParameters.bias;
  18892. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18893. return fresnelParameters;
  18894. };
  18895. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18896. var material;
  18897. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18898. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18899. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18900. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18901. material.specularPower = parsedMaterial.specularPower;
  18902. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18903. material.alpha = parsedMaterial.alpha;
  18904. material.id = parsedMaterial.id;
  18905. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18906. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18907. material.wireframe = parsedMaterial.wireframe;
  18908. if (parsedMaterial.diffuseTexture) {
  18909. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18910. }
  18911. if (parsedMaterial.diffuseFresnelParameters) {
  18912. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18913. }
  18914. if (parsedMaterial.ambientTexture) {
  18915. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18916. }
  18917. if (parsedMaterial.opacityTexture) {
  18918. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18919. }
  18920. if (parsedMaterial.opacityFresnelParameters) {
  18921. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18922. }
  18923. if (parsedMaterial.reflectionTexture) {
  18924. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18925. }
  18926. if (parsedMaterial.reflectionFresnelParameters) {
  18927. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18928. }
  18929. if (parsedMaterial.emissiveTexture) {
  18930. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18931. }
  18932. if (parsedMaterial.emissiveFresnelParameters) {
  18933. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18934. }
  18935. if (parsedMaterial.specularTexture) {
  18936. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18937. }
  18938. if (parsedMaterial.bumpTexture) {
  18939. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18940. }
  18941. return material;
  18942. };
  18943. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18944. for (var index = 0; index < parsedData.materials.length; index++) {
  18945. var parsedMaterial = parsedData.materials[index];
  18946. if (parsedMaterial.id === id) {
  18947. return parseMaterial(parsedMaterial, scene, rootUrl);
  18948. }
  18949. }
  18950. return null;
  18951. };
  18952. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18953. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18954. multiMaterial.id = parsedMultiMaterial.id;
  18955. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18956. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18957. var subMatId = parsedMultiMaterial.materials[matIndex];
  18958. if (subMatId) {
  18959. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18960. }
  18961. else {
  18962. multiMaterial.subMaterials.push(null);
  18963. }
  18964. }
  18965. return multiMaterial;
  18966. };
  18967. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18968. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18969. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18970. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18971. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18972. var parsedFlare = parsedLensFlareSystem.flares[index];
  18973. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18974. }
  18975. return lensFlareSystem;
  18976. };
  18977. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18978. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18979. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18980. if (parsedParticleSystem.textureName) {
  18981. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18982. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18983. }
  18984. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18985. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18986. particleSystem.minSize = parsedParticleSystem.minSize;
  18987. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18988. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18989. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18990. particleSystem.emitter = emitter;
  18991. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18992. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18993. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18994. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18995. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18996. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18997. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18998. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18999. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19000. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19001. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19002. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19003. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19004. particleSystem.start();
  19005. return particleSystem;
  19006. };
  19007. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19008. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19009. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19010. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19011. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19012. shadowGenerator.getShadowMap().renderList.push(mesh);
  19013. }
  19014. if (parsedShadowGenerator.usePoissonSampling) {
  19015. shadowGenerator.usePoissonSampling = true;
  19016. }
  19017. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19018. shadowGenerator.useVarianceShadowMap = true;
  19019. }
  19020. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19021. shadowGenerator.useBlurVarianceShadowMap = true;
  19022. }
  19023. if (parsedShadowGenerator.bias) {
  19024. shadowGenerator.bias = parsedShadowGenerator.bias;
  19025. }
  19026. return shadowGenerator;
  19027. };
  19028. var parseAnimation = function (parsedAnimation) {
  19029. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19030. var dataType = parsedAnimation.dataType;
  19031. var keys = [];
  19032. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19033. var key = parsedAnimation.keys[index];
  19034. var data;
  19035. switch (dataType) {
  19036. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19037. data = key.values[0];
  19038. break;
  19039. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19040. data = BABYLON.Quaternion.FromArray(key.values);
  19041. break;
  19042. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19043. data = BABYLON.Matrix.FromArray(key.values);
  19044. break;
  19045. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19046. default:
  19047. data = BABYLON.Vector3.FromArray(key.values);
  19048. break;
  19049. }
  19050. keys.push({
  19051. frame: key.frame,
  19052. value: data
  19053. });
  19054. }
  19055. animation.setKeys(keys);
  19056. return animation;
  19057. };
  19058. var parseLight = function (parsedLight, scene) {
  19059. var light;
  19060. switch (parsedLight.type) {
  19061. case 0:
  19062. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19063. break;
  19064. case 1:
  19065. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19066. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19067. break;
  19068. case 2:
  19069. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19070. break;
  19071. case 3:
  19072. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19073. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19074. break;
  19075. }
  19076. light.id = parsedLight.id;
  19077. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19078. if (parsedLight.intensity !== undefined) {
  19079. light.intensity = parsedLight.intensity;
  19080. }
  19081. if (parsedLight.range) {
  19082. light.range = parsedLight.range;
  19083. }
  19084. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19085. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19086. if (parsedLight.excludedMeshesIds) {
  19087. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19088. }
  19089. // Parent
  19090. if (parsedLight.parentId) {
  19091. light._waitingParentId = parsedLight.parentId;
  19092. }
  19093. if (parsedLight.includedOnlyMeshesIds) {
  19094. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19095. }
  19096. // Animations
  19097. if (parsedLight.animations) {
  19098. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19099. var parsedAnimation = parsedLight.animations[animationIndex];
  19100. light.animations.push(parseAnimation(parsedAnimation));
  19101. }
  19102. }
  19103. if (parsedLight.autoAnimate) {
  19104. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19105. }
  19106. };
  19107. var parseCamera = function (parsedCamera, scene) {
  19108. var camera;
  19109. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19110. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19111. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19112. var alpha = parsedCamera.alpha;
  19113. var beta = parsedCamera.beta;
  19114. var radius = parsedCamera.radius;
  19115. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19116. var eye_space = parsedCamera.eye_space;
  19117. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19118. }
  19119. else {
  19120. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19121. }
  19122. }
  19123. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19124. eye_space = parsedCamera.eye_space;
  19125. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19126. }
  19127. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19128. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19129. }
  19130. else if (parsedCamera.type === "FollowCamera") {
  19131. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19132. camera.heightOffset = parsedCamera.heightOffset;
  19133. camera.radius = parsedCamera.radius;
  19134. camera.rotationOffset = parsedCamera.rotationOffset;
  19135. if (lockedTargetMesh)
  19136. camera.target = lockedTargetMesh;
  19137. }
  19138. else if (parsedCamera.type === "GamepadCamera") {
  19139. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19140. }
  19141. else if (parsedCamera.type === "OculusCamera") {
  19142. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19143. }
  19144. else if (parsedCamera.type === "OculusGamepadCamera") {
  19145. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19146. }
  19147. else if (parsedCamera.type === "TouchCamera") {
  19148. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19149. }
  19150. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19151. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19152. }
  19153. else if (parsedCamera.type === "WebVRCamera") {
  19154. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19155. }
  19156. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19157. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19158. }
  19159. else {
  19160. // Free Camera is the default value
  19161. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19162. }
  19163. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19164. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19165. camera.lockedTarget = lockedTargetMesh;
  19166. }
  19167. camera.id = parsedCamera.id;
  19168. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19169. // Parent
  19170. if (parsedCamera.parentId) {
  19171. camera._waitingParentId = parsedCamera.parentId;
  19172. }
  19173. // Target
  19174. if (parsedCamera.target) {
  19175. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19176. }
  19177. else {
  19178. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19179. }
  19180. camera.fov = parsedCamera.fov;
  19181. camera.minZ = parsedCamera.minZ;
  19182. camera.maxZ = parsedCamera.maxZ;
  19183. camera.speed = parsedCamera.speed;
  19184. camera.inertia = parsedCamera.inertia;
  19185. camera.checkCollisions = parsedCamera.checkCollisions;
  19186. camera.applyGravity = parsedCamera.applyGravity;
  19187. if (parsedCamera.ellipsoid) {
  19188. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19189. }
  19190. // Animations
  19191. if (parsedCamera.animations) {
  19192. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19193. var parsedAnimation = parsedCamera.animations[animationIndex];
  19194. camera.animations.push(parseAnimation(parsedAnimation));
  19195. }
  19196. }
  19197. if (parsedCamera.autoAnimate) {
  19198. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19199. }
  19200. // Layer Mask
  19201. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19202. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19203. }
  19204. else {
  19205. camera.layerMask = 0xFFFFFFFF;
  19206. }
  19207. return camera;
  19208. };
  19209. var parseGeometry = function (parsedGeometry, scene) {
  19210. var id = parsedGeometry.id;
  19211. return scene.getGeometryByID(id);
  19212. };
  19213. var parseBox = function (parsedBox, scene) {
  19214. if (parseGeometry(parsedBox, scene)) {
  19215. return null; // null since geometry could be something else than a box...
  19216. }
  19217. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19218. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19219. scene.pushGeometry(box, true);
  19220. return box;
  19221. };
  19222. var parseSphere = function (parsedSphere, scene) {
  19223. if (parseGeometry(parsedSphere, scene)) {
  19224. return null; // null since geometry could be something else than a sphere...
  19225. }
  19226. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19227. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19228. scene.pushGeometry(sphere, true);
  19229. return sphere;
  19230. };
  19231. var parseCylinder = function (parsedCylinder, scene) {
  19232. if (parseGeometry(parsedCylinder, scene)) {
  19233. return null; // null since geometry could be something else than a cylinder...
  19234. }
  19235. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19236. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19237. scene.pushGeometry(cylinder, true);
  19238. return cylinder;
  19239. };
  19240. var parseTorus = function (parsedTorus, scene) {
  19241. if (parseGeometry(parsedTorus, scene)) {
  19242. return null; // null since geometry could be something else than a torus...
  19243. }
  19244. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19245. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19246. scene.pushGeometry(torus, true);
  19247. return torus;
  19248. };
  19249. var parseGround = function (parsedGround, scene) {
  19250. if (parseGeometry(parsedGround, scene)) {
  19251. return null; // null since geometry could be something else than a ground...
  19252. }
  19253. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19254. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19255. scene.pushGeometry(ground, true);
  19256. return ground;
  19257. };
  19258. var parsePlane = function (parsedPlane, scene) {
  19259. if (parseGeometry(parsedPlane, scene)) {
  19260. return null; // null since geometry could be something else than a plane...
  19261. }
  19262. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19263. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19264. scene.pushGeometry(plane, true);
  19265. return plane;
  19266. };
  19267. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19268. if (parseGeometry(parsedTorusKnot, scene)) {
  19269. return null; // null since geometry could be something else than a torusKnot...
  19270. }
  19271. 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);
  19272. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19273. scene.pushGeometry(torusKnot, true);
  19274. return torusKnot;
  19275. };
  19276. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19277. if (parseGeometry(parsedVertexData, scene)) {
  19278. return null; // null since geometry could be a primitive
  19279. }
  19280. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19281. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19282. if (parsedVertexData.delayLoadingFile) {
  19283. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19284. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19285. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19286. geometry._delayInfo = [];
  19287. if (parsedVertexData.hasUVs) {
  19288. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19289. }
  19290. if (parsedVertexData.hasUVs2) {
  19291. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19292. }
  19293. if (parsedVertexData.hasColors) {
  19294. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19295. }
  19296. if (parsedVertexData.hasMatricesIndices) {
  19297. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19298. }
  19299. if (parsedVertexData.hasMatricesWeights) {
  19300. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19301. }
  19302. geometry._delayLoadingFunction = importVertexData;
  19303. }
  19304. else {
  19305. importVertexData(parsedVertexData, geometry);
  19306. }
  19307. scene.pushGeometry(geometry, true);
  19308. return geometry;
  19309. };
  19310. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19311. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19312. mesh.id = parsedMesh.id;
  19313. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19314. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19315. if (parsedMesh.rotationQuaternion) {
  19316. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19317. }
  19318. else if (parsedMesh.rotation) {
  19319. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19320. }
  19321. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19322. if (parsedMesh.localMatrix) {
  19323. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19324. }
  19325. else if (parsedMesh.pivotMatrix) {
  19326. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19327. }
  19328. mesh.setEnabled(parsedMesh.isEnabled);
  19329. mesh.isVisible = parsedMesh.isVisible;
  19330. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19331. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19332. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19333. if (parsedMesh.applyFog !== undefined) {
  19334. mesh.applyFog = parsedMesh.applyFog;
  19335. }
  19336. if (parsedMesh.pickable !== undefined) {
  19337. mesh.isPickable = parsedMesh.pickable;
  19338. }
  19339. if (parsedMesh.alphaIndex !== undefined) {
  19340. mesh.alphaIndex = parsedMesh.alphaIndex;
  19341. }
  19342. mesh.receiveShadows = parsedMesh.receiveShadows;
  19343. mesh.billboardMode = parsedMesh.billboardMode;
  19344. if (parsedMesh.visibility !== undefined) {
  19345. mesh.visibility = parsedMesh.visibility;
  19346. }
  19347. mesh.checkCollisions = parsedMesh.checkCollisions;
  19348. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19349. // Parent
  19350. if (parsedMesh.parentId) {
  19351. mesh._waitingParentId = parsedMesh.parentId;
  19352. }
  19353. // Actions
  19354. if (parsedMesh.actions !== undefined) {
  19355. mesh._waitingActions = parsedMesh.actions;
  19356. }
  19357. // Geometry
  19358. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19359. if (parsedMesh.delayLoadingFile) {
  19360. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19361. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19362. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19363. if (parsedMesh._binaryInfo) {
  19364. mesh._binaryInfo = parsedMesh._binaryInfo;
  19365. }
  19366. mesh._delayInfo = [];
  19367. if (parsedMesh.hasUVs) {
  19368. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19369. }
  19370. if (parsedMesh.hasUVs2) {
  19371. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19372. }
  19373. if (parsedMesh.hasColors) {
  19374. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19375. }
  19376. if (parsedMesh.hasMatricesIndices) {
  19377. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19378. }
  19379. if (parsedMesh.hasMatricesWeights) {
  19380. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19381. }
  19382. mesh._delayLoadingFunction = importGeometry;
  19383. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19384. mesh._checkDelayState();
  19385. }
  19386. }
  19387. else {
  19388. importGeometry(parsedMesh, mesh);
  19389. }
  19390. // Material
  19391. if (parsedMesh.materialId) {
  19392. mesh.setMaterialByID(parsedMesh.materialId);
  19393. }
  19394. else {
  19395. mesh.material = null;
  19396. }
  19397. // Skeleton
  19398. if (parsedMesh.skeletonId > -1) {
  19399. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19400. }
  19401. // Physics
  19402. if (parsedMesh.physicsImpostor) {
  19403. if (!scene.isPhysicsEnabled()) {
  19404. scene.enablePhysics();
  19405. }
  19406. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19407. }
  19408. // Animations
  19409. if (parsedMesh.animations) {
  19410. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19411. var parsedAnimation = parsedMesh.animations[animationIndex];
  19412. mesh.animations.push(parseAnimation(parsedAnimation));
  19413. }
  19414. }
  19415. if (parsedMesh.autoAnimate) {
  19416. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19417. }
  19418. // Layer Mask
  19419. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19420. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19421. }
  19422. else {
  19423. mesh.layerMask = 0xFFFFFFFF;
  19424. }
  19425. // Instances
  19426. if (parsedMesh.instances) {
  19427. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19428. var parsedInstance = parsedMesh.instances[index];
  19429. var instance = mesh.createInstance(parsedInstance.name);
  19430. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19431. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19432. if (parsedInstance.rotationQuaternion) {
  19433. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19434. }
  19435. else if (parsedInstance.rotation) {
  19436. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19437. }
  19438. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19439. instance.checkCollisions = mesh.checkCollisions;
  19440. if (parsedMesh.animations) {
  19441. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19442. parsedAnimation = parsedMesh.animations[animationIndex];
  19443. instance.animations.push(parseAnimation(parsedAnimation));
  19444. }
  19445. }
  19446. }
  19447. }
  19448. return mesh;
  19449. };
  19450. var parseActions = function (parsedActions, object, scene) {
  19451. var actionManager = new BABYLON.ActionManager(scene);
  19452. if (object === null)
  19453. scene.actionManager = actionManager;
  19454. else
  19455. object.actionManager = actionManager;
  19456. // instanciate a new object
  19457. var instanciate = function (name, params) {
  19458. var newInstance = Object.create(BABYLON[name].prototype);
  19459. newInstance.constructor.apply(newInstance, params);
  19460. return newInstance;
  19461. };
  19462. var parseParameter = function (name, value, target, propertyPath) {
  19463. if (propertyPath === null) {
  19464. // String, boolean or float
  19465. var floatValue = parseFloat(value);
  19466. if (value === "true" || value === "false")
  19467. return value === "true";
  19468. else
  19469. return isNaN(floatValue) ? value : floatValue;
  19470. }
  19471. var effectiveTarget = propertyPath.split(".");
  19472. var values = value.split(",");
  19473. for (var i = 0; i < effectiveTarget.length; i++) {
  19474. target = target[effectiveTarget[i]];
  19475. }
  19476. // Return appropriate value with its type
  19477. if (target instanceof Boolean)
  19478. return values[0] === "true";
  19479. if (target instanceof String)
  19480. return values[0];
  19481. // Parameters with multiple values such as Vector3 etc.
  19482. var split = new Array();
  19483. for (var i = 0; i < values.length; i++)
  19484. split.push(parseFloat(values[i]));
  19485. if (target instanceof BABYLON.Vector3)
  19486. return BABYLON.Vector3.FromArray(split);
  19487. if (target instanceof BABYLON.Vector4)
  19488. return BABYLON.Vector4.FromArray(split);
  19489. if (target instanceof BABYLON.Color3)
  19490. return BABYLON.Color3.FromArray(split);
  19491. if (target instanceof BABYLON.Color4)
  19492. return BABYLON.Color4.FromArray(split);
  19493. return parseFloat(values[0]);
  19494. };
  19495. // traverse graph per trigger
  19496. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19497. if (combineArray === void 0) { combineArray = null; }
  19498. if (parsedAction.detached)
  19499. return;
  19500. var parameters = new Array();
  19501. var target = null;
  19502. var propertyPath = null;
  19503. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19504. // Parameters
  19505. if (parsedAction.type === 2)
  19506. parameters.push(actionManager);
  19507. else
  19508. parameters.push(trigger);
  19509. if (combine) {
  19510. var actions = new Array();
  19511. for (var j = 0; j < parsedAction.combine.length; j++) {
  19512. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19513. }
  19514. parameters.push(actions);
  19515. }
  19516. else {
  19517. for (var i = 0; i < parsedAction.properties.length; i++) {
  19518. var value = parsedAction.properties[i].value;
  19519. var name = parsedAction.properties[i].name;
  19520. if (name === "target")
  19521. value = target = scene.getNodeByName(value);
  19522. else if (name === "parent")
  19523. value = scene.getNodeByName(value);
  19524. else if (name === "sound")
  19525. value = scene.getSoundByName(value);
  19526. else if (name !== "propertyPath") {
  19527. if (parsedAction.type === 2 && name === "operator")
  19528. value = BABYLON.ValueCondition[value];
  19529. else
  19530. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19531. }
  19532. else {
  19533. propertyPath = value;
  19534. }
  19535. parameters.push(value);
  19536. }
  19537. }
  19538. parameters.push(condition);
  19539. // If interpolate value action
  19540. if (parsedAction.name === "InterpolateValueAction") {
  19541. var param = parameters[parameters.length - 2];
  19542. parameters[parameters.length - 1] = param;
  19543. parameters[parameters.length - 2] = condition;
  19544. }
  19545. // Action or condition(s) and not CombineAction
  19546. var newAction = instanciate(parsedAction.name, parameters);
  19547. if (combineArray === null) {
  19548. if (newAction instanceof BABYLON.Condition) {
  19549. condition = newAction;
  19550. newAction = action;
  19551. }
  19552. else {
  19553. condition = null;
  19554. if (action)
  19555. action.then(newAction);
  19556. else
  19557. actionManager.registerAction(newAction);
  19558. }
  19559. }
  19560. else {
  19561. combineArray.push(newAction);
  19562. }
  19563. for (var i = 0; i < parsedAction.children.length; i++)
  19564. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19565. };
  19566. for (var i = 0; i < parsedActions.children.length; i++) {
  19567. var triggerParams;
  19568. var trigger = parsedActions.children[i];
  19569. if (trigger.properties.length > 0) {
  19570. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19571. }
  19572. else
  19573. triggerParams = BABYLON.ActionManager[trigger.name];
  19574. for (var j = 0; j < trigger.children.length; j++)
  19575. traverse(trigger.children[j], triggerParams, null, null);
  19576. }
  19577. };
  19578. var parseSound = function (parsedSound, scene, rootUrl) {
  19579. var soundName = parsedSound.name;
  19580. var soundUrl = rootUrl + soundName;
  19581. var options = {
  19582. autoplay: parsedSound.autoplay,
  19583. loop: parsedSound.loop,
  19584. volume: parsedSound.volume,
  19585. spatialSound: parsedSound.spatialSound,
  19586. maxDistance: parsedSound.maxDistance,
  19587. rolloffFactor: parsedSound.rolloffFactor,
  19588. refDistance: parsedSound.refDistance,
  19589. distanceModel: parsedSound.distanceModel,
  19590. playbackRate: parsedSound.playbackRate
  19591. };
  19592. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19593. scene._removePendingData(newSound);
  19594. }, options);
  19595. scene._addPendingData(newSound);
  19596. if (parsedSound.position) {
  19597. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19598. newSound.setPosition(soundPosition);
  19599. }
  19600. if (parsedSound.isDirectional) {
  19601. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19602. if (parsedSound.localDirectionToMesh) {
  19603. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19604. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19605. }
  19606. }
  19607. if (parsedSound.connectedMeshId) {
  19608. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19609. if (connectedMesh) {
  19610. newSound.attachToMesh(connectedMesh);
  19611. }
  19612. }
  19613. };
  19614. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19615. names = (names instanceof Array) ? names : [names];
  19616. for (var i in names) {
  19617. if (mesh.name === names[i]) {
  19618. hierarchyIds.push(mesh.id);
  19619. return true;
  19620. }
  19621. }
  19622. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19623. hierarchyIds.push(mesh.id);
  19624. return true;
  19625. }
  19626. return false;
  19627. };
  19628. var importVertexData = function (parsedVertexData, geometry) {
  19629. var vertexData = new BABYLON.VertexData();
  19630. // positions
  19631. var positions = parsedVertexData.positions;
  19632. if (positions) {
  19633. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19634. }
  19635. // normals
  19636. var normals = parsedVertexData.normals;
  19637. if (normals) {
  19638. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19639. }
  19640. // uvs
  19641. var uvs = parsedVertexData.uvs;
  19642. if (uvs) {
  19643. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19644. }
  19645. // uv2s
  19646. var uv2s = parsedVertexData.uv2s;
  19647. if (uv2s) {
  19648. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19649. }
  19650. // colors
  19651. var colors = parsedVertexData.colors;
  19652. if (colors) {
  19653. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19654. }
  19655. // matricesIndices
  19656. var matricesIndices = parsedVertexData.matricesIndices;
  19657. if (matricesIndices) {
  19658. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19659. }
  19660. // matricesWeights
  19661. var matricesWeights = parsedVertexData.matricesWeights;
  19662. if (matricesWeights) {
  19663. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19664. }
  19665. // indices
  19666. var indices = parsedVertexData.indices;
  19667. if (indices) {
  19668. vertexData.indices = indices;
  19669. }
  19670. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19671. };
  19672. var importGeometry = function (parsedGeometry, mesh) {
  19673. var scene = mesh.getScene();
  19674. // Geometry
  19675. var geometryId = parsedGeometry.geometryId;
  19676. if (geometryId) {
  19677. var geometry = scene.getGeometryByID(geometryId);
  19678. if (geometry) {
  19679. geometry.applyToMesh(mesh);
  19680. }
  19681. }
  19682. else if (parsedGeometry instanceof ArrayBuffer) {
  19683. var binaryInfo = mesh._binaryInfo;
  19684. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19685. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19686. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19687. }
  19688. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19689. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19690. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19691. }
  19692. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19693. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19695. }
  19696. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19697. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19698. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19699. }
  19700. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19701. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19702. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19703. }
  19704. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19705. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19707. }
  19708. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19709. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19711. }
  19712. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19713. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19714. mesh.setIndices(indicesData);
  19715. }
  19716. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19717. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19718. mesh.subMeshes = [];
  19719. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19720. var materialIndex = subMeshesData[(i * 5) + 0];
  19721. var verticesStart = subMeshesData[(i * 5) + 1];
  19722. var verticesCount = subMeshesData[(i * 5) + 2];
  19723. var indexStart = subMeshesData[(i * 5) + 3];
  19724. var indexCount = subMeshesData[(i * 5) + 4];
  19725. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19726. }
  19727. }
  19728. }
  19729. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19730. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19731. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19732. if (parsedGeometry.uvs) {
  19733. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19734. }
  19735. if (parsedGeometry.uvs2) {
  19736. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19737. }
  19738. if (parsedGeometry.colors) {
  19739. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19740. }
  19741. if (parsedGeometry.matricesIndices) {
  19742. if (!parsedGeometry.matricesIndices._isExpanded) {
  19743. var floatIndices = [];
  19744. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19745. var matricesIndex = parsedGeometry.matricesIndices[i];
  19746. floatIndices.push(matricesIndex & 0x000000FF);
  19747. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19748. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19749. floatIndices.push(matricesIndex >> 24);
  19750. }
  19751. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19752. }
  19753. else {
  19754. delete parsedGeometry.matricesIndices._isExpanded;
  19755. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19756. }
  19757. }
  19758. if (parsedGeometry.matricesWeights) {
  19759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19760. }
  19761. mesh.setIndices(parsedGeometry.indices);
  19762. // SubMeshes
  19763. if (parsedGeometry.subMeshes) {
  19764. mesh.subMeshes = [];
  19765. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19766. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19767. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19768. }
  19769. }
  19770. }
  19771. // Flat shading
  19772. if (mesh._shouldGenerateFlatShading) {
  19773. mesh.convertToFlatShadedMesh();
  19774. delete mesh._shouldGenerateFlatShading;
  19775. }
  19776. // Update
  19777. mesh.computeWorldMatrix(true);
  19778. // Octree
  19779. if (scene._selectionOctree) {
  19780. scene._selectionOctree.addMesh(mesh);
  19781. }
  19782. };
  19783. BABYLON.SceneLoader.RegisterPlugin({
  19784. extensions: ".babylon",
  19785. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19786. var parsedData = JSON.parse(data);
  19787. var loadedSkeletonsIds = [];
  19788. var loadedMaterialsIds = [];
  19789. var hierarchyIds = [];
  19790. for (var index = 0; index < parsedData.meshes.length; index++) {
  19791. var parsedMesh = parsedData.meshes[index];
  19792. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19793. if (meshesNames instanceof Array) {
  19794. // Remove found mesh name from list.
  19795. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19796. }
  19797. // Material ?
  19798. if (parsedMesh.materialId) {
  19799. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19800. if (!materialFound) {
  19801. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19802. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19803. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19804. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19805. var subMatId = parsedMultiMaterial.materials[matIndex];
  19806. loadedMaterialsIds.push(subMatId);
  19807. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19808. }
  19809. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19810. parseMultiMaterial(parsedMultiMaterial, scene);
  19811. materialFound = true;
  19812. break;
  19813. }
  19814. }
  19815. }
  19816. if (!materialFound) {
  19817. loadedMaterialsIds.push(parsedMesh.materialId);
  19818. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19819. }
  19820. }
  19821. // Skeleton ?
  19822. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19823. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19824. if (!skeletonAlreadyLoaded) {
  19825. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19826. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19827. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19828. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19829. loadedSkeletonsIds.push(parsedSkeleton.id);
  19830. }
  19831. }
  19832. }
  19833. }
  19834. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19835. meshes.push(mesh);
  19836. }
  19837. }
  19838. for (index = 0; index < scene.meshes.length; index++) {
  19839. var currentMesh = scene.meshes[index];
  19840. if (currentMesh._waitingParentId) {
  19841. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19842. currentMesh._waitingParentId = undefined;
  19843. }
  19844. }
  19845. // Particles
  19846. if (parsedData.particleSystems) {
  19847. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19848. var parsedParticleSystem = parsedData.particleSystems[index];
  19849. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19850. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19851. }
  19852. }
  19853. }
  19854. return true;
  19855. },
  19856. load: function (scene, data, rootUrl) {
  19857. var parsedData = JSON.parse(data);
  19858. // Scene
  19859. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19860. scene.autoClear = parsedData.autoClear;
  19861. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19862. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19863. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19864. // Fog
  19865. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19866. scene.fogMode = parsedData.fogMode;
  19867. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19868. scene.fogStart = parsedData.fogStart;
  19869. scene.fogEnd = parsedData.fogEnd;
  19870. scene.fogDensity = parsedData.fogDensity;
  19871. }
  19872. for (var index = 0; index < parsedData.lights.length; index++) {
  19873. var parsedLight = parsedData.lights[index];
  19874. parseLight(parsedLight, scene);
  19875. }
  19876. // Materials
  19877. if (parsedData.materials) {
  19878. for (index = 0; index < parsedData.materials.length; index++) {
  19879. var parsedMaterial = parsedData.materials[index];
  19880. parseMaterial(parsedMaterial, scene, rootUrl);
  19881. }
  19882. }
  19883. if (parsedData.multiMaterials) {
  19884. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19885. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19886. parseMultiMaterial(parsedMultiMaterial, scene);
  19887. }
  19888. }
  19889. // Skeletons
  19890. if (parsedData.skeletons) {
  19891. for (index = 0; index < parsedData.skeletons.length; index++) {
  19892. var parsedSkeleton = parsedData.skeletons[index];
  19893. parseSkeleton(parsedSkeleton, scene);
  19894. }
  19895. }
  19896. // Geometries
  19897. var geometries = parsedData.geometries;
  19898. if (geometries) {
  19899. // Boxes
  19900. var boxes = geometries.boxes;
  19901. if (boxes) {
  19902. for (index = 0; index < boxes.length; index++) {
  19903. var parsedBox = boxes[index];
  19904. parseBox(parsedBox, scene);
  19905. }
  19906. }
  19907. // Spheres
  19908. var spheres = geometries.spheres;
  19909. if (spheres) {
  19910. for (index = 0; index < spheres.length; index++) {
  19911. var parsedSphere = spheres[index];
  19912. parseSphere(parsedSphere, scene);
  19913. }
  19914. }
  19915. // Cylinders
  19916. var cylinders = geometries.cylinders;
  19917. if (cylinders) {
  19918. for (index = 0; index < cylinders.length; index++) {
  19919. var parsedCylinder = cylinders[index];
  19920. parseCylinder(parsedCylinder, scene);
  19921. }
  19922. }
  19923. // Toruses
  19924. var toruses = geometries.toruses;
  19925. if (toruses) {
  19926. for (index = 0; index < toruses.length; index++) {
  19927. var parsedTorus = toruses[index];
  19928. parseTorus(parsedTorus, scene);
  19929. }
  19930. }
  19931. // Grounds
  19932. var grounds = geometries.grounds;
  19933. if (grounds) {
  19934. for (index = 0; index < grounds.length; index++) {
  19935. var parsedGround = grounds[index];
  19936. parseGround(parsedGround, scene);
  19937. }
  19938. }
  19939. // Planes
  19940. var planes = geometries.planes;
  19941. if (planes) {
  19942. for (index = 0; index < planes.length; index++) {
  19943. var parsedPlane = planes[index];
  19944. parsePlane(parsedPlane, scene);
  19945. }
  19946. }
  19947. // TorusKnots
  19948. var torusKnots = geometries.torusKnots;
  19949. if (torusKnots) {
  19950. for (index = 0; index < torusKnots.length; index++) {
  19951. var parsedTorusKnot = torusKnots[index];
  19952. parseTorusKnot(parsedTorusKnot, scene);
  19953. }
  19954. }
  19955. // VertexData
  19956. var vertexData = geometries.vertexData;
  19957. if (vertexData) {
  19958. for (index = 0; index < vertexData.length; index++) {
  19959. var parsedVertexData = vertexData[index];
  19960. parseVertexData(parsedVertexData, scene, rootUrl);
  19961. }
  19962. }
  19963. }
  19964. for (index = 0; index < parsedData.meshes.length; index++) {
  19965. var parsedMesh = parsedData.meshes[index];
  19966. parseMesh(parsedMesh, scene, rootUrl);
  19967. }
  19968. for (index = 0; index < parsedData.cameras.length; index++) {
  19969. var parsedCamera = parsedData.cameras[index];
  19970. parseCamera(parsedCamera, scene);
  19971. }
  19972. if (parsedData.activeCameraID) {
  19973. scene.setActiveCameraByID(parsedData.activeCameraID);
  19974. }
  19975. for (index = 0; index < scene.cameras.length; index++) {
  19976. var camera = scene.cameras[index];
  19977. if (camera._waitingParentId) {
  19978. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19979. camera._waitingParentId = undefined;
  19980. }
  19981. }
  19982. for (index = 0; index < scene.lights.length; index++) {
  19983. var light = scene.lights[index];
  19984. if (light._waitingParentId) {
  19985. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19986. light._waitingParentId = undefined;
  19987. }
  19988. }
  19989. // Sounds
  19990. if (parsedData.sounds) {
  19991. for (index = 0; index < parsedData.sounds.length; index++) {
  19992. var parsedSound = parsedData.sounds[index];
  19993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19994. parseSound(parsedSound, scene, rootUrl);
  19995. }
  19996. else {
  19997. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19998. }
  19999. }
  20000. }
  20001. for (index = 0; index < scene.meshes.length; index++) {
  20002. var mesh = scene.meshes[index];
  20003. if (mesh._waitingParentId) {
  20004. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20005. mesh._waitingParentId = undefined;
  20006. }
  20007. if (mesh._waitingActions) {
  20008. parseActions(mesh._waitingActions, mesh, scene);
  20009. mesh._waitingActions = undefined;
  20010. }
  20011. }
  20012. // Particles Systems
  20013. if (parsedData.particleSystems) {
  20014. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20015. var parsedParticleSystem = parsedData.particleSystems[index];
  20016. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20017. }
  20018. }
  20019. // Lens flares
  20020. if (parsedData.lensFlareSystems) {
  20021. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20022. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20023. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20024. }
  20025. }
  20026. // Shadows
  20027. if (parsedData.shadowGenerators) {
  20028. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20029. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20030. parseShadowGenerator(parsedShadowGenerator, scene);
  20031. }
  20032. }
  20033. // Actions (scene)
  20034. if (parsedData.actions) {
  20035. parseActions(parsedData.actions, null, scene);
  20036. }
  20037. // Finish
  20038. return true;
  20039. }
  20040. });
  20041. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20042. })(BABYLON || (BABYLON = {}));
  20043. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20044. (function (BABYLON) {
  20045. // Unique ID when we import meshes from Babylon to CSG
  20046. var currentCSGMeshId = 0;
  20047. // # class Vertex
  20048. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20049. // one to provide additional features like texture coordinates and vertex
  20050. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20051. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20052. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20053. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20054. // is not used anywhere else.
  20055. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20056. var Vertex = (function () {
  20057. function Vertex(pos, normal, uv) {
  20058. this.pos = pos;
  20059. this.normal = normal;
  20060. this.uv = uv;
  20061. }
  20062. Vertex.prototype.clone = function () {
  20063. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20064. };
  20065. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20066. // orientation of a polygon is flipped.
  20067. Vertex.prototype.flip = function () {
  20068. this.normal = this.normal.scale(-1);
  20069. };
  20070. // Create a new vertex between this vertex and `other` by linearly
  20071. // interpolating all properties using a parameter of `t`. Subclasses should
  20072. // override this to interpolate additional properties.
  20073. Vertex.prototype.interpolate = function (other, t) {
  20074. 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));
  20075. };
  20076. return Vertex;
  20077. })();
  20078. // # class Plane
  20079. // Represents a plane in 3D space.
  20080. var Plane = (function () {
  20081. function Plane(normal, w) {
  20082. this.normal = normal;
  20083. this.w = w;
  20084. }
  20085. Plane.FromPoints = function (a, b, c) {
  20086. var v0 = c.subtract(a);
  20087. var v1 = b.subtract(a);
  20088. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20089. return null;
  20090. }
  20091. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20092. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20093. };
  20094. Plane.prototype.clone = function () {
  20095. return new Plane(this.normal.clone(), this.w);
  20096. };
  20097. Plane.prototype.flip = function () {
  20098. this.normal.scaleInPlace(-1);
  20099. this.w = -this.w;
  20100. };
  20101. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20102. // fragments in the appropriate lists. Coplanar polygons go into either
  20103. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20104. // respect to this plane. Polygons in front or in back of this plane go into
  20105. // either `front` or `back`.
  20106. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20107. var COPLANAR = 0;
  20108. var FRONT = 1;
  20109. var BACK = 2;
  20110. var SPANNING = 3;
  20111. // Classify each point as well as the entire polygon into one of the above
  20112. // four classes.
  20113. var polygonType = 0;
  20114. var types = [];
  20115. for (var i = 0; i < polygon.vertices.length; i++) {
  20116. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20117. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20118. polygonType |= type;
  20119. types.push(type);
  20120. }
  20121. switch (polygonType) {
  20122. case COPLANAR:
  20123. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20124. break;
  20125. case FRONT:
  20126. front.push(polygon);
  20127. break;
  20128. case BACK:
  20129. back.push(polygon);
  20130. break;
  20131. case SPANNING:
  20132. var f = [], b = [];
  20133. for (i = 0; i < polygon.vertices.length; i++) {
  20134. var j = (i + 1) % polygon.vertices.length;
  20135. var ti = types[i], tj = types[j];
  20136. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20137. if (ti != BACK)
  20138. f.push(vi);
  20139. if (ti != FRONT)
  20140. b.push(ti != BACK ? vi.clone() : vi);
  20141. if ((ti | tj) == SPANNING) {
  20142. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20143. var v = vi.interpolate(vj, t);
  20144. f.push(v);
  20145. b.push(v.clone());
  20146. }
  20147. }
  20148. if (f.length >= 3) {
  20149. var poly = new Polygon(f, polygon.shared);
  20150. if (poly.plane)
  20151. front.push(poly);
  20152. }
  20153. if (b.length >= 3) {
  20154. poly = new Polygon(b, polygon.shared);
  20155. if (poly.plane)
  20156. back.push(poly);
  20157. }
  20158. break;
  20159. }
  20160. };
  20161. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20162. // point is on the plane.
  20163. Plane.EPSILON = 1e-5;
  20164. return Plane;
  20165. })();
  20166. // # class Polygon
  20167. // Represents a convex polygon. The vertices used to initialize a polygon must
  20168. // be coplanar and form a convex loop.
  20169. //
  20170. // Each convex polygon has a `shared` property, which is shared between all
  20171. // polygons that are clones of each other or were split from the same polygon.
  20172. // This can be used to define per-polygon properties (such as surface color).
  20173. var Polygon = (function () {
  20174. function Polygon(vertices, shared) {
  20175. this.vertices = vertices;
  20176. this.shared = shared;
  20177. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20178. }
  20179. Polygon.prototype.clone = function () {
  20180. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20181. return new Polygon(vertices, this.shared);
  20182. };
  20183. Polygon.prototype.flip = function () {
  20184. this.vertices.reverse().map(function (v) {
  20185. v.flip();
  20186. });
  20187. this.plane.flip();
  20188. };
  20189. return Polygon;
  20190. })();
  20191. // # class Node
  20192. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20193. // by picking a polygon to split along. That polygon (and all other coplanar
  20194. // polygons) are added directly to that node and the other polygons are added to
  20195. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20196. // no distinction between internal and leaf nodes.
  20197. var Node = (function () {
  20198. function Node(polygons) {
  20199. this.plane = null;
  20200. this.front = null;
  20201. this.back = null;
  20202. this.polygons = [];
  20203. if (polygons) {
  20204. this.build(polygons);
  20205. }
  20206. }
  20207. Node.prototype.clone = function () {
  20208. var node = new Node();
  20209. node.plane = this.plane && this.plane.clone();
  20210. node.front = this.front && this.front.clone();
  20211. node.back = this.back && this.back.clone();
  20212. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20213. return node;
  20214. };
  20215. // Convert solid space to empty space and empty space to solid space.
  20216. Node.prototype.invert = function () {
  20217. for (var i = 0; i < this.polygons.length; i++) {
  20218. this.polygons[i].flip();
  20219. }
  20220. if (this.plane) {
  20221. this.plane.flip();
  20222. }
  20223. if (this.front) {
  20224. this.front.invert();
  20225. }
  20226. if (this.back) {
  20227. this.back.invert();
  20228. }
  20229. var temp = this.front;
  20230. this.front = this.back;
  20231. this.back = temp;
  20232. };
  20233. // Recursively remove all polygons in `polygons` that are inside this BSP
  20234. // tree.
  20235. Node.prototype.clipPolygons = function (polygons) {
  20236. if (!this.plane)
  20237. return polygons.slice();
  20238. var front = [], back = [];
  20239. for (var i = 0; i < polygons.length; i++) {
  20240. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20241. }
  20242. if (this.front) {
  20243. front = this.front.clipPolygons(front);
  20244. }
  20245. if (this.back) {
  20246. back = this.back.clipPolygons(back);
  20247. }
  20248. else {
  20249. back = [];
  20250. }
  20251. return front.concat(back);
  20252. };
  20253. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20254. // `bsp`.
  20255. Node.prototype.clipTo = function (bsp) {
  20256. this.polygons = bsp.clipPolygons(this.polygons);
  20257. if (this.front)
  20258. this.front.clipTo(bsp);
  20259. if (this.back)
  20260. this.back.clipTo(bsp);
  20261. };
  20262. // Return a list of all polygons in this BSP tree.
  20263. Node.prototype.allPolygons = function () {
  20264. var polygons = this.polygons.slice();
  20265. if (this.front)
  20266. polygons = polygons.concat(this.front.allPolygons());
  20267. if (this.back)
  20268. polygons = polygons.concat(this.back.allPolygons());
  20269. return polygons;
  20270. };
  20271. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20272. // new polygons are filtered down to the bottom of the tree and become new
  20273. // nodes there. Each set of polygons is partitioned using the first polygon
  20274. // (no heuristic is used to pick a good split).
  20275. Node.prototype.build = function (polygons) {
  20276. if (!polygons.length)
  20277. return;
  20278. if (!this.plane)
  20279. this.plane = polygons[0].plane.clone();
  20280. var front = [], back = [];
  20281. for (var i = 0; i < polygons.length; i++) {
  20282. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20283. }
  20284. if (front.length) {
  20285. if (!this.front)
  20286. this.front = new Node();
  20287. this.front.build(front);
  20288. }
  20289. if (back.length) {
  20290. if (!this.back)
  20291. this.back = new Node();
  20292. this.back.build(back);
  20293. }
  20294. };
  20295. return Node;
  20296. })();
  20297. var CSG = (function () {
  20298. function CSG() {
  20299. this.polygons = new Array();
  20300. }
  20301. // Convert BABYLON.Mesh to BABYLON.CSG
  20302. CSG.FromMesh = function (mesh) {
  20303. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20304. if (mesh instanceof BABYLON.Mesh) {
  20305. mesh.computeWorldMatrix(true);
  20306. var matrix = mesh.getWorldMatrix();
  20307. var meshPosition = mesh.position.clone();
  20308. var meshRotation = mesh.rotation.clone();
  20309. var meshScaling = mesh.scaling.clone();
  20310. }
  20311. else {
  20312. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20313. }
  20314. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20315. var subMeshes = mesh.subMeshes;
  20316. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20317. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20318. vertices = [];
  20319. for (var j = 0; j < 3; j++) {
  20320. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20321. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20322. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20323. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20324. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20325. vertex = new Vertex(position, normal, uv);
  20326. vertices.push(vertex);
  20327. }
  20328. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20329. // To handle the case of degenerated triangle
  20330. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20331. if (polygon.plane)
  20332. polygons.push(polygon);
  20333. }
  20334. }
  20335. var csg = CSG.FromPolygons(polygons);
  20336. csg.matrix = matrix;
  20337. csg.position = meshPosition;
  20338. csg.rotation = meshRotation;
  20339. csg.scaling = meshScaling;
  20340. currentCSGMeshId++;
  20341. return csg;
  20342. };
  20343. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20344. CSG.FromPolygons = function (polygons) {
  20345. var csg = new BABYLON.CSG();
  20346. csg.polygons = polygons;
  20347. return csg;
  20348. };
  20349. CSG.prototype.clone = function () {
  20350. var csg = new BABYLON.CSG();
  20351. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20352. csg.copyTransformAttributes(this);
  20353. return csg;
  20354. };
  20355. CSG.prototype.toPolygons = function () {
  20356. return this.polygons;
  20357. };
  20358. CSG.prototype.union = function (csg) {
  20359. var a = new Node(this.clone().polygons);
  20360. var b = new Node(csg.clone().polygons);
  20361. a.clipTo(b);
  20362. b.clipTo(a);
  20363. b.invert();
  20364. b.clipTo(a);
  20365. b.invert();
  20366. a.build(b.allPolygons());
  20367. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20368. };
  20369. CSG.prototype.unionInPlace = function (csg) {
  20370. var a = new Node(this.polygons);
  20371. var b = new Node(csg.polygons);
  20372. a.clipTo(b);
  20373. b.clipTo(a);
  20374. b.invert();
  20375. b.clipTo(a);
  20376. b.invert();
  20377. a.build(b.allPolygons());
  20378. this.polygons = a.allPolygons();
  20379. };
  20380. CSG.prototype.subtract = function (csg) {
  20381. var a = new Node(this.clone().polygons);
  20382. var b = new Node(csg.clone().polygons);
  20383. a.invert();
  20384. a.clipTo(b);
  20385. b.clipTo(a);
  20386. b.invert();
  20387. b.clipTo(a);
  20388. b.invert();
  20389. a.build(b.allPolygons());
  20390. a.invert();
  20391. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20392. };
  20393. CSG.prototype.subtractInPlace = function (csg) {
  20394. var a = new Node(this.polygons);
  20395. var b = new Node(csg.polygons);
  20396. a.invert();
  20397. a.clipTo(b);
  20398. b.clipTo(a);
  20399. b.invert();
  20400. b.clipTo(a);
  20401. b.invert();
  20402. a.build(b.allPolygons());
  20403. a.invert();
  20404. this.polygons = a.allPolygons();
  20405. };
  20406. CSG.prototype.intersect = function (csg) {
  20407. var a = new Node(this.clone().polygons);
  20408. var b = new Node(csg.clone().polygons);
  20409. a.invert();
  20410. b.clipTo(a);
  20411. b.invert();
  20412. a.clipTo(b);
  20413. b.clipTo(a);
  20414. a.build(b.allPolygons());
  20415. a.invert();
  20416. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20417. };
  20418. CSG.prototype.intersectInPlace = function (csg) {
  20419. var a = new Node(this.polygons);
  20420. var b = new Node(csg.polygons);
  20421. a.invert();
  20422. b.clipTo(a);
  20423. b.invert();
  20424. a.clipTo(b);
  20425. b.clipTo(a);
  20426. a.build(b.allPolygons());
  20427. a.invert();
  20428. this.polygons = a.allPolygons();
  20429. };
  20430. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20431. // not modified.
  20432. CSG.prototype.inverse = function () {
  20433. var csg = this.clone();
  20434. csg.inverseInPlace();
  20435. return csg;
  20436. };
  20437. CSG.prototype.inverseInPlace = function () {
  20438. this.polygons.map(function (p) {
  20439. p.flip();
  20440. });
  20441. };
  20442. // This is used to keep meshes transformations so they can be restored
  20443. // when we build back a Babylon Mesh
  20444. // NB : All CSG operations are performed in world coordinates
  20445. CSG.prototype.copyTransformAttributes = function (csg) {
  20446. this.matrix = csg.matrix;
  20447. this.position = csg.position;
  20448. this.rotation = csg.rotation;
  20449. this.scaling = csg.scaling;
  20450. return this;
  20451. };
  20452. // Build Raw mesh from CSG
  20453. // Coordinates here are in world space
  20454. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20455. var matrix = this.matrix.clone();
  20456. matrix.invert();
  20457. 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;
  20458. if (keepSubMeshes) {
  20459. // Sort Polygons, since subMeshes are indices range
  20460. polygons.sort(function (a, b) {
  20461. if (a.shared.meshId === b.shared.meshId) {
  20462. return a.shared.subMeshId - b.shared.subMeshId;
  20463. }
  20464. else {
  20465. return a.shared.meshId - b.shared.meshId;
  20466. }
  20467. });
  20468. }
  20469. for (var i = 0, il = polygons.length; i < il; i++) {
  20470. polygon = polygons[i];
  20471. // Building SubMeshes
  20472. if (!subMesh_dict[polygon.shared.meshId]) {
  20473. subMesh_dict[polygon.shared.meshId] = {};
  20474. }
  20475. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20476. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20477. indexStart: +Infinity,
  20478. indexEnd: -Infinity,
  20479. materialIndex: polygon.shared.materialIndex
  20480. };
  20481. }
  20482. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20483. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20484. polygonIndices[0] = 0;
  20485. polygonIndices[1] = j - 1;
  20486. polygonIndices[2] = j;
  20487. for (var k = 0; k < 3; k++) {
  20488. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20489. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20490. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20491. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20492. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20493. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20494. // Check if 2 points can be merged
  20495. 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)) {
  20496. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20497. uvs.push(uv.x, uv.y);
  20498. normals.push(normal.x, normal.y, normal.z);
  20499. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20500. }
  20501. indices.push(vertex_idx);
  20502. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20503. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20504. currentIndex++;
  20505. }
  20506. }
  20507. }
  20508. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20509. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20510. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20511. mesh.setIndices(indices);
  20512. if (keepSubMeshes) {
  20513. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20514. var materialIndexOffset = 0, materialMaxIndex;
  20515. mesh.subMeshes.length = 0;
  20516. for (var m in subMesh_dict) {
  20517. materialMaxIndex = -1;
  20518. for (var sm in subMesh_dict[m]) {
  20519. subMesh_obj = subMesh_dict[m][sm];
  20520. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20521. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20522. }
  20523. materialIndexOffset += ++materialMaxIndex;
  20524. }
  20525. }
  20526. return mesh;
  20527. };
  20528. // Build Mesh from CSG taking material and transforms into account
  20529. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20530. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20531. mesh.material = material;
  20532. mesh.position.copyFrom(this.position);
  20533. mesh.rotation.copyFrom(this.rotation);
  20534. mesh.scaling.copyFrom(this.scaling);
  20535. mesh.computeWorldMatrix(true);
  20536. return mesh;
  20537. };
  20538. return CSG;
  20539. })();
  20540. BABYLON.CSG = CSG;
  20541. })(BABYLON || (BABYLON = {}));
  20542. //# sourceMappingURL=babylon.csg.js.map
  20543. var BABYLON;
  20544. (function (BABYLON) {
  20545. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20546. __extends(OculusDistortionCorrectionPostProcess, _super);
  20547. //ANY
  20548. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20549. var _this = this;
  20550. _super.call(this, name, "oculusDistortionCorrection", [
  20551. 'LensCenter',
  20552. 'Scale',
  20553. 'ScaleIn',
  20554. 'HmdWarpParam'
  20555. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20556. this._isRightEye = isRightEye;
  20557. this._distortionFactors = cameraSettings.DistortionK;
  20558. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20559. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20560. this.onSizeChanged = function () {
  20561. _this.aspectRatio = _this.width * .5 / _this.height;
  20562. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20563. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20564. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20565. };
  20566. this.onApply = function (effect) {
  20567. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20568. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20569. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20570. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20571. };
  20572. }
  20573. return OculusDistortionCorrectionPostProcess;
  20574. })(BABYLON.PostProcess);
  20575. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20576. })(BABYLON || (BABYLON = {}));
  20577. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20578. // 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
  20579. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20580. var BABYLON;
  20581. (function (BABYLON) {
  20582. (function (JoystickAxis) {
  20583. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20584. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20585. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20586. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20587. var JoystickAxis = BABYLON.JoystickAxis;
  20588. var VirtualJoystick = (function () {
  20589. function VirtualJoystick(leftJoystick) {
  20590. var _this = this;
  20591. if (leftJoystick) {
  20592. this._leftJoystick = true;
  20593. }
  20594. else {
  20595. this._leftJoystick = false;
  20596. }
  20597. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20598. VirtualJoystick._globalJoystickIndex++;
  20599. // By default left & right arrow keys are moving the X
  20600. // and up & down keys are moving the Y
  20601. this._axisTargetedByLeftAndRight = 0 /* X */;
  20602. this._axisTargetedByUpAndDown = 1 /* Y */;
  20603. this.reverseLeftRight = false;
  20604. this.reverseUpDown = false;
  20605. // collections of pointers
  20606. this._touches = new BABYLON.VirtualJoystick.Collection();
  20607. this.deltaPosition = BABYLON.Vector3.Zero();
  20608. this._joystickSensibility = 25;
  20609. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20610. this._rotationSpeed = 25;
  20611. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20612. this._rotateOnAxisRelativeToMesh = false;
  20613. // injecting a canvas element on top of the canvas 3D game
  20614. if (!VirtualJoystick.vjCanvas) {
  20615. window.addEventListener("resize", function () {
  20616. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20617. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20618. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20619. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20620. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20621. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20622. }, false);
  20623. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20624. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20625. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20626. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20627. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20628. VirtualJoystick.vjCanvas.style.width = "100%";
  20629. VirtualJoystick.vjCanvas.style.height = "100%";
  20630. VirtualJoystick.vjCanvas.style.position = "absolute";
  20631. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20632. VirtualJoystick.vjCanvas.style.top = "0px";
  20633. VirtualJoystick.vjCanvas.style.left = "0px";
  20634. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20635. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20636. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20637. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20638. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20639. document.body.appendChild(VirtualJoystick.vjCanvas);
  20640. }
  20641. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20642. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20643. this.pressed = false;
  20644. // default joystick color
  20645. this._joystickColor = "cyan";
  20646. this._joystickPointerID = -1;
  20647. // current joystick position
  20648. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20649. // origin joystick position
  20650. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20651. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20652. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20653. _this._onPointerDown(evt);
  20654. }, false);
  20655. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20656. _this._onPointerMove(evt);
  20657. }, false);
  20658. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20659. _this._onPointerUp(evt);
  20660. }, false);
  20661. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20662. _this._onPointerUp(evt);
  20663. }, false);
  20664. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20665. evt.preventDefault(); // Disables system menu
  20666. }, false);
  20667. requestAnimationFrame(function () {
  20668. _this._drawVirtualJoystick();
  20669. });
  20670. }
  20671. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20672. this._joystickSensibility = newJoystickSensibility;
  20673. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20674. };
  20675. VirtualJoystick.prototype._onPointerDown = function (e) {
  20676. var positionOnScreenCondition;
  20677. e.preventDefault();
  20678. if (this._leftJoystick === true) {
  20679. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20680. }
  20681. else {
  20682. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20683. }
  20684. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20685. // First contact will be dedicated to the virtual joystick
  20686. this._joystickPointerID = e.pointerId;
  20687. this._joystickPointerStartPos.x = e.clientX;
  20688. this._joystickPointerStartPos.y = e.clientY;
  20689. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20690. this._deltaJoystickVector.x = 0;
  20691. this._deltaJoystickVector.y = 0;
  20692. this.pressed = true;
  20693. this._touches.add(e.pointerId.toString(), e);
  20694. }
  20695. else {
  20696. // You can only trigger the action buttons with a joystick declared
  20697. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20698. this._action();
  20699. this._touches.add(e.pointerId.toString(), e);
  20700. }
  20701. }
  20702. };
  20703. VirtualJoystick.prototype._onPointerMove = function (e) {
  20704. // If the current pointer is the one associated to the joystick (first touch contact)
  20705. if (this._joystickPointerID == e.pointerId) {
  20706. this._joystickPointerPos.x = e.clientX;
  20707. this._joystickPointerPos.y = e.clientY;
  20708. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20709. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20710. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20711. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20712. switch (this._axisTargetedByLeftAndRight) {
  20713. case 0 /* X */:
  20714. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20715. break;
  20716. case 1 /* Y */:
  20717. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20718. break;
  20719. case 2 /* Z */:
  20720. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20721. break;
  20722. }
  20723. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20724. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20725. switch (this._axisTargetedByUpAndDown) {
  20726. case 0 /* X */:
  20727. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20728. break;
  20729. case 1 /* Y */:
  20730. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20731. break;
  20732. case 2 /* Z */:
  20733. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20734. break;
  20735. }
  20736. }
  20737. else {
  20738. if (this._touches.item(e.pointerId.toString())) {
  20739. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20740. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20741. }
  20742. }
  20743. };
  20744. VirtualJoystick.prototype._onPointerUp = function (e) {
  20745. this._clearCanvas();
  20746. if (this._joystickPointerID == e.pointerId) {
  20747. this._joystickPointerID = -1;
  20748. this.pressed = false;
  20749. }
  20750. this._deltaJoystickVector.x = 0;
  20751. this._deltaJoystickVector.y = 0;
  20752. this._touches.remove(e.pointerId.toString());
  20753. };
  20754. /**
  20755. * Change the color of the virtual joystick
  20756. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20757. */
  20758. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20759. this._joystickColor = newColor;
  20760. };
  20761. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20762. this._action = action;
  20763. };
  20764. // Define which axis you'd like to control for left & right
  20765. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20766. switch (axis) {
  20767. case 0 /* X */:
  20768. case 1 /* Y */:
  20769. case 2 /* Z */:
  20770. this._axisTargetedByLeftAndRight = axis;
  20771. break;
  20772. default:
  20773. this._axisTargetedByLeftAndRight = 0 /* X */;
  20774. break;
  20775. }
  20776. };
  20777. // Define which axis you'd like to control for up & down
  20778. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20779. switch (axis) {
  20780. case 0 /* X */:
  20781. case 1 /* Y */:
  20782. case 2 /* Z */:
  20783. this._axisTargetedByUpAndDown = axis;
  20784. break;
  20785. default:
  20786. this._axisTargetedByUpAndDown = 1 /* Y */;
  20787. break;
  20788. }
  20789. };
  20790. VirtualJoystick.prototype._clearCanvas = function () {
  20791. if (this._leftJoystick) {
  20792. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20793. }
  20794. else {
  20795. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20796. }
  20797. };
  20798. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20799. var _this = this;
  20800. if (this.pressed) {
  20801. this._clearCanvas();
  20802. this._touches.forEach(function (touch) {
  20803. if (touch.pointerId === _this._joystickPointerID) {
  20804. VirtualJoystick.vjCanvasContext.beginPath();
  20805. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20806. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20807. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20808. VirtualJoystick.vjCanvasContext.stroke();
  20809. VirtualJoystick.vjCanvasContext.beginPath();
  20810. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20811. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20812. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20813. VirtualJoystick.vjCanvasContext.stroke();
  20814. VirtualJoystick.vjCanvasContext.beginPath();
  20815. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20816. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20817. VirtualJoystick.vjCanvasContext.stroke();
  20818. }
  20819. else {
  20820. VirtualJoystick.vjCanvasContext.beginPath();
  20821. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20822. VirtualJoystick.vjCanvasContext.beginPath();
  20823. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20824. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20825. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20826. VirtualJoystick.vjCanvasContext.stroke();
  20827. }
  20828. ;
  20829. });
  20830. }
  20831. requestAnimationFrame(function () {
  20832. _this._drawVirtualJoystick();
  20833. });
  20834. };
  20835. VirtualJoystick.prototype.releaseCanvas = function () {
  20836. if (VirtualJoystick.vjCanvas) {
  20837. document.body.removeChild(VirtualJoystick.vjCanvas);
  20838. VirtualJoystick.vjCanvas = null;
  20839. }
  20840. };
  20841. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20842. VirtualJoystick._globalJoystickIndex = 0;
  20843. return VirtualJoystick;
  20844. })();
  20845. BABYLON.VirtualJoystick = VirtualJoystick;
  20846. })(BABYLON || (BABYLON = {}));
  20847. var BABYLON;
  20848. (function (BABYLON) {
  20849. var VirtualJoystick;
  20850. (function (VirtualJoystick) {
  20851. var Collection = (function () {
  20852. function Collection() {
  20853. this._count = 0;
  20854. this._collection = new Array();
  20855. }
  20856. Collection.prototype.Count = function () {
  20857. return this._count;
  20858. };
  20859. Collection.prototype.add = function (key, item) {
  20860. if (this._collection[key] != undefined) {
  20861. return undefined;
  20862. }
  20863. this._collection[key] = item;
  20864. return ++this._count;
  20865. };
  20866. Collection.prototype.remove = function (key) {
  20867. if (this._collection[key] == undefined) {
  20868. return undefined;
  20869. }
  20870. delete this._collection[key];
  20871. return --this._count;
  20872. };
  20873. Collection.prototype.item = function (key) {
  20874. return this._collection[key];
  20875. };
  20876. Collection.prototype.forEach = function (block) {
  20877. var key;
  20878. for (key in this._collection) {
  20879. if (this._collection.hasOwnProperty(key)) {
  20880. block(this._collection[key]);
  20881. }
  20882. }
  20883. };
  20884. return Collection;
  20885. })();
  20886. VirtualJoystick.Collection = Collection;
  20887. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20888. })(BABYLON || (BABYLON = {}));
  20889. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20890. var BABYLON;
  20891. (function (BABYLON) {
  20892. var OculusRiftDevKit2013_Metric = {
  20893. HResolution: 1280,
  20894. VResolution: 800,
  20895. HScreenSize: 0.149759993,
  20896. VScreenSize: 0.0935999975,
  20897. VScreenCenter: 0.0467999987,
  20898. EyeToScreenDistance: 0.0410000011,
  20899. LensSeparationDistance: 0.0635000020,
  20900. InterpupillaryDistance: 0.0640000030,
  20901. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20902. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20903. PostProcessScaleFactor: 1.714605507808412,
  20904. LensCenterOffset: 0.151976421
  20905. };
  20906. var _OculusInnerCamera = (function (_super) {
  20907. __extends(_OculusInnerCamera, _super);
  20908. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20909. _super.call(this, name, position, scene);
  20910. this._workMatrix = new BABYLON.Matrix();
  20911. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20912. // Constants
  20913. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20914. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20915. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20916. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20917. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20918. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20919. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20920. // Postprocess
  20921. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20922. }
  20923. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20924. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20925. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20926. return this._projectionMatrix;
  20927. };
  20928. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20930. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20931. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20932. // Computing target and final matrix
  20933. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20934. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20935. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20936. return this._viewMatrix;
  20937. };
  20938. return _OculusInnerCamera;
  20939. })(BABYLON.FreeCamera);
  20940. var OculusCamera = (function (_super) {
  20941. __extends(OculusCamera, _super);
  20942. function OculusCamera(name, position, scene) {
  20943. _super.call(this, name, position, scene);
  20944. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20945. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20946. this.subCameras.push(this._leftCamera);
  20947. this.subCameras.push(this._rightCamera);
  20948. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20949. }
  20950. OculusCamera.prototype._update = function () {
  20951. this._leftCamera.position.copyFrom(this.position);
  20952. this._rightCamera.position.copyFrom(this.position);
  20953. this._updateCamera(this._leftCamera);
  20954. this._updateCamera(this._rightCamera);
  20955. _super.prototype._update.call(this);
  20956. };
  20957. OculusCamera.prototype._updateCamera = function (camera) {
  20958. camera.minZ = this.minZ;
  20959. camera.maxZ = this.maxZ;
  20960. camera.rotation.x = this.rotation.x;
  20961. camera.rotation.y = this.rotation.y;
  20962. camera.rotation.z = this.rotation.z;
  20963. };
  20964. // Oculus events
  20965. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20966. var yaw = evt.alpha / 180 * Math.PI;
  20967. var pitch = evt.beta / 180 * Math.PI;
  20968. var roll = evt.gamma / 180 * Math.PI;
  20969. if (!this._offsetOrientation) {
  20970. this._offsetOrientation = {
  20971. yaw: yaw,
  20972. pitch: pitch,
  20973. roll: roll
  20974. };
  20975. return;
  20976. }
  20977. else {
  20978. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20979. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20980. this.rotation.z += this._offsetOrientation.roll - roll;
  20981. this._offsetOrientation.yaw = yaw;
  20982. this._offsetOrientation.pitch = pitch;
  20983. this._offsetOrientation.roll = roll;
  20984. }
  20985. };
  20986. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20987. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20988. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20989. };
  20990. OculusCamera.prototype.detachControl = function (element) {
  20991. _super.prototype.detachControl.call(this, element);
  20992. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20993. };
  20994. return OculusCamera;
  20995. })(BABYLON.FreeCamera);
  20996. BABYLON.OculusCamera = OculusCamera;
  20997. })(BABYLON || (BABYLON = {}));
  20998. //# sourceMappingURL=babylon.oculusCamera.js.map
  20999. var BABYLON;
  21000. (function (BABYLON) {
  21001. var OculusRiftDevKit2013_Metric = {
  21002. HResolution: 1280,
  21003. VResolution: 800,
  21004. HScreenSize: 0.149759993,
  21005. VScreenSize: 0.0935999975,
  21006. VScreenCenter: 0.0467999987,
  21007. EyeToScreenDistance: 0.0410000011,
  21008. LensSeparationDistance: 0.0635000020,
  21009. InterpupillaryDistance: 0.0640000030,
  21010. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21011. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21012. PostProcessScaleFactor: 1.714605507808412,
  21013. LensCenterOffset: 0.151976421
  21014. };
  21015. var _OculusInnerGamepadCamera = (function (_super) {
  21016. __extends(_OculusInnerGamepadCamera, _super);
  21017. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21018. _super.call(this, name, position, scene);
  21019. this._workMatrix = new BABYLON.Matrix();
  21020. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21021. // Constants
  21022. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21023. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21024. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21025. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21026. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21027. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21028. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21029. // Postprocess
  21030. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21031. }
  21032. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21033. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21034. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21035. return this._projectionMatrix;
  21036. };
  21037. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21038. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21039. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21040. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21041. // Computing target and final matrix
  21042. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21043. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21044. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21045. return this._viewMatrix;
  21046. };
  21047. return _OculusInnerGamepadCamera;
  21048. })(BABYLON.FreeCamera);
  21049. var OculusGamepadCamera = (function (_super) {
  21050. __extends(OculusGamepadCamera, _super);
  21051. function OculusGamepadCamera(name, position, scene) {
  21052. var _this = this;
  21053. _super.call(this, name, position, scene);
  21054. this.angularSensibility = 200;
  21055. this.moveSensibility = 75;
  21056. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21057. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21058. this.subCameras.push(this._leftCamera);
  21059. this.subCameras.push(this._rightCamera);
  21060. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21061. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21062. _this._onNewGameConnected(gamepad);
  21063. });
  21064. }
  21065. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21066. // Only the first gamepad can control the camera
  21067. if (gamepad.index === 0) {
  21068. this._gamepad = gamepad;
  21069. }
  21070. };
  21071. OculusGamepadCamera.prototype._update = function () {
  21072. this._leftCamera.position.copyFrom(this.position);
  21073. this._rightCamera.position.copyFrom(this.position);
  21074. this._updateCamera(this._leftCamera);
  21075. this._updateCamera(this._rightCamera);
  21076. _super.prototype._update.call(this);
  21077. };
  21078. OculusGamepadCamera.prototype._checkInputs = function () {
  21079. if (!this._gamepad) {
  21080. return;
  21081. }
  21082. var LSValues = this._gamepad.leftStick;
  21083. var normalizedLX = LSValues.x / this.moveSensibility;
  21084. var normalizedLY = LSValues.y / this.moveSensibility;
  21085. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21086. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21087. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21088. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21089. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21090. };
  21091. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21092. camera.minZ = this.minZ;
  21093. camera.maxZ = this.maxZ;
  21094. camera.rotation.x = this.rotation.x;
  21095. camera.rotation.y = this.rotation.y;
  21096. camera.rotation.z = this.rotation.z;
  21097. };
  21098. // Oculus events
  21099. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21100. var yaw = evt.alpha / 180 * Math.PI;
  21101. var pitch = evt.beta / 180 * Math.PI;
  21102. var roll = evt.gamma / 180 * Math.PI;
  21103. if (!this._offsetOrientation) {
  21104. this._offsetOrientation = {
  21105. yaw: yaw,
  21106. pitch: pitch,
  21107. roll: roll
  21108. };
  21109. return;
  21110. }
  21111. else {
  21112. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21113. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21114. this.rotation.z += this._offsetOrientation.roll - roll;
  21115. this._offsetOrientation.yaw = yaw;
  21116. this._offsetOrientation.pitch = pitch;
  21117. this._offsetOrientation.roll = roll;
  21118. }
  21119. };
  21120. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21121. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21122. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21123. };
  21124. OculusGamepadCamera.prototype.detachControl = function (element) {
  21125. _super.prototype.detachControl.call(this, element);
  21126. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21127. };
  21128. OculusGamepadCamera.prototype.dispose = function () {
  21129. this._gamepads.dispose();
  21130. _super.prototype.dispose.call(this);
  21131. };
  21132. return OculusGamepadCamera;
  21133. })(BABYLON.FreeCamera);
  21134. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21135. })(BABYLON || (BABYLON = {}));
  21136. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21137. var BABYLON;
  21138. (function (BABYLON) {
  21139. // We're mainly based on the logic defined into the FreeCamera code
  21140. var VirtualJoysticksCamera = (function (_super) {
  21141. __extends(VirtualJoysticksCamera, _super);
  21142. function VirtualJoysticksCamera(name, position, scene) {
  21143. _super.call(this, name, position, scene);
  21144. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21145. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21146. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21147. this._leftjoystick.setJoystickSensibility(0.15);
  21148. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21149. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21150. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21151. this._rightjoystick.reverseUpDown = true;
  21152. this._rightjoystick.setJoystickSensibility(0.05);
  21153. this._rightjoystick.setJoystickColor("yellow");
  21154. }
  21155. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21156. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21157. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21158. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21159. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21160. if (!this._leftjoystick.pressed) {
  21161. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21162. }
  21163. if (!this._rightjoystick.pressed) {
  21164. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21165. }
  21166. };
  21167. VirtualJoysticksCamera.prototype.dispose = function () {
  21168. this._leftjoystick.releaseCanvas();
  21169. _super.prototype.dispose.call(this);
  21170. };
  21171. return VirtualJoysticksCamera;
  21172. })(BABYLON.FreeCamera);
  21173. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21174. })(BABYLON || (BABYLON = {}));
  21175. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21176. var BABYLON;
  21177. (function (BABYLON) {
  21178. var ShaderMaterial = (function (_super) {
  21179. __extends(ShaderMaterial, _super);
  21180. function ShaderMaterial(name, scene, shaderPath, options) {
  21181. _super.call(this, name, scene);
  21182. this._textures = new Array();
  21183. this._floats = new Array();
  21184. this._floatsArrays = {};
  21185. this._colors3 = new Array();
  21186. this._colors4 = new Array();
  21187. this._vectors2 = new Array();
  21188. this._vectors3 = new Array();
  21189. this._matrices = new Array();
  21190. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21191. this._shaderPath = shaderPath;
  21192. options.needAlphaBlending = options.needAlphaBlending || false;
  21193. options.needAlphaTesting = options.needAlphaTesting || false;
  21194. options.attributes = options.attributes || ["position", "normal", "uv"];
  21195. options.uniforms = options.uniforms || ["worldViewProjection"];
  21196. options.samplers = options.samplers || [];
  21197. this._options = options;
  21198. }
  21199. ShaderMaterial.prototype.needAlphaBlending = function () {
  21200. return this._options.needAlphaBlending;
  21201. };
  21202. ShaderMaterial.prototype.needAlphaTesting = function () {
  21203. return this._options.needAlphaTesting;
  21204. };
  21205. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21206. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21207. this._options.uniforms.push(uniformName);
  21208. }
  21209. };
  21210. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21211. if (this._options.samplers.indexOf(name) === -1) {
  21212. this._options.samplers.push(name);
  21213. }
  21214. this._textures[name] = texture;
  21215. return this;
  21216. };
  21217. ShaderMaterial.prototype.setFloat = function (name, value) {
  21218. this._checkUniform(name);
  21219. this._floats[name] = value;
  21220. return this;
  21221. };
  21222. ShaderMaterial.prototype.setFloats = function (name, value) {
  21223. this._checkUniform(name);
  21224. this._floatsArrays[name] = value;
  21225. return this;
  21226. };
  21227. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21228. this._checkUniform(name);
  21229. this._colors3[name] = value;
  21230. return this;
  21231. };
  21232. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21233. this._checkUniform(name);
  21234. this._colors4[name] = value;
  21235. return this;
  21236. };
  21237. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21238. this._checkUniform(name);
  21239. this._vectors2[name] = value;
  21240. return this;
  21241. };
  21242. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21243. this._checkUniform(name);
  21244. this._vectors3[name] = value;
  21245. return this;
  21246. };
  21247. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21248. this._checkUniform(name);
  21249. this._matrices[name] = value;
  21250. return this;
  21251. };
  21252. ShaderMaterial.prototype.isReady = function () {
  21253. var scene = this.getScene();
  21254. var engine = scene.getEngine();
  21255. if (!this.checkReadyOnEveryCall) {
  21256. if (this._renderId === scene.getRenderId()) {
  21257. return true;
  21258. }
  21259. }
  21260. var previousEffect = this._effect;
  21261. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21262. if (!this._effect.isReady()) {
  21263. return false;
  21264. }
  21265. if (previousEffect !== this._effect) {
  21266. scene.resetCachedMaterial();
  21267. }
  21268. this._renderId = scene.getRenderId();
  21269. return true;
  21270. };
  21271. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21272. var scene = this.getScene();
  21273. if (this._options.uniforms.indexOf("world") !== -1) {
  21274. this._effect.setMatrix("world", world);
  21275. }
  21276. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21277. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21278. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21279. }
  21280. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21281. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21282. }
  21283. };
  21284. ShaderMaterial.prototype.bind = function (world) {
  21285. // Std values
  21286. this.bindOnlyWorldMatrix(world);
  21287. if (this.getScene().getCachedMaterial() !== this) {
  21288. if (this._options.uniforms.indexOf("view") !== -1) {
  21289. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21290. }
  21291. if (this._options.uniforms.indexOf("projection") !== -1) {
  21292. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21293. }
  21294. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21295. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21296. }
  21297. for (var name in this._textures) {
  21298. this._effect.setTexture(name, this._textures[name]);
  21299. }
  21300. for (name in this._floats) {
  21301. this._effect.setFloat(name, this._floats[name]);
  21302. }
  21303. for (name in this._floatsArrays) {
  21304. this._effect.setArray(name, this._floatsArrays[name]);
  21305. }
  21306. for (name in this._colors3) {
  21307. this._effect.setColor3(name, this._colors3[name]);
  21308. }
  21309. for (name in this._colors4) {
  21310. var color = this._colors4[name];
  21311. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21312. }
  21313. for (name in this._vectors2) {
  21314. this._effect.setVector2(name, this._vectors2[name]);
  21315. }
  21316. for (name in this._vectors3) {
  21317. this._effect.setVector3(name, this._vectors3[name]);
  21318. }
  21319. for (name in this._matrices) {
  21320. this._effect.setMatrix(name, this._matrices[name]);
  21321. }
  21322. }
  21323. _super.prototype.bind.call(this, world, null);
  21324. };
  21325. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21326. for (var name in this._textures) {
  21327. this._textures[name].dispose();
  21328. }
  21329. this._textures = [];
  21330. _super.prototype.dispose.call(this, forceDisposeEffect);
  21331. };
  21332. return ShaderMaterial;
  21333. })(BABYLON.Material);
  21334. BABYLON.ShaderMaterial = ShaderMaterial;
  21335. })(BABYLON || (BABYLON = {}));
  21336. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21337. (function (BABYLON) {
  21338. var VertexData = (function () {
  21339. function VertexData() {
  21340. }
  21341. VertexData.prototype.set = function (data, kind) {
  21342. switch (kind) {
  21343. case BABYLON.VertexBuffer.PositionKind:
  21344. this.positions = data;
  21345. break;
  21346. case BABYLON.VertexBuffer.NormalKind:
  21347. this.normals = data;
  21348. break;
  21349. case BABYLON.VertexBuffer.UVKind:
  21350. this.uvs = data;
  21351. break;
  21352. case BABYLON.VertexBuffer.UV2Kind:
  21353. this.uv2s = data;
  21354. break;
  21355. case BABYLON.VertexBuffer.ColorKind:
  21356. this.colors = data;
  21357. break;
  21358. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21359. this.matricesIndices = data;
  21360. break;
  21361. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21362. this.matricesWeights = data;
  21363. break;
  21364. }
  21365. };
  21366. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21367. this._applyTo(mesh, updatable);
  21368. };
  21369. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21370. this._applyTo(geometry, updatable);
  21371. };
  21372. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21373. this._update(mesh);
  21374. };
  21375. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21376. this._update(geometry);
  21377. };
  21378. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21379. if (this.positions) {
  21380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21381. }
  21382. if (this.normals) {
  21383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21384. }
  21385. if (this.uvs) {
  21386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21387. }
  21388. if (this.uv2s) {
  21389. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21390. }
  21391. if (this.colors) {
  21392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21393. }
  21394. if (this.matricesIndices) {
  21395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21396. }
  21397. if (this.matricesWeights) {
  21398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21399. }
  21400. if (this.indices) {
  21401. meshOrGeometry.setIndices(this.indices);
  21402. }
  21403. };
  21404. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21405. if (this.positions) {
  21406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21407. }
  21408. if (this.normals) {
  21409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21410. }
  21411. if (this.uvs) {
  21412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21413. }
  21414. if (this.uv2s) {
  21415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21416. }
  21417. if (this.colors) {
  21418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21419. }
  21420. if (this.matricesIndices) {
  21421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21422. }
  21423. if (this.matricesWeights) {
  21424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21425. }
  21426. if (this.indices) {
  21427. meshOrGeometry.setIndices(this.indices);
  21428. }
  21429. };
  21430. VertexData.prototype.transform = function (matrix) {
  21431. var transformed = BABYLON.Vector3.Zero();
  21432. if (this.positions) {
  21433. var position = BABYLON.Vector3.Zero();
  21434. for (var index = 0; index < this.positions.length; index += 3) {
  21435. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21436. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21437. this.positions[index] = transformed.x;
  21438. this.positions[index + 1] = transformed.y;
  21439. this.positions[index + 2] = transformed.z;
  21440. }
  21441. }
  21442. if (this.normals) {
  21443. var normal = BABYLON.Vector3.Zero();
  21444. for (index = 0; index < this.normals.length; index += 3) {
  21445. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21446. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21447. this.normals[index] = transformed.x;
  21448. this.normals[index + 1] = transformed.y;
  21449. this.normals[index + 2] = transformed.z;
  21450. }
  21451. }
  21452. };
  21453. VertexData.prototype.merge = function (other) {
  21454. if (other.indices) {
  21455. if (!this.indices) {
  21456. this.indices = [];
  21457. }
  21458. var offset = this.positions ? this.positions.length / 3 : 0;
  21459. for (var index = 0; index < other.indices.length; index++) {
  21460. this.indices.push(other.indices[index] + offset);
  21461. }
  21462. }
  21463. if (other.positions) {
  21464. if (!this.positions) {
  21465. this.positions = [];
  21466. }
  21467. for (index = 0; index < other.positions.length; index++) {
  21468. this.positions.push(other.positions[index]);
  21469. }
  21470. }
  21471. if (other.normals) {
  21472. if (!this.normals) {
  21473. this.normals = [];
  21474. }
  21475. for (index = 0; index < other.normals.length; index++) {
  21476. this.normals.push(other.normals[index]);
  21477. }
  21478. }
  21479. if (other.uvs) {
  21480. if (!this.uvs) {
  21481. this.uvs = [];
  21482. }
  21483. for (index = 0; index < other.uvs.length; index++) {
  21484. this.uvs.push(other.uvs[index]);
  21485. }
  21486. }
  21487. if (other.uv2s) {
  21488. if (!this.uv2s) {
  21489. this.uv2s = [];
  21490. }
  21491. for (index = 0; index < other.uv2s.length; index++) {
  21492. this.uv2s.push(other.uv2s[index]);
  21493. }
  21494. }
  21495. if (other.matricesIndices) {
  21496. if (!this.matricesIndices) {
  21497. this.matricesIndices = [];
  21498. }
  21499. for (index = 0; index < other.matricesIndices.length; index++) {
  21500. this.matricesIndices.push(other.matricesIndices[index]);
  21501. }
  21502. }
  21503. if (other.matricesWeights) {
  21504. if (!this.matricesWeights) {
  21505. this.matricesWeights = [];
  21506. }
  21507. for (index = 0; index < other.matricesWeights.length; index++) {
  21508. this.matricesWeights.push(other.matricesWeights[index]);
  21509. }
  21510. }
  21511. if (other.colors) {
  21512. if (!this.colors) {
  21513. this.colors = [];
  21514. }
  21515. for (index = 0; index < other.colors.length; index++) {
  21516. this.colors.push(other.colors[index]);
  21517. }
  21518. }
  21519. };
  21520. // Statics
  21521. VertexData.ExtractFromMesh = function (mesh) {
  21522. return VertexData._ExtractFrom(mesh);
  21523. };
  21524. VertexData.ExtractFromGeometry = function (geometry) {
  21525. return VertexData._ExtractFrom(geometry);
  21526. };
  21527. VertexData._ExtractFrom = function (meshOrGeometry) {
  21528. var result = new VertexData();
  21529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21530. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21531. }
  21532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21533. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21534. }
  21535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21536. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21537. }
  21538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21539. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21540. }
  21541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21542. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21543. }
  21544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21545. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21546. }
  21547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21548. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21549. }
  21550. result.indices = meshOrGeometry.getIndices();
  21551. return result;
  21552. };
  21553. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21554. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21555. closeArray = closeArray || false;
  21556. closePath = closePath || false;
  21557. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21558. offset = offset || defaultOffset;
  21559. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21560. var positions = [];
  21561. var indices = [];
  21562. var normals = [];
  21563. var uvs = [];
  21564. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21565. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21566. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21567. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21568. var minlg; // minimal length among all paths from pathArray
  21569. var lg = []; // array of path lengths : nb of vertex per path
  21570. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21571. var p; // path iterator
  21572. var i; // point iterator
  21573. var j; // point iterator
  21574. // if single path in pathArray
  21575. if (pathArray.length < 2) {
  21576. var ar1 = [];
  21577. var ar2 = [];
  21578. for (i = 0; i < pathArray[0].length - offset; i++) {
  21579. ar1.push(pathArray[0][i]);
  21580. ar2.push(pathArray[0][i + offset]);
  21581. }
  21582. pathArray = [ar1, ar2];
  21583. }
  21584. // positions and horizontal distances (u)
  21585. var idc = 0;
  21586. minlg = pathArray[0].length;
  21587. for (p = 0; p < pathArray.length; p++) {
  21588. uTotalDistance[p] = 0;
  21589. us[p] = [0];
  21590. var path = pathArray[p];
  21591. var l = path.length;
  21592. minlg = (minlg < l) ? minlg : l;
  21593. lg[p] = l;
  21594. idx[p] = idc;
  21595. j = 0;
  21596. while (j < l) {
  21597. positions.push(path[j].x, path[j].y, path[j].z);
  21598. if (j > 0) {
  21599. var vectlg = path[j].subtract(path[j - 1]).length();
  21600. var dist = vectlg + uTotalDistance[p];
  21601. us[p].push(dist);
  21602. uTotalDistance[p] = dist;
  21603. }
  21604. j++;
  21605. }
  21606. if (closePath) {
  21607. vectlg = path[0].subtract(path[j - 1]).length();
  21608. dist = vectlg + uTotalDistance[p];
  21609. uTotalDistance[p] = dist;
  21610. }
  21611. idc += l;
  21612. }
  21613. for (i = 0; i < minlg; i++) {
  21614. vTotalDistance[i] = 0;
  21615. vs[i] = [0];
  21616. var path1;
  21617. var path2;
  21618. for (p = 0; p < pathArray.length - 1; p++) {
  21619. path1 = pathArray[p];
  21620. path2 = pathArray[p + 1];
  21621. vectlg = path2[i].subtract(path1[i]).length();
  21622. dist = vectlg + vTotalDistance[i];
  21623. vs[i].push(dist);
  21624. vTotalDistance[i] = dist;
  21625. }
  21626. if (closeArray) {
  21627. path1 = pathArray[p];
  21628. path2 = pathArray[0];
  21629. vectlg = path2[i].subtract(path1[i]).length();
  21630. dist = vectlg + vTotalDistance[i];
  21631. vTotalDistance[i] = dist;
  21632. }
  21633. }
  21634. // uvs
  21635. var u;
  21636. var v;
  21637. for (p = 0; p < pathArray.length; p++) {
  21638. for (i = 0; i < minlg; i++) {
  21639. u = us[p][i] / uTotalDistance[p];
  21640. v = vs[i][p] / vTotalDistance[i];
  21641. uvs.push(u, v);
  21642. }
  21643. }
  21644. // indices
  21645. p = 0; // path index
  21646. var pi = 0; // positions array index
  21647. var l1 = lg[p] - 1; // path1 length
  21648. var l2 = lg[p + 1] - 1; // path2 length
  21649. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21650. var shft = idx[1] - idx[0]; // shift
  21651. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21652. var t1; // two consecutive triangles, so 4 points : point1
  21653. var t2; // point2
  21654. var t3; // point3
  21655. var t4; // point4
  21656. while (pi <= min && p < path1nb) {
  21657. // 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
  21658. t1 = pi;
  21659. t2 = pi + shft;
  21660. t3 = pi + 1;
  21661. t4 = pi + shft + 1;
  21662. indices.push(pi, pi + shft, pi + 1);
  21663. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21664. pi += 1;
  21665. if (pi === min) {
  21666. if (closePath) {
  21667. indices.push(pi, pi + shft, idx[p]);
  21668. indices.push(idx[p] + shft, idx[p], pi + shft);
  21669. t3 = idx[p];
  21670. t4 = idx[p] + shft;
  21671. }
  21672. p++;
  21673. if (p === lg.length - 1) {
  21674. shft = idx[0] - idx[p];
  21675. l1 = lg[p] - 1;
  21676. l2 = lg[0] - 1;
  21677. }
  21678. else {
  21679. shft = idx[p + 1] - idx[p];
  21680. l1 = lg[p] - 1;
  21681. l2 = lg[p + 1] - 1;
  21682. }
  21683. pi = idx[p];
  21684. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21685. }
  21686. }
  21687. // normals
  21688. VertexData.ComputeNormals(positions, indices, normals);
  21689. // sides
  21690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21691. // Result
  21692. var vertexData = new VertexData();
  21693. vertexData.indices = indices;
  21694. vertexData.positions = positions;
  21695. vertexData.normals = normals;
  21696. vertexData.uvs = uvs;
  21697. return vertexData;
  21698. };
  21699. VertexData.CreateBox = function (size, sideOrientation) {
  21700. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21701. var normalsSource = [
  21702. new BABYLON.Vector3(0, 0, 1),
  21703. new BABYLON.Vector3(0, 0, -1),
  21704. new BABYLON.Vector3(1, 0, 0),
  21705. new BABYLON.Vector3(-1, 0, 0),
  21706. new BABYLON.Vector3(0, 1, 0),
  21707. new BABYLON.Vector3(0, -1, 0)
  21708. ];
  21709. var indices = [];
  21710. var positions = [];
  21711. var normals = [];
  21712. var uvs = [];
  21713. size = size || 1;
  21714. for (var index = 0; index < normalsSource.length; index++) {
  21715. var normal = normalsSource[index];
  21716. // Get two vectors perpendicular to the face normal and to each other.
  21717. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21718. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21719. // Six indices (two triangles) per face.
  21720. var verticesLength = positions.length / 3;
  21721. indices.push(verticesLength);
  21722. indices.push(verticesLength + 1);
  21723. indices.push(verticesLength + 2);
  21724. indices.push(verticesLength);
  21725. indices.push(verticesLength + 2);
  21726. indices.push(verticesLength + 3);
  21727. // Four vertices per face.
  21728. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21729. positions.push(vertex.x, vertex.y, vertex.z);
  21730. normals.push(normal.x, normal.y, normal.z);
  21731. uvs.push(1.0, 1.0);
  21732. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21733. positions.push(vertex.x, vertex.y, vertex.z);
  21734. normals.push(normal.x, normal.y, normal.z);
  21735. uvs.push(0.0, 1.0);
  21736. vertex = normal.add(side1).add(side2).scale(size / 2);
  21737. positions.push(vertex.x, vertex.y, vertex.z);
  21738. normals.push(normal.x, normal.y, normal.z);
  21739. uvs.push(0.0, 0.0);
  21740. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21741. positions.push(vertex.x, vertex.y, vertex.z);
  21742. normals.push(normal.x, normal.y, normal.z);
  21743. uvs.push(1.0, 0.0);
  21744. }
  21745. // sides
  21746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21747. // Result
  21748. var vertexData = new VertexData();
  21749. vertexData.indices = indices;
  21750. vertexData.positions = positions;
  21751. vertexData.normals = normals;
  21752. vertexData.uvs = uvs;
  21753. return vertexData;
  21754. };
  21755. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21756. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21757. segments = segments || 32;
  21758. diameter = diameter || 1;
  21759. var radius = diameter / 2;
  21760. var totalZRotationSteps = 2 + segments;
  21761. var totalYRotationSteps = 2 * totalZRotationSteps;
  21762. var indices = [];
  21763. var positions = [];
  21764. var normals = [];
  21765. var uvs = [];
  21766. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21767. var normalizedZ = zRotationStep / totalZRotationSteps;
  21768. var angleZ = (normalizedZ * Math.PI);
  21769. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21770. var normalizedY = yRotationStep / totalYRotationSteps;
  21771. var angleY = normalizedY * Math.PI * 2;
  21772. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21773. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21774. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21775. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21776. var vertex = complete.scale(radius);
  21777. var normal = BABYLON.Vector3.Normalize(vertex);
  21778. positions.push(vertex.x, vertex.y, vertex.z);
  21779. normals.push(normal.x, normal.y, normal.z);
  21780. uvs.push(normalizedZ, normalizedY);
  21781. }
  21782. if (zRotationStep > 0) {
  21783. var verticesCount = positions.length / 3;
  21784. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21785. indices.push((firstIndex));
  21786. indices.push((firstIndex + 1));
  21787. indices.push(firstIndex + totalYRotationSteps + 1);
  21788. indices.push((firstIndex + totalYRotationSteps + 1));
  21789. indices.push((firstIndex + 1));
  21790. indices.push((firstIndex + totalYRotationSteps + 2));
  21791. }
  21792. }
  21793. }
  21794. // Sides
  21795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21796. // Result
  21797. var vertexData = new VertexData();
  21798. vertexData.indices = indices;
  21799. vertexData.positions = positions;
  21800. vertexData.normals = normals;
  21801. vertexData.uvs = uvs;
  21802. return vertexData;
  21803. };
  21804. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21805. if (subdivisions === void 0) { subdivisions = 1; }
  21806. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21807. var radiusTop = diameterTop / 2;
  21808. var radiusBottom = diameterBottom / 2;
  21809. var indices = [];
  21810. var positions = [];
  21811. var normals = [];
  21812. var uvs = [];
  21813. height = height || 1;
  21814. diameterTop = diameterTop || 0.5;
  21815. diameterBottom = diameterBottom || 1;
  21816. tessellation = tessellation || 16;
  21817. subdivisions = subdivisions || 1;
  21818. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21819. var getCircleVector = function (i) {
  21820. var angle = (i * 2.0 * Math.PI / tessellation);
  21821. var dx = Math.cos(angle);
  21822. var dz = Math.sin(angle);
  21823. return new BABYLON.Vector3(dx, 0, dz);
  21824. };
  21825. var createCylinderCap = function (isTop) {
  21826. var radius = isTop ? radiusTop : radiusBottom;
  21827. if (radius === 0) {
  21828. return;
  21829. }
  21830. var vbase = positions.length / 3;
  21831. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21832. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21833. if (!isTop) {
  21834. offset.scaleInPlace(-1);
  21835. textureScale.x = -textureScale.x;
  21836. }
  21837. for (var i = 0; i < tessellation; i++) {
  21838. var circleVector = getCircleVector(i);
  21839. var position = circleVector.scale(radius).add(offset);
  21840. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21841. positions.push(position.x, position.y, position.z);
  21842. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21843. }
  21844. for (i = 0; i < tessellation - 2; i++) {
  21845. if (!isTop) {
  21846. indices.push(vbase);
  21847. indices.push(vbase + (i + 2) % tessellation);
  21848. indices.push(vbase + (i + 1) % tessellation);
  21849. }
  21850. else {
  21851. indices.push(vbase);
  21852. indices.push(vbase + (i + 1) % tessellation);
  21853. indices.push(vbase + (i + 2) % tessellation);
  21854. }
  21855. }
  21856. };
  21857. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21858. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21859. var stride = tessellation + 1;
  21860. for (var i = 0; i <= tessellation; i++) {
  21861. var circleVector = getCircleVector(i);
  21862. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21863. var position, radius = radiusBottom;
  21864. for (var s = 0; s <= subdivisions; s++) {
  21865. // Update variables
  21866. position = circleVector.scale(radius);
  21867. position.addInPlace(base.add(offset.scale(s)));
  21868. textureCoordinate.y += 1 / subdivisions;
  21869. radius += (radiusTop - radiusBottom) / subdivisions;
  21870. // Push in arrays
  21871. positions.push(position.x, position.y, position.z);
  21872. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21873. }
  21874. }
  21875. subdivisions += 1;
  21876. for (s = 0; s < subdivisions - 1; s++) {
  21877. for (i = 0; i <= tessellation; i++) {
  21878. indices.push(i * subdivisions + s);
  21879. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21880. indices.push(i * subdivisions + (s + 1));
  21881. indices.push(i * subdivisions + (s + 1));
  21882. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21883. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21884. }
  21885. }
  21886. // Create flat triangle fan caps to seal the top and bottom.
  21887. createCylinderCap(true);
  21888. createCylinderCap(false);
  21889. // Normals
  21890. VertexData.ComputeNormals(positions, indices, normals);
  21891. // Sides
  21892. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21893. // Result
  21894. var vertexData = new VertexData();
  21895. vertexData.indices = indices;
  21896. vertexData.positions = positions;
  21897. vertexData.normals = normals;
  21898. vertexData.uvs = uvs;
  21899. return vertexData;
  21900. };
  21901. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21902. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21903. var indices = [];
  21904. var positions = [];
  21905. var normals = [];
  21906. var uvs = [];
  21907. diameter = diameter || 1;
  21908. thickness = thickness || 0.5;
  21909. tessellation = tessellation || 16;
  21910. var stride = tessellation + 1;
  21911. for (var i = 0; i <= tessellation; i++) {
  21912. var u = i / tessellation;
  21913. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21914. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21915. for (var j = 0; j <= tessellation; j++) {
  21916. var v = 1 - j / tessellation;
  21917. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21918. var dx = Math.cos(innerAngle);
  21919. var dy = Math.sin(innerAngle);
  21920. // Create a vertex.
  21921. var normal = new BABYLON.Vector3(dx, dy, 0);
  21922. var position = normal.scale(thickness / 2);
  21923. var textureCoordinate = new BABYLON.Vector2(u, v);
  21924. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21925. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21926. positions.push(position.x, position.y, position.z);
  21927. normals.push(normal.x, normal.y, normal.z);
  21928. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21929. // And create indices for two triangles.
  21930. var nextI = (i + 1) % stride;
  21931. var nextJ = (j + 1) % stride;
  21932. indices.push(i * stride + j);
  21933. indices.push(i * stride + nextJ);
  21934. indices.push(nextI * stride + j);
  21935. indices.push(i * stride + nextJ);
  21936. indices.push(nextI * stride + nextJ);
  21937. indices.push(nextI * stride + j);
  21938. }
  21939. }
  21940. // Sides
  21941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21942. // Result
  21943. var vertexData = new VertexData();
  21944. vertexData.indices = indices;
  21945. vertexData.positions = positions;
  21946. vertexData.normals = normals;
  21947. vertexData.uvs = uvs;
  21948. return vertexData;
  21949. };
  21950. VertexData.CreateLines = function (points) {
  21951. var indices = [];
  21952. var positions = [];
  21953. for (var index = 0; index < points.length; index++) {
  21954. positions.push(points[index].x, points[index].y, points[index].z);
  21955. if (index > 0) {
  21956. indices.push(index - 1);
  21957. indices.push(index);
  21958. }
  21959. }
  21960. // Result
  21961. var vertexData = new VertexData();
  21962. vertexData.indices = indices;
  21963. vertexData.positions = positions;
  21964. return vertexData;
  21965. };
  21966. VertexData.CreateGround = function (width, height, subdivisions) {
  21967. var indices = [];
  21968. var positions = [];
  21969. var normals = [];
  21970. var uvs = [];
  21971. var row, col;
  21972. width = width || 1;
  21973. height = height || 1;
  21974. subdivisions = subdivisions || 1;
  21975. for (row = 0; row <= subdivisions; row++) {
  21976. for (col = 0; col <= subdivisions; col++) {
  21977. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21978. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21979. positions.push(position.x, position.y, position.z);
  21980. normals.push(normal.x, normal.y, normal.z);
  21981. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21982. }
  21983. }
  21984. for (row = 0; row < subdivisions; row++) {
  21985. for (col = 0; col < subdivisions; col++) {
  21986. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21987. indices.push(col + 1 + row * (subdivisions + 1));
  21988. indices.push(col + row * (subdivisions + 1));
  21989. indices.push(col + (row + 1) * (subdivisions + 1));
  21990. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21991. indices.push(col + row * (subdivisions + 1));
  21992. }
  21993. }
  21994. // Result
  21995. var vertexData = new VertexData();
  21996. vertexData.indices = indices;
  21997. vertexData.positions = positions;
  21998. vertexData.normals = normals;
  21999. vertexData.uvs = uvs;
  22000. return vertexData;
  22001. };
  22002. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22003. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22004. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22005. var indices = [];
  22006. var positions = [];
  22007. var normals = [];
  22008. var uvs = [];
  22009. var row, col, tileRow, tileCol;
  22010. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22011. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22012. precision.w = (precision.w < 1) ? 1 : precision.w;
  22013. precision.h = (precision.h < 1) ? 1 : precision.h;
  22014. var tileSize = {
  22015. 'w': (xmax - xmin) / subdivisions.w,
  22016. 'h': (zmax - zmin) / subdivisions.h
  22017. };
  22018. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22019. // Indices
  22020. var base = positions.length / 3;
  22021. var rowLength = precision.w + 1;
  22022. for (row = 0; row < precision.h; row++) {
  22023. for (col = 0; col < precision.w; col++) {
  22024. var square = [
  22025. base + col + row * rowLength,
  22026. base + (col + 1) + row * rowLength,
  22027. base + (col + 1) + (row + 1) * rowLength,
  22028. base + col + (row + 1) * rowLength
  22029. ];
  22030. indices.push(square[1]);
  22031. indices.push(square[2]);
  22032. indices.push(square[3]);
  22033. indices.push(square[0]);
  22034. indices.push(square[1]);
  22035. indices.push(square[3]);
  22036. }
  22037. }
  22038. // Position, normals and uvs
  22039. var position = BABYLON.Vector3.Zero();
  22040. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22041. for (row = 0; row <= precision.h; row++) {
  22042. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22043. for (col = 0; col <= precision.w; col++) {
  22044. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22045. position.y = 0;
  22046. positions.push(position.x, position.y, position.z);
  22047. normals.push(normal.x, normal.y, normal.z);
  22048. uvs.push(col / precision.w, row / precision.h);
  22049. }
  22050. }
  22051. }
  22052. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22053. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22054. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22055. }
  22056. }
  22057. // Result
  22058. var vertexData = new VertexData();
  22059. vertexData.indices = indices;
  22060. vertexData.positions = positions;
  22061. vertexData.normals = normals;
  22062. vertexData.uvs = uvs;
  22063. return vertexData;
  22064. };
  22065. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22066. var indices = [];
  22067. var positions = [];
  22068. var normals = [];
  22069. var uvs = [];
  22070. var row, col;
  22071. for (row = 0; row <= subdivisions; row++) {
  22072. for (col = 0; col <= subdivisions; col++) {
  22073. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22074. // Compute height
  22075. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22076. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22077. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22078. var r = buffer[pos] / 255.0;
  22079. var g = buffer[pos + 1] / 255.0;
  22080. var b = buffer[pos + 2] / 255.0;
  22081. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22082. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22083. // Add vertex
  22084. positions.push(position.x, position.y, position.z);
  22085. normals.push(0, 0, 0);
  22086. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22087. }
  22088. }
  22089. for (row = 0; row < subdivisions; row++) {
  22090. for (col = 0; col < subdivisions; col++) {
  22091. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22092. indices.push(col + 1 + row * (subdivisions + 1));
  22093. indices.push(col + row * (subdivisions + 1));
  22094. indices.push(col + (row + 1) * (subdivisions + 1));
  22095. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22096. indices.push(col + row * (subdivisions + 1));
  22097. }
  22098. }
  22099. // Normals
  22100. VertexData.ComputeNormals(positions, indices, normals);
  22101. // Result
  22102. var vertexData = new VertexData();
  22103. vertexData.indices = indices;
  22104. vertexData.positions = positions;
  22105. vertexData.normals = normals;
  22106. vertexData.uvs = uvs;
  22107. return vertexData;
  22108. };
  22109. VertexData.CreatePlane = function (size, sideOrientation) {
  22110. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22111. var indices = [];
  22112. var positions = [];
  22113. var normals = [];
  22114. var uvs = [];
  22115. size = size || 1;
  22116. // Vertices
  22117. var halfSize = size / 2.0;
  22118. positions.push(-halfSize, -halfSize, 0);
  22119. normals.push(0, 0, -1.0);
  22120. uvs.push(0.0, 0.0);
  22121. positions.push(halfSize, -halfSize, 0);
  22122. normals.push(0, 0, -1.0);
  22123. uvs.push(1.0, 0.0);
  22124. positions.push(halfSize, halfSize, 0);
  22125. normals.push(0, 0, -1.0);
  22126. uvs.push(1.0, 1.0);
  22127. positions.push(-halfSize, halfSize, 0);
  22128. normals.push(0, 0, -1.0);
  22129. uvs.push(0.0, 1.0);
  22130. // Indices
  22131. indices.push(0);
  22132. indices.push(1);
  22133. indices.push(2);
  22134. indices.push(0);
  22135. indices.push(2);
  22136. indices.push(3);
  22137. // Sides
  22138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22139. // Result
  22140. var vertexData = new VertexData();
  22141. vertexData.indices = indices;
  22142. vertexData.positions = positions;
  22143. vertexData.normals = normals;
  22144. vertexData.uvs = uvs;
  22145. return vertexData;
  22146. };
  22147. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22148. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22149. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22150. var indices = [];
  22151. var positions = [];
  22152. var normals = [];
  22153. var uvs = [];
  22154. radius = radius || 2;
  22155. tube = tube || 0.5;
  22156. radialSegments = radialSegments || 32;
  22157. tubularSegments = tubularSegments || 32;
  22158. p = p || 2;
  22159. q = q || 3;
  22160. // Helper
  22161. var getPos = function (angle) {
  22162. var cu = Math.cos(angle);
  22163. var su = Math.sin(angle);
  22164. var quOverP = q / p * angle;
  22165. var cs = Math.cos(quOverP);
  22166. var tx = radius * (2 + cs) * 0.5 * cu;
  22167. var ty = radius * (2 + cs) * su * 0.5;
  22168. var tz = radius * Math.sin(quOverP) * 0.5;
  22169. return new BABYLON.Vector3(tx, ty, tz);
  22170. };
  22171. for (var i = 0; i <= radialSegments; i++) {
  22172. var modI = i % radialSegments;
  22173. var u = modI / radialSegments * 2 * p * Math.PI;
  22174. var p1 = getPos(u);
  22175. var p2 = getPos(u + 0.01);
  22176. var tang = p2.subtract(p1);
  22177. var n = p2.add(p1);
  22178. var bitan = BABYLON.Vector3.Cross(tang, n);
  22179. n = BABYLON.Vector3.Cross(bitan, tang);
  22180. bitan.normalize();
  22181. n.normalize();
  22182. for (var j = 0; j < tubularSegments; j++) {
  22183. var modJ = j % tubularSegments;
  22184. var v = modJ / tubularSegments * 2 * Math.PI;
  22185. var cx = -tube * Math.cos(v);
  22186. var cy = tube * Math.sin(v);
  22187. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22188. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22189. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22190. uvs.push(i / radialSegments);
  22191. uvs.push(j / tubularSegments);
  22192. }
  22193. }
  22194. for (i = 0; i < radialSegments; i++) {
  22195. for (j = 0; j < tubularSegments; j++) {
  22196. var jNext = (j + 1) % tubularSegments;
  22197. var a = i * tubularSegments + j;
  22198. var b = (i + 1) * tubularSegments + j;
  22199. var c = (i + 1) * tubularSegments + jNext;
  22200. var d = i * tubularSegments + jNext;
  22201. indices.push(d);
  22202. indices.push(b);
  22203. indices.push(a);
  22204. indices.push(d);
  22205. indices.push(c);
  22206. indices.push(b);
  22207. }
  22208. }
  22209. // Normals
  22210. VertexData.ComputeNormals(positions, indices, normals);
  22211. // Sides
  22212. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22213. // Result
  22214. var vertexData = new VertexData();
  22215. vertexData.indices = indices;
  22216. vertexData.positions = positions;
  22217. vertexData.normals = normals;
  22218. vertexData.uvs = uvs;
  22219. return vertexData;
  22220. };
  22221. // Tools
  22222. VertexData.ComputeNormals = function (positions, indices, normals) {
  22223. var positionVectors = [];
  22224. var facesOfVertices = [];
  22225. var index;
  22226. for (index = 0; index < positions.length; index += 3) {
  22227. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22228. positionVectors.push(vector3);
  22229. facesOfVertices.push([]);
  22230. }
  22231. // Compute normals
  22232. var facesNormals = [];
  22233. for (index = 0; index < indices.length / 3; index++) {
  22234. var i1 = indices[index * 3];
  22235. var i2 = indices[index * 3 + 1];
  22236. var i3 = indices[index * 3 + 2];
  22237. var p1 = positionVectors[i1];
  22238. var p2 = positionVectors[i2];
  22239. var p3 = positionVectors[i3];
  22240. var p1p2 = p1.subtract(p2);
  22241. var p3p2 = p3.subtract(p2);
  22242. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22243. facesOfVertices[i1].push(index);
  22244. facesOfVertices[i2].push(index);
  22245. facesOfVertices[i3].push(index);
  22246. }
  22247. for (index = 0; index < positionVectors.length; index++) {
  22248. var faces = facesOfVertices[index];
  22249. var normal = BABYLON.Vector3.Zero();
  22250. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22251. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22252. }
  22253. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22254. normals[index * 3] = normal.x;
  22255. normals[index * 3 + 1] = normal.y;
  22256. normals[index * 3 + 2] = normal.z;
  22257. }
  22258. };
  22259. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22260. var li = indices.length;
  22261. var ln = normals.length;
  22262. var i;
  22263. var n;
  22264. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22265. switch (sideOrientation) {
  22266. case BABYLON.Mesh.FRONTSIDE:
  22267. break;
  22268. case BABYLON.Mesh.BACKSIDE:
  22269. var tmp;
  22270. for (i = 0; i < li; i += 3) {
  22271. tmp = indices[i];
  22272. indices[i] = indices[i + 2];
  22273. indices[i + 2] = tmp;
  22274. }
  22275. for (n = 0; n < ln; n++) {
  22276. normals[n] = -normals[n];
  22277. }
  22278. break;
  22279. case BABYLON.Mesh.DOUBLESIDE:
  22280. // positions
  22281. var lp = positions.length;
  22282. var l = lp / 3;
  22283. for (var p = 0; p < lp; p++) {
  22284. positions[lp + p] = positions[p];
  22285. }
  22286. for (i = 0; i < li; i += 3) {
  22287. indices[i + li] = indices[i + 2] + l;
  22288. indices[i + 1 + li] = indices[i + 1] + l;
  22289. indices[i + 2 + li] = indices[i] + l;
  22290. }
  22291. for (n = 0; n < ln; n++) {
  22292. normals[ln + n] = -normals[n];
  22293. }
  22294. // uvs
  22295. var lu = uvs.length;
  22296. for (var u = 0; u < lu; u++) {
  22297. uvs[u + lu] = uvs[u];
  22298. }
  22299. break;
  22300. }
  22301. };
  22302. return VertexData;
  22303. })();
  22304. BABYLON.VertexData = VertexData;
  22305. })(BABYLON || (BABYLON = {}));
  22306. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22307. var BABYLON;
  22308. (function (BABYLON) {
  22309. var buildCamera = function (that, name) {
  22310. that._leftCamera.isIntermediate = true;
  22311. that.subCameras.push(that._leftCamera);
  22312. that.subCameras.push(that._rightCamera);
  22313. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22314. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22315. that._anaglyphPostProcess.onApply = function (effect) {
  22316. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22317. };
  22318. that._update();
  22319. };
  22320. var AnaglyphArcRotateCamera = (function (_super) {
  22321. __extends(AnaglyphArcRotateCamera, _super);
  22322. // ANY
  22323. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22324. _super.call(this, name, alpha, beta, radius, target, scene);
  22325. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22326. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22327. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22328. buildCamera(this, name);
  22329. }
  22330. AnaglyphArcRotateCamera.prototype._update = function () {
  22331. this._updateCamera(this._leftCamera);
  22332. this._updateCamera(this._rightCamera);
  22333. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22334. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22335. _super.prototype._update.call(this);
  22336. };
  22337. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22338. camera.beta = this.beta;
  22339. camera.radius = this.radius;
  22340. camera.minZ = this.minZ;
  22341. camera.maxZ = this.maxZ;
  22342. camera.fov = this.fov;
  22343. camera.target = this.target;
  22344. };
  22345. return AnaglyphArcRotateCamera;
  22346. })(BABYLON.ArcRotateCamera);
  22347. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22348. var AnaglyphFreeCamera = (function (_super) {
  22349. __extends(AnaglyphFreeCamera, _super);
  22350. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22351. _super.call(this, name, position, scene);
  22352. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22353. this._transformMatrix = new BABYLON.Matrix();
  22354. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22355. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22356. buildCamera(this, name);
  22357. }
  22358. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22359. var target = this.getTarget();
  22360. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22361. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22362. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22363. };
  22364. AnaglyphFreeCamera.prototype._update = function () {
  22365. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22366. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22367. this._updateCamera(this._leftCamera);
  22368. this._updateCamera(this._rightCamera);
  22369. _super.prototype._update.call(this);
  22370. };
  22371. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22372. camera.minZ = this.minZ;
  22373. camera.maxZ = this.maxZ;
  22374. camera.fov = this.fov;
  22375. camera.viewport = this.viewport;
  22376. camera.setTarget(this.getTarget());
  22377. };
  22378. return AnaglyphFreeCamera;
  22379. })(BABYLON.FreeCamera);
  22380. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22381. })(BABYLON || (BABYLON = {}));
  22382. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22383. var BABYLON;
  22384. (function (BABYLON) {
  22385. var AnaglyphPostProcess = (function (_super) {
  22386. __extends(AnaglyphPostProcess, _super);
  22387. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22388. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22389. }
  22390. return AnaglyphPostProcess;
  22391. })(BABYLON.PostProcess);
  22392. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22393. })(BABYLON || (BABYLON = {}));
  22394. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22395. (function (BABYLON) {
  22396. var Tags = (function () {
  22397. function Tags() {
  22398. }
  22399. Tags.EnableFor = function (obj) {
  22400. obj._tags = obj._tags || {};
  22401. obj.hasTags = function () {
  22402. return Tags.HasTags(obj);
  22403. };
  22404. obj.addTags = function (tagsString) {
  22405. return Tags.AddTagsTo(obj, tagsString);
  22406. };
  22407. obj.removeTags = function (tagsString) {
  22408. return Tags.RemoveTagsFrom(obj, tagsString);
  22409. };
  22410. obj.matchesTagsQuery = function (tagsQuery) {
  22411. return Tags.MatchesQuery(obj, tagsQuery);
  22412. };
  22413. };
  22414. Tags.DisableFor = function (obj) {
  22415. delete obj._tags;
  22416. delete obj.hasTags;
  22417. delete obj.addTags;
  22418. delete obj.removeTags;
  22419. delete obj.matchesTagsQuery;
  22420. };
  22421. Tags.HasTags = function (obj) {
  22422. if (!obj._tags) {
  22423. return false;
  22424. }
  22425. return !BABYLON.Tools.IsEmpty(obj._tags);
  22426. };
  22427. Tags.GetTags = function (obj) {
  22428. if (!obj._tags) {
  22429. return null;
  22430. }
  22431. return obj._tags;
  22432. };
  22433. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22434. // a tag cannot start with '||', '&&', and '!'
  22435. // it cannot contain whitespaces
  22436. Tags.AddTagsTo = function (obj, tagsString) {
  22437. if (!tagsString) {
  22438. return;
  22439. }
  22440. var tags = tagsString.split(" ");
  22441. for (var t in tags) {
  22442. Tags._AddTagTo(obj, tags[t]);
  22443. }
  22444. };
  22445. Tags._AddTagTo = function (obj, tag) {
  22446. tag = tag.trim();
  22447. if (tag === "" || tag === "true" || tag === "false") {
  22448. return;
  22449. }
  22450. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22451. return;
  22452. }
  22453. Tags.EnableFor(obj);
  22454. obj._tags[tag] = true;
  22455. };
  22456. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22457. if (!Tags.HasTags(obj)) {
  22458. return;
  22459. }
  22460. var tags = tagsString.split(" ");
  22461. for (var t in tags) {
  22462. Tags._RemoveTagFrom(obj, tags[t]);
  22463. }
  22464. };
  22465. Tags._RemoveTagFrom = function (obj, tag) {
  22466. delete obj._tags[tag];
  22467. };
  22468. Tags.MatchesQuery = function (obj, tagsQuery) {
  22469. if (tagsQuery === undefined) {
  22470. return true;
  22471. }
  22472. if (tagsQuery === "") {
  22473. return Tags.HasTags(obj);
  22474. }
  22475. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22476. };
  22477. return Tags;
  22478. })();
  22479. BABYLON.Tags = Tags;
  22480. })(BABYLON || (BABYLON = {}));
  22481. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22482. (function (BABYLON) {
  22483. var Internals;
  22484. (function (Internals) {
  22485. var AndOrNotEvaluator = (function () {
  22486. function AndOrNotEvaluator() {
  22487. }
  22488. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22489. if (!query.match(/\([^\(\)]*\)/g)) {
  22490. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22491. }
  22492. else {
  22493. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22494. // remove parenthesis
  22495. r = r.slice(1, r.length - 1);
  22496. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22497. });
  22498. }
  22499. if (query === "true") {
  22500. return true;
  22501. }
  22502. if (query === "false") {
  22503. return false;
  22504. }
  22505. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22506. };
  22507. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22508. evaluateCallback = evaluateCallback || (function (r) {
  22509. return r === "true" ? true : false;
  22510. });
  22511. var result;
  22512. var or = parenthesisContent.split("||");
  22513. for (var i in or) {
  22514. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22515. var and = ori.split("&&");
  22516. if (and.length > 1) {
  22517. for (var j = 0; j < and.length; ++j) {
  22518. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22519. if (andj !== "true" && andj !== "false") {
  22520. if (andj[0] === "!") {
  22521. result = !evaluateCallback(andj.substring(1));
  22522. }
  22523. else {
  22524. result = evaluateCallback(andj);
  22525. }
  22526. }
  22527. else {
  22528. result = andj === "true" ? true : false;
  22529. }
  22530. if (!result) {
  22531. ori = "false";
  22532. break;
  22533. }
  22534. }
  22535. }
  22536. if (result || ori === "true") {
  22537. result = true;
  22538. break;
  22539. }
  22540. // result equals false (or undefined)
  22541. if (ori !== "true" && ori !== "false") {
  22542. if (ori[0] === "!") {
  22543. result = !evaluateCallback(ori.substring(1));
  22544. }
  22545. else {
  22546. result = evaluateCallback(ori);
  22547. }
  22548. }
  22549. else {
  22550. result = ori === "true" ? true : false;
  22551. }
  22552. }
  22553. // the whole parenthesis scope is replaced by 'true' or 'false'
  22554. return result ? "true" : "false";
  22555. };
  22556. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22557. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22558. // remove whitespaces
  22559. r = r.replace(/[\s]/g, function () { return ""; });
  22560. return r.length % 2 ? "!" : "";
  22561. });
  22562. booleanString = booleanString.trim();
  22563. if (booleanString === "!true") {
  22564. booleanString = "false";
  22565. }
  22566. else if (booleanString === "!false") {
  22567. booleanString = "true";
  22568. }
  22569. return booleanString;
  22570. };
  22571. return AndOrNotEvaluator;
  22572. })();
  22573. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22574. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22575. })(BABYLON || (BABYLON = {}));
  22576. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22577. (function (BABYLON) {
  22578. var PostProcessRenderPass = (function () {
  22579. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22580. this._enabled = true;
  22581. this._refCount = 0;
  22582. this._name = name;
  22583. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22584. this.setRenderList(renderList);
  22585. this._renderTexture.onBeforeRender = beforeRender;
  22586. this._renderTexture.onAfterRender = afterRender;
  22587. this._scene = scene;
  22588. this._renderList = renderList;
  22589. }
  22590. // private
  22591. PostProcessRenderPass.prototype._incRefCount = function () {
  22592. if (this._refCount === 0) {
  22593. this._scene.customRenderTargets.push(this._renderTexture);
  22594. }
  22595. return ++this._refCount;
  22596. };
  22597. PostProcessRenderPass.prototype._decRefCount = function () {
  22598. this._refCount--;
  22599. if (this._refCount <= 0) {
  22600. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22601. }
  22602. return this._refCount;
  22603. };
  22604. PostProcessRenderPass.prototype._update = function () {
  22605. this.setRenderList(this._renderList);
  22606. };
  22607. // public
  22608. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22609. this._renderTexture.renderList = renderList;
  22610. };
  22611. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22612. return this._renderTexture;
  22613. };
  22614. return PostProcessRenderPass;
  22615. })();
  22616. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22617. })(BABYLON || (BABYLON = {}));
  22618. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22619. (function (BABYLON) {
  22620. var PostProcessRenderEffect = (function () {
  22621. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22622. this._engine = engine;
  22623. this._name = name;
  22624. this._singleInstance = singleInstance || true;
  22625. this._getPostProcess = getPostProcess;
  22626. this._cameras = [];
  22627. this._indicesForCamera = [];
  22628. this._postProcesses = {};
  22629. this._renderPasses = {};
  22630. this._renderEffectAsPasses = {};
  22631. }
  22632. PostProcessRenderEffect.prototype._update = function () {
  22633. for (var renderPassName in this._renderPasses) {
  22634. this._renderPasses[renderPassName]._update();
  22635. }
  22636. };
  22637. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22638. this._renderPasses[renderPass._name] = renderPass;
  22639. this._linkParameters();
  22640. };
  22641. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22642. delete this._renderPasses[renderPass._name];
  22643. this._linkParameters();
  22644. };
  22645. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22646. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22647. this._linkParameters();
  22648. };
  22649. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22650. for (var renderPassName in this._renderPasses) {
  22651. if (renderPassName === passName) {
  22652. return this._renderPasses[passName];
  22653. }
  22654. }
  22655. };
  22656. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22657. this._renderPasses = {};
  22658. this._linkParameters();
  22659. };
  22660. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22661. var cameraKey;
  22662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22663. for (var i = 0; i < _cam.length; i++) {
  22664. var camera = _cam[i];
  22665. var cameraName = camera.name;
  22666. if (this._singleInstance) {
  22667. cameraKey = 0;
  22668. }
  22669. else {
  22670. cameraKey = cameraName;
  22671. }
  22672. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22673. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22674. if (!this._indicesForCamera[cameraName]) {
  22675. this._indicesForCamera[cameraName] = [];
  22676. }
  22677. this._indicesForCamera[cameraName].push(index);
  22678. if (this._cameras.indexOf(camera) === -1) {
  22679. this._cameras[cameraName] = camera;
  22680. }
  22681. for (var passName in this._renderPasses) {
  22682. this._renderPasses[passName]._incRefCount();
  22683. }
  22684. }
  22685. this._linkParameters();
  22686. };
  22687. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22688. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22689. for (var i = 0; i < _cam.length; i++) {
  22690. var camera = _cam[i];
  22691. var cameraName = camera.name;
  22692. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22693. var index = this._cameras.indexOf(cameraName);
  22694. this._indicesForCamera.splice(index, 1);
  22695. this._cameras.splice(index, 1);
  22696. for (var passName in this._renderPasses) {
  22697. this._renderPasses[passName]._decRefCount();
  22698. }
  22699. }
  22700. };
  22701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22702. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22703. for (var i = 0; i < _cam.length; i++) {
  22704. var camera = _cam[i];
  22705. var cameraName = camera.name;
  22706. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22707. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22708. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22709. }
  22710. }
  22711. for (var passName in this._renderPasses) {
  22712. this._renderPasses[passName]._incRefCount();
  22713. }
  22714. }
  22715. };
  22716. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22717. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22718. for (var i = 0; i < _cam.length; i++) {
  22719. var camera = _cam[i];
  22720. var cameraName = camera.Name;
  22721. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22722. for (var passName in this._renderPasses) {
  22723. this._renderPasses[passName]._decRefCount();
  22724. }
  22725. }
  22726. };
  22727. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22728. if (this._singleInstance) {
  22729. return this._postProcesses[0];
  22730. }
  22731. else {
  22732. return this._postProcesses[camera.name];
  22733. }
  22734. };
  22735. PostProcessRenderEffect.prototype._linkParameters = function () {
  22736. var _this = this;
  22737. for (var index in this._postProcesses) {
  22738. if (this.applyParameters) {
  22739. this.applyParameters(this._postProcesses[index]);
  22740. }
  22741. this._postProcesses[index].onBeforeRender = function (effect) {
  22742. _this._linkTextures(effect);
  22743. };
  22744. }
  22745. };
  22746. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22747. for (var renderPassName in this._renderPasses) {
  22748. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22749. }
  22750. for (var renderEffectName in this._renderEffectAsPasses) {
  22751. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22752. }
  22753. };
  22754. return PostProcessRenderEffect;
  22755. })();
  22756. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22757. })(BABYLON || (BABYLON = {}));
  22758. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22759. (function (BABYLON) {
  22760. var PostProcessRenderPipeline = (function () {
  22761. function PostProcessRenderPipeline(engine, name) {
  22762. this._engine = engine;
  22763. this._name = name;
  22764. this._renderEffects = {};
  22765. this._renderEffectsForIsolatedPass = {};
  22766. this._cameras = [];
  22767. }
  22768. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22769. this._renderEffects[renderEffect._name] = renderEffect;
  22770. };
  22771. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22772. var renderEffects = this._renderEffects[renderEffectName];
  22773. if (!renderEffects) {
  22774. return;
  22775. }
  22776. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22777. };
  22778. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22779. var renderEffects = this._renderEffects[renderEffectName];
  22780. if (!renderEffects) {
  22781. return;
  22782. }
  22783. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22784. };
  22785. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22786. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22787. var indicesToDelete = [];
  22788. for (var i = 0; i < _cam.length; i++) {
  22789. var camera = _cam[i];
  22790. var cameraName = camera.name;
  22791. if (this._cameras.indexOf(camera) === -1) {
  22792. this._cameras[cameraName] = camera;
  22793. }
  22794. else if (unique) {
  22795. indicesToDelete.push(i);
  22796. }
  22797. }
  22798. for (var i = 0; i < indicesToDelete.length; i++) {
  22799. cameras.splice(indicesToDelete[i], 1);
  22800. }
  22801. for (var renderEffectName in this._renderEffects) {
  22802. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22803. }
  22804. };
  22805. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22806. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22807. for (var renderEffectName in this._renderEffects) {
  22808. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22809. }
  22810. for (var i = 0; i < _cam.length; i++) {
  22811. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22812. }
  22813. };
  22814. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22815. var _this = this;
  22816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22817. var pass = null;
  22818. for (var renderEffectName in this._renderEffects) {
  22819. pass = this._renderEffects[renderEffectName].getPass(passName);
  22820. if (pass != null) {
  22821. break;
  22822. }
  22823. }
  22824. if (pass === null) {
  22825. return;
  22826. }
  22827. for (var renderEffectName in this._renderEffects) {
  22828. this._renderEffects[renderEffectName]._disable(_cam);
  22829. }
  22830. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22831. for (var i = 0; i < _cam.length; i++) {
  22832. var camera = _cam[i];
  22833. var cameraName = camera.name;
  22834. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22835. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22836. });
  22837. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22838. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22839. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22840. }
  22841. };
  22842. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22843. var _this = this;
  22844. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22845. for (var i = 0; i < _cam.length; i++) {
  22846. var camera = _cam[i];
  22847. var cameraName = camera.name;
  22848. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22849. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22850. });
  22851. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22852. }
  22853. for (var renderEffectName in this._renderEffects) {
  22854. this._renderEffects[renderEffectName]._enable(_cam);
  22855. }
  22856. };
  22857. PostProcessRenderPipeline.prototype._update = function () {
  22858. for (var renderEffectName in this._renderEffects) {
  22859. this._renderEffects[renderEffectName]._update();
  22860. }
  22861. for (var i = 0; i < this._cameras.length; i++) {
  22862. var cameraName = this._cameras[i].name;
  22863. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22864. this._renderEffectsForIsolatedPass[cameraName]._update();
  22865. }
  22866. }
  22867. };
  22868. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22869. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22870. return PostProcessRenderPipeline;
  22871. })();
  22872. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22873. })(BABYLON || (BABYLON = {}));
  22874. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22875. (function (BABYLON) {
  22876. var PostProcessRenderPipelineManager = (function () {
  22877. function PostProcessRenderPipelineManager() {
  22878. this._renderPipelines = {};
  22879. }
  22880. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22881. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22882. };
  22883. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22884. var renderPipeline = this._renderPipelines[renderPipelineName];
  22885. if (!renderPipeline) {
  22886. return;
  22887. }
  22888. renderPipeline._attachCameras(cameras, unique);
  22889. };
  22890. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22891. var renderPipeline = this._renderPipelines[renderPipelineName];
  22892. if (!renderPipeline) {
  22893. return;
  22894. }
  22895. renderPipeline._detachCameras(cameras);
  22896. };
  22897. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22898. var renderPipeline = this._renderPipelines[renderPipelineName];
  22899. if (!renderPipeline) {
  22900. return;
  22901. }
  22902. renderPipeline._enableEffect(renderEffectName, cameras);
  22903. };
  22904. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22905. var renderPipeline = this._renderPipelines[renderPipelineName];
  22906. if (!renderPipeline) {
  22907. return;
  22908. }
  22909. renderPipeline._disableEffect(renderEffectName, cameras);
  22910. };
  22911. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22912. var renderPipeline = this._renderPipelines[renderPipelineName];
  22913. if (!renderPipeline) {
  22914. return;
  22915. }
  22916. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22917. };
  22918. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22919. var renderPipeline = this._renderPipelines[renderPipelineName];
  22920. if (!renderPipeline) {
  22921. return;
  22922. }
  22923. renderPipeline._disableDisplayOnlyPass(cameras);
  22924. };
  22925. PostProcessRenderPipelineManager.prototype.update = function () {
  22926. for (var renderPipelineName in this._renderPipelines) {
  22927. this._renderPipelines[renderPipelineName]._update();
  22928. }
  22929. };
  22930. return PostProcessRenderPipelineManager;
  22931. })();
  22932. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22933. })(BABYLON || (BABYLON = {}));
  22934. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22935. var BABYLON;
  22936. (function (BABYLON) {
  22937. var DisplayPassPostProcess = (function (_super) {
  22938. __extends(DisplayPassPostProcess, _super);
  22939. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22940. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22941. }
  22942. return DisplayPassPostProcess;
  22943. })(BABYLON.PostProcess);
  22944. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22945. })(BABYLON || (BABYLON = {}));
  22946. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22947. (function (BABYLON) {
  22948. var BoundingBoxRenderer = (function () {
  22949. function BoundingBoxRenderer(scene) {
  22950. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22951. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22952. this.showBackLines = true;
  22953. this.renderList = new BABYLON.SmartArray(32);
  22954. this._scene = scene;
  22955. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22956. attributes: ["position"],
  22957. uniforms: ["worldViewProjection", "color"]
  22958. });
  22959. var engine = this._scene.getEngine();
  22960. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22961. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22962. 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]);
  22963. }
  22964. BoundingBoxRenderer.prototype.reset = function () {
  22965. this.renderList.reset();
  22966. };
  22967. BoundingBoxRenderer.prototype.render = function () {
  22968. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22969. return;
  22970. }
  22971. var engine = this._scene.getEngine();
  22972. engine.setDepthWrite(false);
  22973. this._colorShader._preBind();
  22974. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22975. var boundingBox = this.renderList.data[boundingBoxIndex];
  22976. var min = boundingBox.minimum;
  22977. var max = boundingBox.maximum;
  22978. var diff = max.subtract(min);
  22979. var median = min.add(diff.scale(0.5));
  22980. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22981. // VBOs
  22982. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22983. if (this.showBackLines) {
  22984. // Back
  22985. engine.setDepthFunctionToGreaterOrEqual();
  22986. this._scene.resetCachedMaterial();
  22987. this._colorShader.setColor4("color", this.backColor.toColor4());
  22988. this._colorShader.bind(worldMatrix);
  22989. // Draw order
  22990. engine.draw(false, 0, 24);
  22991. }
  22992. // Front
  22993. engine.setDepthFunctionToLess();
  22994. this._scene.resetCachedMaterial();
  22995. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22996. this._colorShader.bind(worldMatrix);
  22997. // Draw order
  22998. engine.draw(false, 0, 24);
  22999. }
  23000. this._colorShader.unbind();
  23001. engine.setDepthFunctionToLessOrEqual();
  23002. engine.setDepthWrite(true);
  23003. };
  23004. BoundingBoxRenderer.prototype.dispose = function () {
  23005. this._colorShader.dispose();
  23006. this._vb.dispose();
  23007. this._scene.getEngine()._releaseBuffer(this._ib);
  23008. };
  23009. return BoundingBoxRenderer;
  23010. })();
  23011. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23012. })(BABYLON || (BABYLON = {}));
  23013. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23014. (function (BABYLON) {
  23015. var Internals;
  23016. (function (Internals) {
  23017. /*
  23018. * Based on jsTGALoader - Javascript loader for TGA file
  23019. * By Vincent Thibault
  23020. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23021. */
  23022. var TGATools = (function () {
  23023. function TGATools() {
  23024. }
  23025. TGATools.GetTGAHeader = function (data) {
  23026. var offset = 0;
  23027. var header = {
  23028. id_length: data[offset++],
  23029. colormap_type: data[offset++],
  23030. image_type: data[offset++],
  23031. colormap_index: data[offset++] | data[offset++] << 8,
  23032. colormap_length: data[offset++] | data[offset++] << 8,
  23033. colormap_size: data[offset++],
  23034. origin: [
  23035. data[offset++] | data[offset++] << 8,
  23036. data[offset++] | data[offset++] << 8
  23037. ],
  23038. width: data[offset++] | data[offset++] << 8,
  23039. height: data[offset++] | data[offset++] << 8,
  23040. pixel_size: data[offset++],
  23041. flags: data[offset++]
  23042. };
  23043. return header;
  23044. };
  23045. TGATools.UploadContent = function (gl, data) {
  23046. // Not enough data to contain header ?
  23047. if (data.length < 19) {
  23048. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23049. return;
  23050. }
  23051. // Read Header
  23052. var offset = 18;
  23053. var header = TGATools.GetTGAHeader(data);
  23054. // Assume it's a valid Targa file.
  23055. if (header.id_length + offset > data.length) {
  23056. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23057. return;
  23058. }
  23059. // Skip not needed data
  23060. offset += header.id_length;
  23061. var use_rle = false;
  23062. var use_pal = false;
  23063. var use_rgb = false;
  23064. var use_grey = false;
  23065. switch (header.image_type) {
  23066. case TGATools._TYPE_RLE_INDEXED:
  23067. use_rle = true;
  23068. case TGATools._TYPE_INDEXED:
  23069. use_pal = true;
  23070. break;
  23071. case TGATools._TYPE_RLE_RGB:
  23072. use_rle = true;
  23073. case TGATools._TYPE_RGB:
  23074. use_rgb = true;
  23075. break;
  23076. case TGATools._TYPE_RLE_GREY:
  23077. use_rle = true;
  23078. case TGATools._TYPE_GREY:
  23079. use_grey = true;
  23080. break;
  23081. }
  23082. var pixel_data;
  23083. var numAlphaBits = header.flags & 0xf;
  23084. var pixel_size = header.pixel_size >> 3;
  23085. var pixel_total = header.width * header.height * pixel_size;
  23086. // Read palettes
  23087. var palettes;
  23088. if (use_pal) {
  23089. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23090. }
  23091. // Read LRE
  23092. if (use_rle) {
  23093. pixel_data = new Uint8Array(pixel_total);
  23094. var c, count, i;
  23095. var localOffset = 0;
  23096. var pixels = new Uint8Array(pixel_size);
  23097. while (offset < pixel_total && localOffset < pixel_total) {
  23098. c = data[offset++];
  23099. count = (c & 0x7f) + 1;
  23100. // RLE pixels
  23101. if (c & 0x80) {
  23102. for (i = 0; i < pixel_size; ++i) {
  23103. pixels[i] = data[offset++];
  23104. }
  23105. for (i = 0; i < count; ++i) {
  23106. pixel_data.set(pixels, localOffset + i * pixel_size);
  23107. }
  23108. localOffset += pixel_size * count;
  23109. }
  23110. else {
  23111. count *= pixel_size;
  23112. for (i = 0; i < count; ++i) {
  23113. pixel_data[localOffset + i] = data[offset++];
  23114. }
  23115. localOffset += count;
  23116. }
  23117. }
  23118. }
  23119. else {
  23120. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23121. }
  23122. // Load to texture
  23123. var x_start, y_start, x_step, y_step, y_end, x_end;
  23124. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23125. default:
  23126. case TGATools._ORIGIN_UL:
  23127. x_start = 0;
  23128. x_step = 1;
  23129. x_end = header.width;
  23130. y_start = 0;
  23131. y_step = 1;
  23132. y_end = header.height;
  23133. break;
  23134. case TGATools._ORIGIN_BL:
  23135. x_start = 0;
  23136. x_step = 1;
  23137. x_end = header.width;
  23138. y_start = header.height - 1;
  23139. y_step = -1;
  23140. y_end = -1;
  23141. break;
  23142. case TGATools._ORIGIN_UR:
  23143. x_start = header.width - 1;
  23144. x_step = -1;
  23145. x_end = -1;
  23146. y_start = 0;
  23147. y_step = 1;
  23148. y_end = header.height;
  23149. break;
  23150. case TGATools._ORIGIN_BR:
  23151. x_start = header.width - 1;
  23152. x_step = -1;
  23153. x_end = -1;
  23154. y_start = header.height - 1;
  23155. y_step = -1;
  23156. y_end = -1;
  23157. break;
  23158. }
  23159. // Load the specify method
  23160. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23161. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23162. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23163. };
  23164. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23165. var image = pixel_data, colormap = palettes;
  23166. var width = header.width, height = header.height;
  23167. var color, i = 0, x, y;
  23168. var imageData = new Uint8Array(width * height * 4);
  23169. for (y = y_start; y !== y_end; y += y_step) {
  23170. for (x = x_start; x !== x_end; x += x_step, i++) {
  23171. color = image[i];
  23172. imageData[(x + width * y) * 4 + 3] = 255;
  23173. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23174. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23175. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23176. }
  23177. }
  23178. return imageData;
  23179. };
  23180. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23181. var image = pixel_data;
  23182. var width = header.width, height = header.height;
  23183. var color, i = 0, x, y;
  23184. var imageData = new Uint8Array(width * height * 4);
  23185. for (y = y_start; y !== y_end; y += y_step) {
  23186. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23187. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23188. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23189. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23190. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23191. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23192. }
  23193. }
  23194. return imageData;
  23195. };
  23196. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23197. var image = pixel_data;
  23198. var width = header.width, height = header.height;
  23199. var i = 0, x, y;
  23200. var imageData = new Uint8Array(width * height * 4);
  23201. for (y = y_start; y !== y_end; y += y_step) {
  23202. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23203. imageData[(x + width * y) * 4 + 3] = 255;
  23204. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23205. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23206. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23207. }
  23208. }
  23209. return imageData;
  23210. };
  23211. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23212. var image = pixel_data;
  23213. var width = header.width, height = header.height;
  23214. var i = 0, x, y;
  23215. var imageData = new Uint8Array(width * height * 4);
  23216. for (y = y_start; y !== y_end; y += y_step) {
  23217. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23218. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23219. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23220. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23221. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23222. }
  23223. }
  23224. return imageData;
  23225. };
  23226. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23227. var image = pixel_data;
  23228. var width = header.width, height = header.height;
  23229. var color, i = 0, x, y;
  23230. var imageData = new Uint8Array(width * height * 4);
  23231. for (y = y_start; y !== y_end; y += y_step) {
  23232. for (x = x_start; x !== x_end; x += x_step, i++) {
  23233. color = image[i];
  23234. imageData[(x + width * y) * 4 + 0] = color;
  23235. imageData[(x + width * y) * 4 + 1] = color;
  23236. imageData[(x + width * y) * 4 + 2] = color;
  23237. imageData[(x + width * y) * 4 + 3] = 255;
  23238. }
  23239. }
  23240. return imageData;
  23241. };
  23242. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23243. var image = pixel_data;
  23244. var width = header.width, height = header.height;
  23245. var i = 0, x, y;
  23246. var imageData = new Uint8Array(width * height * 4);
  23247. for (y = y_start; y !== y_end; y += y_step) {
  23248. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23249. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23250. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23251. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23252. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23253. }
  23254. }
  23255. return imageData;
  23256. };
  23257. TGATools._TYPE_NO_DATA = 0;
  23258. TGATools._TYPE_INDEXED = 1;
  23259. TGATools._TYPE_RGB = 2;
  23260. TGATools._TYPE_GREY = 3;
  23261. TGATools._TYPE_RLE_INDEXED = 9;
  23262. TGATools._TYPE_RLE_RGB = 10;
  23263. TGATools._TYPE_RLE_GREY = 11;
  23264. TGATools._ORIGIN_MASK = 0x30;
  23265. TGATools._ORIGIN_SHIFT = 0x04;
  23266. TGATools._ORIGIN_BL = 0x00;
  23267. TGATools._ORIGIN_BR = 0x01;
  23268. TGATools._ORIGIN_UL = 0x02;
  23269. TGATools._ORIGIN_UR = 0x03;
  23270. return TGATools;
  23271. })();
  23272. Internals.TGATools = TGATools;
  23273. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23274. })(BABYLON || (BABYLON = {}));
  23275. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23276. (function (BABYLON) {
  23277. var Internals;
  23278. (function (Internals) {
  23279. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23280. // All values and structures referenced from:
  23281. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23282. var DDS_MAGIC = 0x20534444;
  23283. 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;
  23284. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23285. 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;
  23286. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23287. function FourCCToInt32(value) {
  23288. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23289. }
  23290. function Int32ToFourCC(value) {
  23291. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23292. }
  23293. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23294. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23295. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23296. var headerLengthInt = 31; // The header length in 32 bit ints
  23297. // Offsets into the header array
  23298. var off_magic = 0;
  23299. var off_size = 1;
  23300. var off_flags = 2;
  23301. var off_height = 3;
  23302. var off_width = 4;
  23303. var off_mipmapCount = 7;
  23304. var off_pfFlags = 20;
  23305. var off_pfFourCC = 21;
  23306. var off_RGBbpp = 22;
  23307. var off_RMask = 23;
  23308. var off_GMask = 24;
  23309. var off_BMask = 25;
  23310. var off_AMask = 26;
  23311. var off_caps1 = 27;
  23312. var off_caps2 = 28;
  23313. ;
  23314. var DDSTools = (function () {
  23315. function DDSTools() {
  23316. }
  23317. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23318. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23319. var mipmapCount = 1;
  23320. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23321. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23322. }
  23323. return {
  23324. width: header[off_width],
  23325. height: header[off_height],
  23326. mipmapCount: mipmapCount,
  23327. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23328. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23329. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23330. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23331. };
  23332. };
  23333. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23334. var byteArray = new Uint8Array(dataLength);
  23335. var srcData = new Uint8Array(arrayBuffer);
  23336. var index = 0;
  23337. for (var y = height - 1; y >= 0; y--) {
  23338. for (var x = 0; x < width; x++) {
  23339. var srcPos = dataOffset + (x + y * width) * 4;
  23340. byteArray[index + 2] = srcData[srcPos];
  23341. byteArray[index + 1] = srcData[srcPos + 1];
  23342. byteArray[index] = srcData[srcPos + 2];
  23343. byteArray[index + 3] = srcData[srcPos + 3];
  23344. index += 4;
  23345. }
  23346. }
  23347. return byteArray;
  23348. };
  23349. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23350. var byteArray = new Uint8Array(dataLength);
  23351. var srcData = new Uint8Array(arrayBuffer);
  23352. var index = 0;
  23353. for (var y = height - 1; y >= 0; y--) {
  23354. for (var x = 0; x < width; x++) {
  23355. var srcPos = dataOffset + (x + y * width) * 3;
  23356. byteArray[index + 2] = srcData[srcPos];
  23357. byteArray[index + 1] = srcData[srcPos + 1];
  23358. byteArray[index] = srcData[srcPos + 2];
  23359. index += 3;
  23360. }
  23361. }
  23362. return byteArray;
  23363. };
  23364. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23365. var byteArray = new Uint8Array(dataLength);
  23366. var srcData = new Uint8Array(arrayBuffer);
  23367. var index = 0;
  23368. for (var y = height - 1; y >= 0; y--) {
  23369. for (var x = 0; x < width; x++) {
  23370. var srcPos = dataOffset + (x + y * width);
  23371. byteArray[index] = srcData[srcPos];
  23372. index++;
  23373. }
  23374. }
  23375. return byteArray;
  23376. };
  23377. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23378. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23379. if (header[off_magic] != DDS_MAGIC) {
  23380. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23381. return;
  23382. }
  23383. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23384. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23385. return;
  23386. }
  23387. if (info.isFourCC) {
  23388. fourCC = header[off_pfFourCC];
  23389. switch (fourCC) {
  23390. case FOURCC_DXT1:
  23391. blockBytes = 8;
  23392. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23393. break;
  23394. case FOURCC_DXT3:
  23395. blockBytes = 16;
  23396. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23397. break;
  23398. case FOURCC_DXT5:
  23399. blockBytes = 16;
  23400. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23401. break;
  23402. default:
  23403. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23404. return;
  23405. }
  23406. }
  23407. mipmapCount = 1;
  23408. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23409. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23410. }
  23411. var bpp = header[off_RGBbpp];
  23412. for (var face = 0; face < faces; face++) {
  23413. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23414. width = header[off_width];
  23415. height = header[off_height];
  23416. dataOffset = header[off_size] + 4;
  23417. for (i = 0; i < mipmapCount; ++i) {
  23418. if (info.isRGB) {
  23419. if (bpp == 24) {
  23420. dataLength = width * height * 3;
  23421. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23422. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23423. }
  23424. else {
  23425. dataLength = width * height * 4;
  23426. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23427. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23428. }
  23429. }
  23430. else if (info.isLuminance) {
  23431. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23432. var unpaddedRowSize = width;
  23433. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23434. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23435. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23436. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23437. }
  23438. else {
  23439. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23440. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23441. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23442. }
  23443. dataOffset += dataLength;
  23444. width *= 0.5;
  23445. height *= 0.5;
  23446. width = Math.max(1.0, width);
  23447. height = Math.max(1.0, height);
  23448. }
  23449. }
  23450. };
  23451. return DDSTools;
  23452. })();
  23453. Internals.DDSTools = DDSTools;
  23454. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23455. })(BABYLON || (BABYLON = {}));
  23456. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23457. (function (BABYLON) {
  23458. var SmartArray = (function () {
  23459. function SmartArray(capacity) {
  23460. this.length = 0;
  23461. this._duplicateId = 0;
  23462. this.data = new Array(capacity);
  23463. this._id = SmartArray._GlobalId++;
  23464. }
  23465. SmartArray.prototype.push = function (value) {
  23466. this.data[this.length++] = value;
  23467. if (this.length > this.data.length) {
  23468. this.data.length *= 2;
  23469. }
  23470. if (!value.__smartArrayFlags) {
  23471. value.__smartArrayFlags = {};
  23472. }
  23473. value.__smartArrayFlags[this._id] = this._duplicateId;
  23474. };
  23475. SmartArray.prototype.pushNoDuplicate = function (value) {
  23476. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23477. return;
  23478. }
  23479. this.push(value);
  23480. };
  23481. SmartArray.prototype.sort = function (compareFn) {
  23482. this.data.sort(compareFn);
  23483. };
  23484. SmartArray.prototype.reset = function () {
  23485. this.length = 0;
  23486. this._duplicateId++;
  23487. };
  23488. SmartArray.prototype.concat = function (array) {
  23489. if (array.length === 0) {
  23490. return;
  23491. }
  23492. if (this.length + array.length > this.data.length) {
  23493. this.data.length = (this.length + array.length) * 2;
  23494. }
  23495. for (var index = 0; index < array.length; index++) {
  23496. this.data[this.length++] = (array.data || array)[index];
  23497. }
  23498. };
  23499. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23500. if (array.length === 0) {
  23501. return;
  23502. }
  23503. if (this.length + array.length > this.data.length) {
  23504. this.data.length = (this.length + array.length) * 2;
  23505. }
  23506. for (var index = 0; index < array.length; index++) {
  23507. var item = (array.data || array)[index];
  23508. this.pushNoDuplicate(item);
  23509. }
  23510. };
  23511. SmartArray.prototype.indexOf = function (value) {
  23512. var position = this.data.indexOf(value);
  23513. if (position >= this.length) {
  23514. return -1;
  23515. }
  23516. return position;
  23517. };
  23518. // Statics
  23519. SmartArray._GlobalId = 0;
  23520. return SmartArray;
  23521. })();
  23522. BABYLON.SmartArray = SmartArray;
  23523. })(BABYLON || (BABYLON = {}));
  23524. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23525. (function (BABYLON) {
  23526. var CannonJSPlugin = (function () {
  23527. function CannonJSPlugin() {
  23528. this._registeredMeshes = [];
  23529. this._physicsMaterials = [];
  23530. this.updateBodyPosition = function (mesh) {
  23531. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23532. var registeredMesh = this._registeredMeshes[index];
  23533. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23534. var body = registeredMesh.body;
  23535. var center = mesh.getBoundingInfo().boundingBox.center;
  23536. body.position.set(center.x, center.z, center.y);
  23537. body.quaternion.x = mesh.rotationQuaternion.x;
  23538. body.quaternion.z = mesh.rotationQuaternion.y;
  23539. body.quaternion.y = mesh.rotationQuaternion.z;
  23540. body.quaternion.w = -mesh.rotationQuaternion.w;
  23541. return;
  23542. }
  23543. }
  23544. };
  23545. }
  23546. CannonJSPlugin.prototype.initialize = function (iterations) {
  23547. if (iterations === void 0) { iterations = 10; }
  23548. this._world = new CANNON.World();
  23549. this._world.broadphase = new CANNON.NaiveBroadphase();
  23550. this._world.solver.iterations = iterations;
  23551. };
  23552. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23553. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23554. };
  23555. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23556. this._world.step(delta);
  23557. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23558. var registeredMesh = this._registeredMeshes[index];
  23559. if (registeredMesh.isChild) {
  23560. continue;
  23561. }
  23562. // Body position
  23563. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23564. var deltaPos = registeredMesh.delta;
  23565. if (deltaPos) {
  23566. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23567. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23568. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23569. }
  23570. else {
  23571. registeredMesh.mesh.position.x = bodyX;
  23572. registeredMesh.mesh.position.y = bodyZ;
  23573. registeredMesh.mesh.position.z = bodyY;
  23574. }
  23575. if (!registeredMesh.mesh.rotationQuaternion) {
  23576. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23577. }
  23578. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23579. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23580. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23581. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23582. }
  23583. };
  23584. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23585. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23586. };
  23587. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23588. this.unregisterMesh(mesh);
  23589. mesh.computeWorldMatrix(true);
  23590. switch (impostor) {
  23591. case BABYLON.PhysicsEngine.SphereImpostor:
  23592. var bbox = mesh.getBoundingInfo().boundingBox;
  23593. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23594. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23595. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23596. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23597. case BABYLON.PhysicsEngine.BoxImpostor:
  23598. bbox = mesh.getBoundingInfo().boundingBox;
  23599. var min = bbox.minimumWorld;
  23600. var max = bbox.maximumWorld;
  23601. var box = max.subtract(min).scale(0.5);
  23602. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23603. case BABYLON.PhysicsEngine.PlaneImpostor:
  23604. return this._createPlane(mesh, options);
  23605. case BABYLON.PhysicsEngine.MeshImpostor:
  23606. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23607. var rawFaces = mesh.getIndices();
  23608. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23609. }
  23610. return null;
  23611. };
  23612. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23613. var shape = new CANNON.Sphere(radius);
  23614. if (!options) {
  23615. return shape;
  23616. }
  23617. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23618. };
  23619. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23620. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23621. if (!options) {
  23622. return shape;
  23623. }
  23624. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23625. };
  23626. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23627. var shape = new CANNON.Plane();
  23628. if (!options) {
  23629. return shape;
  23630. }
  23631. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23632. };
  23633. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23634. var verts = [], faces = [];
  23635. mesh.computeWorldMatrix(true);
  23636. for (var i = 0; i < rawVerts.length; i += 3) {
  23637. var transformed = BABYLON.Vector3.Zero();
  23638. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23639. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23640. }
  23641. for (var j = 0; j < rawFaces.length; j += 3) {
  23642. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23643. }
  23644. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23645. if (!options) {
  23646. return shape;
  23647. }
  23648. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23649. };
  23650. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23651. var index;
  23652. var mat;
  23653. for (index = 0; index < this._physicsMaterials.length; index++) {
  23654. mat = this._physicsMaterials[index];
  23655. if (mat.friction === friction && mat.restitution === restitution) {
  23656. return mat;
  23657. }
  23658. }
  23659. var currentMat = new CANNON.Material();
  23660. currentMat.friction = friction;
  23661. currentMat.restitution = restitution;
  23662. this._physicsMaterials.push(currentMat);
  23663. for (index = 0; index < this._physicsMaterials.length; index++) {
  23664. mat = this._physicsMaterials[index];
  23665. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23666. contactMaterial.contactEquationStiffness = 1e10;
  23667. contactMaterial.contactEquationRegularizationTime = 10;
  23668. this._world.addContactMaterial(contactMaterial);
  23669. }
  23670. return currentMat;
  23671. };
  23672. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23673. var initialRotation = null;
  23674. if (mesh.rotationQuaternion) {
  23675. initialRotation = mesh.rotationQuaternion.clone();
  23676. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23677. }
  23678. // The delta between the mesh position and the mesh bounding box center
  23679. var bbox = mesh.getBoundingInfo().boundingBox;
  23680. var deltaPosition = mesh.position.subtract(bbox.center);
  23681. var material = this._addMaterial(friction, restitution);
  23682. var body = new CANNON.RigidBody(mass, shape, material);
  23683. if (initialRotation) {
  23684. body.quaternion.x = initialRotation.x;
  23685. body.quaternion.z = initialRotation.y;
  23686. body.quaternion.y = initialRotation.z;
  23687. body.quaternion.w = -initialRotation.w;
  23688. }
  23689. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23690. this._world.add(body);
  23691. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23692. return body;
  23693. };
  23694. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23695. var compoundShape = new CANNON.Compound();
  23696. for (var index = 0; index < parts.length; index++) {
  23697. var mesh = parts[index].mesh;
  23698. var shape = this.registerMesh(mesh, parts[index].impostor);
  23699. if (index == 0) {
  23700. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23701. }
  23702. else {
  23703. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23704. }
  23705. }
  23706. var initialMesh = parts[0].mesh;
  23707. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23708. body.parts = parts;
  23709. return body;
  23710. };
  23711. CannonJSPlugin.prototype._unbindBody = function (body) {
  23712. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23713. var registeredMesh = this._registeredMeshes[index];
  23714. if (registeredMesh.body === body) {
  23715. registeredMesh.body = null;
  23716. registeredMesh.delta = 0;
  23717. }
  23718. }
  23719. };
  23720. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23722. var registeredMesh = this._registeredMeshes[index];
  23723. if (registeredMesh.mesh === mesh) {
  23724. // Remove body
  23725. if (registeredMesh.body) {
  23726. this._world.remove(registeredMesh.body);
  23727. this._unbindBody(registeredMesh.body);
  23728. }
  23729. this._registeredMeshes.splice(index, 1);
  23730. return;
  23731. }
  23732. }
  23733. };
  23734. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23735. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23736. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23737. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23738. var registeredMesh = this._registeredMeshes[index];
  23739. if (registeredMesh.mesh === mesh) {
  23740. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23741. return;
  23742. }
  23743. }
  23744. };
  23745. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23746. var body1 = null, body2 = null;
  23747. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23748. var registeredMesh = this._registeredMeshes[index];
  23749. if (registeredMesh.mesh === mesh1) {
  23750. body1 = registeredMesh.body;
  23751. }
  23752. else if (registeredMesh.mesh === mesh2) {
  23753. body2 = registeredMesh.body;
  23754. }
  23755. }
  23756. if (!body1 || !body2) {
  23757. return false;
  23758. }
  23759. 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));
  23760. this._world.addConstraint(constraint);
  23761. return true;
  23762. };
  23763. CannonJSPlugin.prototype.dispose = function () {
  23764. while (this._registeredMeshes.length) {
  23765. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23766. }
  23767. };
  23768. CannonJSPlugin.prototype.isSupported = function () {
  23769. return window.CANNON !== undefined;
  23770. };
  23771. return CannonJSPlugin;
  23772. })();
  23773. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23774. })(BABYLON || (BABYLON = {}));
  23775. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23776. var BABYLON;
  23777. (function (BABYLON) {
  23778. var Condition = (function () {
  23779. function Condition(actionManager) {
  23780. this._actionManager = actionManager;
  23781. }
  23782. Condition.prototype.isValid = function () {
  23783. return true;
  23784. };
  23785. Condition.prototype._getProperty = function (propertyPath) {
  23786. return this._actionManager._getProperty(propertyPath);
  23787. };
  23788. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23789. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23790. };
  23791. return Condition;
  23792. })();
  23793. BABYLON.Condition = Condition;
  23794. var ValueCondition = (function (_super) {
  23795. __extends(ValueCondition, _super);
  23796. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23797. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23798. _super.call(this, actionManager);
  23799. this.propertyPath = propertyPath;
  23800. this.value = value;
  23801. this.operator = operator;
  23802. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23803. this._property = this._getProperty(this.propertyPath);
  23804. }
  23805. Object.defineProperty(ValueCondition, "IsEqual", {
  23806. get: function () {
  23807. return ValueCondition._IsEqual;
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(ValueCondition, "IsDifferent", {
  23813. get: function () {
  23814. return ValueCondition._IsDifferent;
  23815. },
  23816. enumerable: true,
  23817. configurable: true
  23818. });
  23819. Object.defineProperty(ValueCondition, "IsGreater", {
  23820. get: function () {
  23821. return ValueCondition._IsGreater;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. Object.defineProperty(ValueCondition, "IsLesser", {
  23827. get: function () {
  23828. return ValueCondition._IsLesser;
  23829. },
  23830. enumerable: true,
  23831. configurable: true
  23832. });
  23833. // Methods
  23834. ValueCondition.prototype.isValid = function () {
  23835. switch (this.operator) {
  23836. case ValueCondition.IsGreater:
  23837. return this._target[this._property] > this.value;
  23838. case ValueCondition.IsLesser:
  23839. return this._target[this._property] < this.value;
  23840. case ValueCondition.IsEqual:
  23841. case ValueCondition.IsDifferent:
  23842. var check;
  23843. if (this.value.equals) {
  23844. check = this.value.equals(this._target[this._property]);
  23845. }
  23846. else {
  23847. check = this.value === this._target[this._property];
  23848. }
  23849. return this.operator === ValueCondition.IsEqual ? check : !check;
  23850. }
  23851. return false;
  23852. };
  23853. // Statics
  23854. ValueCondition._IsEqual = 0;
  23855. ValueCondition._IsDifferent = 1;
  23856. ValueCondition._IsGreater = 2;
  23857. ValueCondition._IsLesser = 3;
  23858. return ValueCondition;
  23859. })(Condition);
  23860. BABYLON.ValueCondition = ValueCondition;
  23861. var PredicateCondition = (function (_super) {
  23862. __extends(PredicateCondition, _super);
  23863. function PredicateCondition(actionManager, predicate) {
  23864. _super.call(this, actionManager);
  23865. this.predicate = predicate;
  23866. }
  23867. PredicateCondition.prototype.isValid = function () {
  23868. return this.predicate();
  23869. };
  23870. return PredicateCondition;
  23871. })(Condition);
  23872. BABYLON.PredicateCondition = PredicateCondition;
  23873. var StateCondition = (function (_super) {
  23874. __extends(StateCondition, _super);
  23875. function StateCondition(actionManager, target, value) {
  23876. _super.call(this, actionManager);
  23877. this.value = value;
  23878. this._target = target;
  23879. }
  23880. // Methods
  23881. StateCondition.prototype.isValid = function () {
  23882. return this._target.state === this.value;
  23883. };
  23884. return StateCondition;
  23885. })(Condition);
  23886. BABYLON.StateCondition = StateCondition;
  23887. })(BABYLON || (BABYLON = {}));
  23888. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23889. (function (BABYLON) {
  23890. var Action = (function () {
  23891. function Action(triggerOptions, condition) {
  23892. this.triggerOptions = triggerOptions;
  23893. if (triggerOptions.parameter) {
  23894. this.trigger = triggerOptions.trigger;
  23895. this._triggerParameter = triggerOptions.parameter;
  23896. }
  23897. else {
  23898. this.trigger = triggerOptions;
  23899. }
  23900. this._nextActiveAction = this;
  23901. this._condition = condition;
  23902. }
  23903. // Methods
  23904. Action.prototype._prepare = function () {
  23905. };
  23906. Action.prototype.getTriggerParameter = function () {
  23907. return this._triggerParameter;
  23908. };
  23909. Action.prototype._executeCurrent = function (evt) {
  23910. if (this._nextActiveAction._condition) {
  23911. var condition = this._nextActiveAction._condition;
  23912. var currentRenderId = this._actionManager.getScene().getRenderId();
  23913. // We cache the current evaluation for the current frame
  23914. if (condition._evaluationId === currentRenderId) {
  23915. if (!condition._currentResult) {
  23916. return;
  23917. }
  23918. }
  23919. else {
  23920. condition._evaluationId = currentRenderId;
  23921. if (!condition.isValid()) {
  23922. condition._currentResult = false;
  23923. return;
  23924. }
  23925. condition._currentResult = true;
  23926. }
  23927. }
  23928. this._nextActiveAction.execute(evt);
  23929. if (this._nextActiveAction._child) {
  23930. if (!this._nextActiveAction._child._actionManager) {
  23931. this._nextActiveAction._child._actionManager = this._actionManager;
  23932. }
  23933. this._nextActiveAction = this._nextActiveAction._child;
  23934. }
  23935. else {
  23936. this._nextActiveAction = this;
  23937. }
  23938. };
  23939. Action.prototype.execute = function (evt) {
  23940. };
  23941. Action.prototype.then = function (action) {
  23942. this._child = action;
  23943. action._actionManager = this._actionManager;
  23944. action._prepare();
  23945. return action;
  23946. };
  23947. Action.prototype._getProperty = function (propertyPath) {
  23948. return this._actionManager._getProperty(propertyPath);
  23949. };
  23950. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23951. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23952. };
  23953. return Action;
  23954. })();
  23955. BABYLON.Action = Action;
  23956. })(BABYLON || (BABYLON = {}));
  23957. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23958. (function (BABYLON) {
  23959. /**
  23960. * ActionEvent is the event beint sent when an action is triggered.
  23961. */
  23962. var ActionEvent = (function () {
  23963. /**
  23964. * @constructor
  23965. * @param source The mesh that triggered the action.
  23966. * @param pointerX the X mouse cursor position at the time of the event
  23967. * @param pointerY the Y mouse cursor position at the time of the event
  23968. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23969. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23970. */
  23971. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23972. this.source = source;
  23973. this.pointerX = pointerX;
  23974. this.pointerY = pointerY;
  23975. this.meshUnderPointer = meshUnderPointer;
  23976. this.sourceEvent = sourceEvent;
  23977. }
  23978. /**
  23979. * Helper function to auto-create an ActionEvent from a source mesh.
  23980. * @param source the source mesh that triggered the event
  23981. * @param evt {Event} The original (browser) event
  23982. */
  23983. ActionEvent.CreateNew = function (source, evt) {
  23984. var scene = source.getScene();
  23985. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23986. };
  23987. /**
  23988. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23989. * @param scene the scene where the event occurred
  23990. * @param evt {Event} The original (browser) event
  23991. */
  23992. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23993. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23994. };
  23995. return ActionEvent;
  23996. })();
  23997. BABYLON.ActionEvent = ActionEvent;
  23998. /**
  23999. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24000. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24001. */
  24002. var ActionManager = (function () {
  24003. function ActionManager(scene) {
  24004. // Members
  24005. this.actions = new Array();
  24006. this._scene = scene;
  24007. scene._actionManagers.push(this);
  24008. }
  24009. Object.defineProperty(ActionManager, "NothingTrigger", {
  24010. get: function () {
  24011. return ActionManager._NothingTrigger;
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24017. get: function () {
  24018. return ActionManager._OnPickTrigger;
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24024. get: function () {
  24025. return ActionManager._OnLeftPickTrigger;
  24026. },
  24027. enumerable: true,
  24028. configurable: true
  24029. });
  24030. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24031. get: function () {
  24032. return ActionManager._OnRightPickTrigger;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24038. get: function () {
  24039. return ActionManager._OnCenterPickTrigger;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24045. get: function () {
  24046. return ActionManager._OnPointerOverTrigger;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24052. get: function () {
  24053. return ActionManager._OnPointerOutTrigger;
  24054. },
  24055. enumerable: true,
  24056. configurable: true
  24057. });
  24058. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24059. get: function () {
  24060. return ActionManager._OnEveryFrameTrigger;
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24066. get: function () {
  24067. return ActionManager._OnIntersectionEnterTrigger;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24073. get: function () {
  24074. return ActionManager._OnIntersectionExitTrigger;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24080. get: function () {
  24081. return ActionManager._OnKeyDownTrigger;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24087. get: function () {
  24088. return ActionManager._OnKeyUpTrigger;
  24089. },
  24090. enumerable: true,
  24091. configurable: true
  24092. });
  24093. // Methods
  24094. ActionManager.prototype.dispose = function () {
  24095. var index = this._scene._actionManagers.indexOf(this);
  24096. if (index > -1) {
  24097. this._scene._actionManagers.splice(index, 1);
  24098. }
  24099. };
  24100. ActionManager.prototype.getScene = function () {
  24101. return this._scene;
  24102. };
  24103. /**
  24104. * Does this action manager handles actions of any of the given triggers
  24105. * @param {number[]} triggers - the triggers to be tested
  24106. * @return {boolean} whether one (or more) of the triggers is handeled
  24107. */
  24108. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24109. for (var index = 0; index < this.actions.length; index++) {
  24110. var action = this.actions[index];
  24111. if (triggers.indexOf(action.trigger) > -1) {
  24112. return true;
  24113. }
  24114. }
  24115. return false;
  24116. };
  24117. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24118. /**
  24119. * Does this action manager has pointer triggers
  24120. * @return {boolean} whether or not it has pointer triggers
  24121. */
  24122. get: function () {
  24123. for (var index = 0; index < this.actions.length; index++) {
  24124. var action = this.actions[index];
  24125. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24126. return true;
  24127. }
  24128. }
  24129. return false;
  24130. },
  24131. enumerable: true,
  24132. configurable: true
  24133. });
  24134. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24135. /**
  24136. * Does this action manager has pick triggers
  24137. * @return {boolean} whether or not it has pick triggers
  24138. */
  24139. get: function () {
  24140. for (var index = 0; index < this.actions.length; index++) {
  24141. var action = this.actions[index];
  24142. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24143. return true;
  24144. }
  24145. }
  24146. return false;
  24147. },
  24148. enumerable: true,
  24149. configurable: true
  24150. });
  24151. /**
  24152. * Registers an action to this action manager
  24153. * @param {BABYLON.Action} action - the action to be registered
  24154. * @return {BABYLON.Action} the action amended (prepared) after registration
  24155. */
  24156. ActionManager.prototype.registerAction = function (action) {
  24157. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24158. if (this.getScene().actionManager !== this) {
  24159. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24160. return null;
  24161. }
  24162. }
  24163. this.actions.push(action);
  24164. action._actionManager = this;
  24165. action._prepare();
  24166. return action;
  24167. };
  24168. /**
  24169. * Process a specific trigger
  24170. * @param {number} trigger - the trigger to process
  24171. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24172. */
  24173. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24174. for (var index = 0; index < this.actions.length; index++) {
  24175. var action = this.actions[index];
  24176. if (action.trigger === trigger) {
  24177. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24178. var parameter = action.getTriggerParameter();
  24179. if (parameter) {
  24180. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24181. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24182. if (actualkey !== parameter.toLowerCase()) {
  24183. continue;
  24184. }
  24185. }
  24186. }
  24187. action._executeCurrent(evt);
  24188. }
  24189. }
  24190. };
  24191. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24192. var properties = propertyPath.split(".");
  24193. for (var index = 0; index < properties.length - 1; index++) {
  24194. target = target[properties[index]];
  24195. }
  24196. return target;
  24197. };
  24198. ActionManager.prototype._getProperty = function (propertyPath) {
  24199. var properties = propertyPath.split(".");
  24200. return properties[properties.length - 1];
  24201. };
  24202. // Statics
  24203. ActionManager._NothingTrigger = 0;
  24204. ActionManager._OnPickTrigger = 1;
  24205. ActionManager._OnLeftPickTrigger = 2;
  24206. ActionManager._OnRightPickTrigger = 3;
  24207. ActionManager._OnCenterPickTrigger = 4;
  24208. ActionManager._OnPointerOverTrigger = 5;
  24209. ActionManager._OnPointerOutTrigger = 6;
  24210. ActionManager._OnEveryFrameTrigger = 7;
  24211. ActionManager._OnIntersectionEnterTrigger = 8;
  24212. ActionManager._OnIntersectionExitTrigger = 9;
  24213. ActionManager._OnKeyDownTrigger = 10;
  24214. ActionManager._OnKeyUpTrigger = 11;
  24215. return ActionManager;
  24216. })();
  24217. BABYLON.ActionManager = ActionManager;
  24218. })(BABYLON || (BABYLON = {}));
  24219. //# sourceMappingURL=babylon.actionManager.js.map
  24220. var BABYLON;
  24221. (function (BABYLON) {
  24222. var InterpolateValueAction = (function (_super) {
  24223. __extends(InterpolateValueAction, _super);
  24224. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24225. if (duration === void 0) { duration = 1000; }
  24226. _super.call(this, triggerOptions, condition);
  24227. this.propertyPath = propertyPath;
  24228. this.value = value;
  24229. this.duration = duration;
  24230. this.stopOtherAnimations = stopOtherAnimations;
  24231. this._target = target;
  24232. }
  24233. InterpolateValueAction.prototype._prepare = function () {
  24234. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24235. this._property = this._getProperty(this.propertyPath);
  24236. };
  24237. InterpolateValueAction.prototype.execute = function () {
  24238. var scene = this._actionManager.getScene();
  24239. var keys = [
  24240. {
  24241. frame: 0,
  24242. value: this._target[this._property]
  24243. },
  24244. {
  24245. frame: 100,
  24246. value: this.value
  24247. }
  24248. ];
  24249. var dataType;
  24250. if (typeof this.value === "number") {
  24251. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24252. }
  24253. else if (this.value instanceof BABYLON.Color3) {
  24254. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24255. }
  24256. else if (this.value instanceof BABYLON.Vector3) {
  24257. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24258. }
  24259. else if (this.value instanceof BABYLON.Matrix) {
  24260. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24261. }
  24262. else if (this.value instanceof BABYLON.Quaternion) {
  24263. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24264. }
  24265. else {
  24266. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24267. return;
  24268. }
  24269. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24270. animation.setKeys(keys);
  24271. if (this.stopOtherAnimations) {
  24272. scene.stopAnimation(this._target);
  24273. }
  24274. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24275. };
  24276. return InterpolateValueAction;
  24277. })(BABYLON.Action);
  24278. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24279. })(BABYLON || (BABYLON = {}));
  24280. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24281. var BABYLON;
  24282. (function (BABYLON) {
  24283. var SwitchBooleanAction = (function (_super) {
  24284. __extends(SwitchBooleanAction, _super);
  24285. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24286. _super.call(this, triggerOptions, condition);
  24287. this.propertyPath = propertyPath;
  24288. this._target = target;
  24289. }
  24290. SwitchBooleanAction.prototype._prepare = function () {
  24291. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24292. this._property = this._getProperty(this.propertyPath);
  24293. };
  24294. SwitchBooleanAction.prototype.execute = function () {
  24295. this._target[this._property] = !this._target[this._property];
  24296. };
  24297. return SwitchBooleanAction;
  24298. })(BABYLON.Action);
  24299. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24300. var SetStateAction = (function (_super) {
  24301. __extends(SetStateAction, _super);
  24302. function SetStateAction(triggerOptions, target, value, condition) {
  24303. _super.call(this, triggerOptions, condition);
  24304. this.value = value;
  24305. this._target = target;
  24306. }
  24307. SetStateAction.prototype.execute = function () {
  24308. this._target.state = this.value;
  24309. };
  24310. return SetStateAction;
  24311. })(BABYLON.Action);
  24312. BABYLON.SetStateAction = SetStateAction;
  24313. var SetValueAction = (function (_super) {
  24314. __extends(SetValueAction, _super);
  24315. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24316. _super.call(this, triggerOptions, condition);
  24317. this.propertyPath = propertyPath;
  24318. this.value = value;
  24319. this._target = target;
  24320. }
  24321. SetValueAction.prototype._prepare = function () {
  24322. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24323. this._property = this._getProperty(this.propertyPath);
  24324. };
  24325. SetValueAction.prototype.execute = function () {
  24326. this._target[this._property] = this.value;
  24327. };
  24328. return SetValueAction;
  24329. })(BABYLON.Action);
  24330. BABYLON.SetValueAction = SetValueAction;
  24331. var IncrementValueAction = (function (_super) {
  24332. __extends(IncrementValueAction, _super);
  24333. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24334. _super.call(this, triggerOptions, condition);
  24335. this.propertyPath = propertyPath;
  24336. this.value = value;
  24337. this._target = target;
  24338. }
  24339. IncrementValueAction.prototype._prepare = function () {
  24340. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24341. this._property = this._getProperty(this.propertyPath);
  24342. if (typeof this._target[this._property] !== "number") {
  24343. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24344. }
  24345. };
  24346. IncrementValueAction.prototype.execute = function () {
  24347. this._target[this._property] += this.value;
  24348. };
  24349. return IncrementValueAction;
  24350. })(BABYLON.Action);
  24351. BABYLON.IncrementValueAction = IncrementValueAction;
  24352. var PlayAnimationAction = (function (_super) {
  24353. __extends(PlayAnimationAction, _super);
  24354. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24355. _super.call(this, triggerOptions, condition);
  24356. this.from = from;
  24357. this.to = to;
  24358. this.loop = loop;
  24359. this._target = target;
  24360. }
  24361. PlayAnimationAction.prototype._prepare = function () {
  24362. };
  24363. PlayAnimationAction.prototype.execute = function () {
  24364. var scene = this._actionManager.getScene();
  24365. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24366. };
  24367. return PlayAnimationAction;
  24368. })(BABYLON.Action);
  24369. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24370. var StopAnimationAction = (function (_super) {
  24371. __extends(StopAnimationAction, _super);
  24372. function StopAnimationAction(triggerOptions, target, condition) {
  24373. _super.call(this, triggerOptions, condition);
  24374. this._target = target;
  24375. }
  24376. StopAnimationAction.prototype._prepare = function () {
  24377. };
  24378. StopAnimationAction.prototype.execute = function () {
  24379. var scene = this._actionManager.getScene();
  24380. scene.stopAnimation(this._target);
  24381. };
  24382. return StopAnimationAction;
  24383. })(BABYLON.Action);
  24384. BABYLON.StopAnimationAction = StopAnimationAction;
  24385. var DoNothingAction = (function (_super) {
  24386. __extends(DoNothingAction, _super);
  24387. function DoNothingAction(triggerOptions, condition) {
  24388. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24389. _super.call(this, triggerOptions, condition);
  24390. }
  24391. DoNothingAction.prototype.execute = function () {
  24392. };
  24393. return DoNothingAction;
  24394. })(BABYLON.Action);
  24395. BABYLON.DoNothingAction = DoNothingAction;
  24396. var CombineAction = (function (_super) {
  24397. __extends(CombineAction, _super);
  24398. function CombineAction(triggerOptions, children, condition) {
  24399. _super.call(this, triggerOptions, condition);
  24400. this.children = children;
  24401. }
  24402. CombineAction.prototype._prepare = function () {
  24403. for (var index = 0; index < this.children.length; index++) {
  24404. this.children[index]._actionManager = this._actionManager;
  24405. this.children[index]._prepare();
  24406. }
  24407. };
  24408. CombineAction.prototype.execute = function (evt) {
  24409. for (var index = 0; index < this.children.length; index++) {
  24410. this.children[index].execute(evt);
  24411. }
  24412. };
  24413. return CombineAction;
  24414. })(BABYLON.Action);
  24415. BABYLON.CombineAction = CombineAction;
  24416. var ExecuteCodeAction = (function (_super) {
  24417. __extends(ExecuteCodeAction, _super);
  24418. function ExecuteCodeAction(triggerOptions, func, condition) {
  24419. _super.call(this, triggerOptions, condition);
  24420. this.func = func;
  24421. }
  24422. ExecuteCodeAction.prototype.execute = function (evt) {
  24423. this.func(evt);
  24424. };
  24425. return ExecuteCodeAction;
  24426. })(BABYLON.Action);
  24427. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24428. var SetParentAction = (function (_super) {
  24429. __extends(SetParentAction, _super);
  24430. function SetParentAction(triggerOptions, target, parent, condition) {
  24431. _super.call(this, triggerOptions, condition);
  24432. this._target = target;
  24433. this._parent = parent;
  24434. }
  24435. SetParentAction.prototype._prepare = function () {
  24436. };
  24437. SetParentAction.prototype.execute = function () {
  24438. if (this._target.parent === this._parent) {
  24439. return;
  24440. }
  24441. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24442. invertParentWorldMatrix.invert();
  24443. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24444. this._target.parent = this._parent;
  24445. };
  24446. return SetParentAction;
  24447. })(BABYLON.Action);
  24448. BABYLON.SetParentAction = SetParentAction;
  24449. var PlaySoundAction = (function (_super) {
  24450. __extends(PlaySoundAction, _super);
  24451. function PlaySoundAction(triggerOptions, sound, condition) {
  24452. _super.call(this, triggerOptions, condition);
  24453. this._sound = sound;
  24454. }
  24455. PlaySoundAction.prototype._prepare = function () {
  24456. };
  24457. PlaySoundAction.prototype.execute = function () {
  24458. if (this._sound !== undefined)
  24459. this._sound.play();
  24460. };
  24461. return PlaySoundAction;
  24462. })(BABYLON.Action);
  24463. BABYLON.PlaySoundAction = PlaySoundAction;
  24464. var StopSoundAction = (function (_super) {
  24465. __extends(StopSoundAction, _super);
  24466. function StopSoundAction(triggerOptions, sound, condition) {
  24467. _super.call(this, triggerOptions, condition);
  24468. this._sound = sound;
  24469. }
  24470. StopSoundAction.prototype._prepare = function () {
  24471. };
  24472. StopSoundAction.prototype.execute = function () {
  24473. if (this._sound !== undefined)
  24474. this._sound.stop();
  24475. };
  24476. return StopSoundAction;
  24477. })(BABYLON.Action);
  24478. BABYLON.StopSoundAction = StopSoundAction;
  24479. })(BABYLON || (BABYLON = {}));
  24480. //# sourceMappingURL=babylon.directActions.js.map
  24481. var BABYLON;
  24482. (function (BABYLON) {
  24483. var Geometry = (function () {
  24484. function Geometry(id, scene, vertexData, updatable, mesh) {
  24485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24486. this._totalVertices = 0;
  24487. this._indices = [];
  24488. this.id = id;
  24489. this._engine = scene.getEngine();
  24490. this._meshes = [];
  24491. this._scene = scene;
  24492. // vertexData
  24493. if (vertexData) {
  24494. this.setAllVerticesData(vertexData, updatable);
  24495. }
  24496. else {
  24497. this._totalVertices = 0;
  24498. this._indices = [];
  24499. }
  24500. // applyToMesh
  24501. if (mesh) {
  24502. this.applyToMesh(mesh);
  24503. mesh.computeWorldMatrix(true);
  24504. }
  24505. }
  24506. Geometry.prototype.getScene = function () {
  24507. return this._scene;
  24508. };
  24509. Geometry.prototype.getEngine = function () {
  24510. return this._engine;
  24511. };
  24512. Geometry.prototype.isReady = function () {
  24513. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24514. };
  24515. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24516. vertexData.applyToGeometry(this, updatable);
  24517. };
  24518. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24519. this._vertexBuffers = this._vertexBuffers || {};
  24520. if (this._vertexBuffers[kind]) {
  24521. this._vertexBuffers[kind].dispose();
  24522. }
  24523. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24524. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24525. stride = this._vertexBuffers[kind].getStrideSize();
  24526. this._totalVertices = data.length / stride;
  24527. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24528. var meshes = this._meshes;
  24529. var numOfMeshes = meshes.length;
  24530. for (var index = 0; index < numOfMeshes; index++) {
  24531. var mesh = meshes[index];
  24532. mesh._resetPointsArrayCache();
  24533. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24534. mesh._createGlobalSubMesh();
  24535. mesh.computeWorldMatrix(true);
  24536. }
  24537. }
  24538. };
  24539. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24540. var vertexBuffer = this.getVertexBuffer(kind);
  24541. if (!vertexBuffer) {
  24542. return;
  24543. }
  24544. vertexBuffer.updateDirectly(data, offset);
  24545. };
  24546. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24547. var vertexBuffer = this.getVertexBuffer(kind);
  24548. if (!vertexBuffer) {
  24549. return;
  24550. }
  24551. vertexBuffer.update(data);
  24552. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24553. var extend;
  24554. var stride = vertexBuffer.getStrideSize();
  24555. this._totalVertices = data.length / stride;
  24556. if (updateExtends) {
  24557. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24558. }
  24559. var meshes = this._meshes;
  24560. var numOfMeshes = meshes.length;
  24561. for (var index = 0; index < numOfMeshes; index++) {
  24562. var mesh = meshes[index];
  24563. mesh._resetPointsArrayCache();
  24564. if (updateExtends) {
  24565. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24566. }
  24567. }
  24568. }
  24569. };
  24570. Geometry.prototype.getTotalVertices = function () {
  24571. if (!this.isReady()) {
  24572. return 0;
  24573. }
  24574. return this._totalVertices;
  24575. };
  24576. Geometry.prototype.getVerticesData = function (kind) {
  24577. var vertexBuffer = this.getVertexBuffer(kind);
  24578. if (!vertexBuffer) {
  24579. return null;
  24580. }
  24581. return vertexBuffer.getData();
  24582. };
  24583. Geometry.prototype.getVertexBuffer = function (kind) {
  24584. if (!this.isReady()) {
  24585. return null;
  24586. }
  24587. return this._vertexBuffers[kind];
  24588. };
  24589. Geometry.prototype.getVertexBuffers = function () {
  24590. if (!this.isReady()) {
  24591. return null;
  24592. }
  24593. return this._vertexBuffers;
  24594. };
  24595. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24596. if (!this._vertexBuffers) {
  24597. if (this._delayInfo) {
  24598. return this._delayInfo.indexOf(kind) !== -1;
  24599. }
  24600. return false;
  24601. }
  24602. return this._vertexBuffers[kind] !== undefined;
  24603. };
  24604. Geometry.prototype.getVerticesDataKinds = function () {
  24605. var result = [];
  24606. if (!this._vertexBuffers && this._delayInfo) {
  24607. for (var kind in this._delayInfo) {
  24608. result.push(kind);
  24609. }
  24610. }
  24611. else {
  24612. for (kind in this._vertexBuffers) {
  24613. result.push(kind);
  24614. }
  24615. }
  24616. return result;
  24617. };
  24618. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24619. if (this._indexBuffer) {
  24620. this._engine._releaseBuffer(this._indexBuffer);
  24621. }
  24622. this._indices = indices;
  24623. if (this._meshes.length !== 0 && this._indices) {
  24624. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24625. }
  24626. if (totalVertices !== undefined) {
  24627. this._totalVertices = totalVertices;
  24628. }
  24629. var meshes = this._meshes;
  24630. var numOfMeshes = meshes.length;
  24631. for (var index = 0; index < numOfMeshes; index++) {
  24632. meshes[index]._createGlobalSubMesh();
  24633. }
  24634. };
  24635. Geometry.prototype.getTotalIndices = function () {
  24636. if (!this.isReady()) {
  24637. return 0;
  24638. }
  24639. return this._indices.length;
  24640. };
  24641. Geometry.prototype.getIndices = function () {
  24642. if (!this.isReady()) {
  24643. return null;
  24644. }
  24645. return this._indices;
  24646. };
  24647. Geometry.prototype.getIndexBuffer = function () {
  24648. if (!this.isReady()) {
  24649. return null;
  24650. }
  24651. return this._indexBuffer;
  24652. };
  24653. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24654. var meshes = this._meshes;
  24655. var index = meshes.indexOf(mesh);
  24656. if (index === -1) {
  24657. return;
  24658. }
  24659. for (var kind in this._vertexBuffers) {
  24660. this._vertexBuffers[kind].dispose();
  24661. }
  24662. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24663. this._indexBuffer = null;
  24664. }
  24665. meshes.splice(index, 1);
  24666. mesh._geometry = null;
  24667. if (meshes.length === 0 && shouldDispose) {
  24668. this.dispose();
  24669. }
  24670. };
  24671. Geometry.prototype.applyToMesh = function (mesh) {
  24672. if (mesh._geometry === this) {
  24673. return;
  24674. }
  24675. var previousGeometry = mesh._geometry;
  24676. if (previousGeometry) {
  24677. previousGeometry.releaseForMesh(mesh);
  24678. }
  24679. var meshes = this._meshes;
  24680. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24681. mesh._geometry = this;
  24682. this._scene.pushGeometry(this);
  24683. meshes.push(mesh);
  24684. if (this.isReady()) {
  24685. this._applyToMesh(mesh);
  24686. }
  24687. else {
  24688. mesh._boundingInfo = this._boundingInfo;
  24689. }
  24690. };
  24691. Geometry.prototype._applyToMesh = function (mesh) {
  24692. var numOfMeshes = this._meshes.length;
  24693. for (var kind in this._vertexBuffers) {
  24694. if (numOfMeshes === 1) {
  24695. this._vertexBuffers[kind].create();
  24696. }
  24697. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24698. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24699. mesh._resetPointsArrayCache();
  24700. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24701. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24702. mesh._createGlobalSubMesh();
  24703. //bounding info was just created again, world matrix should be applied again.
  24704. mesh._updateBoundingInfo();
  24705. }
  24706. }
  24707. // indexBuffer
  24708. if (numOfMeshes === 1 && this._indices) {
  24709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24710. }
  24711. if (this._indexBuffer) {
  24712. this._indexBuffer.references = numOfMeshes;
  24713. }
  24714. };
  24715. Geometry.prototype.load = function (scene, onLoaded) {
  24716. var _this = this;
  24717. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24718. return;
  24719. }
  24720. if (this.isReady()) {
  24721. if (onLoaded) {
  24722. onLoaded();
  24723. }
  24724. return;
  24725. }
  24726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24727. scene._addPendingData(this);
  24728. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24729. _this._delayLoadingFunction(JSON.parse(data), _this);
  24730. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24731. _this._delayInfo = [];
  24732. scene._removePendingData(_this);
  24733. var meshes = _this._meshes;
  24734. var numOfMeshes = meshes.length;
  24735. for (var index = 0; index < numOfMeshes; index++) {
  24736. _this._applyToMesh(meshes[index]);
  24737. }
  24738. if (onLoaded) {
  24739. onLoaded();
  24740. }
  24741. }, function () {
  24742. }, scene.database);
  24743. };
  24744. Geometry.prototype.dispose = function () {
  24745. var meshes = this._meshes;
  24746. var numOfMeshes = meshes.length;
  24747. var index;
  24748. for (index = 0; index < numOfMeshes; index++) {
  24749. this.releaseForMesh(meshes[index]);
  24750. }
  24751. this._meshes = [];
  24752. for (var kind in this._vertexBuffers) {
  24753. this._vertexBuffers[kind].dispose();
  24754. }
  24755. this._vertexBuffers = [];
  24756. this._totalVertices = 0;
  24757. if (this._indexBuffer) {
  24758. this._engine._releaseBuffer(this._indexBuffer);
  24759. }
  24760. this._indexBuffer = null;
  24761. this._indices = [];
  24762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24763. this.delayLoadingFile = null;
  24764. this._delayLoadingFunction = null;
  24765. this._delayInfo = [];
  24766. this._boundingInfo = null; // todo: .dispose()
  24767. var geometries = this._scene.getGeometries();
  24768. index = geometries.indexOf(this);
  24769. if (index > -1) {
  24770. geometries.splice(index, 1);
  24771. }
  24772. };
  24773. Geometry.prototype.copy = function (id) {
  24774. var vertexData = new BABYLON.VertexData();
  24775. vertexData.indices = [];
  24776. var indices = this.getIndices();
  24777. for (var index = 0; index < indices.length; index++) {
  24778. vertexData.indices.push(indices[index]);
  24779. }
  24780. var updatable = false;
  24781. var stopChecking = false;
  24782. for (var kind in this._vertexBuffers) {
  24783. vertexData.set(this.getVerticesData(kind), kind);
  24784. if (!stopChecking) {
  24785. updatable = this.getVertexBuffer(kind).isUpdatable();
  24786. stopChecking = !updatable;
  24787. }
  24788. }
  24789. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24790. geometry.delayLoadState = this.delayLoadState;
  24791. geometry.delayLoadingFile = this.delayLoadingFile;
  24792. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24793. for (kind in this._delayInfo) {
  24794. geometry._delayInfo = geometry._delayInfo || [];
  24795. geometry._delayInfo.push(kind);
  24796. }
  24797. // Bounding info
  24798. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24799. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24800. return geometry;
  24801. };
  24802. // Statics
  24803. Geometry.ExtractFromMesh = function (mesh, id) {
  24804. var geometry = mesh._geometry;
  24805. if (!geometry) {
  24806. return null;
  24807. }
  24808. return geometry.copy(id);
  24809. };
  24810. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24811. // be aware Math.random() could cause collisions
  24812. Geometry.RandomId = function () {
  24813. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24814. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24815. return v.toString(16);
  24816. });
  24817. };
  24818. return Geometry;
  24819. })();
  24820. BABYLON.Geometry = Geometry;
  24821. /////// Primitives //////////////////////////////////////////////
  24822. var Geometry;
  24823. (function (Geometry) {
  24824. var Primitives;
  24825. (function (Primitives) {
  24826. /// Abstract class
  24827. var _Primitive = (function (_super) {
  24828. __extends(_Primitive, _super);
  24829. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24830. this._beingRegenerated = true;
  24831. this._canBeRegenerated = canBeRegenerated;
  24832. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24833. this._beingRegenerated = false;
  24834. }
  24835. _Primitive.prototype.canBeRegenerated = function () {
  24836. return this._canBeRegenerated;
  24837. };
  24838. _Primitive.prototype.regenerate = function () {
  24839. if (!this._canBeRegenerated) {
  24840. return;
  24841. }
  24842. this._beingRegenerated = true;
  24843. this.setAllVerticesData(this._regenerateVertexData(), false);
  24844. this._beingRegenerated = false;
  24845. };
  24846. _Primitive.prototype.asNewGeometry = function (id) {
  24847. return _super.prototype.copy.call(this, id);
  24848. };
  24849. // overrides
  24850. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24851. if (!this._beingRegenerated) {
  24852. return;
  24853. }
  24854. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24855. };
  24856. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24857. if (!this._beingRegenerated) {
  24858. return;
  24859. }
  24860. _super.prototype.setVerticesData.call(this, kind, data, false);
  24861. };
  24862. // to override
  24863. // protected
  24864. _Primitive.prototype._regenerateVertexData = function () {
  24865. throw new Error("Abstract method");
  24866. };
  24867. _Primitive.prototype.copy = function (id) {
  24868. throw new Error("Must be overriden in sub-classes.");
  24869. };
  24870. return _Primitive;
  24871. })(Geometry);
  24872. Primitives._Primitive = _Primitive;
  24873. var Ribbon = (function (_super) {
  24874. __extends(Ribbon, _super);
  24875. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24876. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24877. this.pathArray = pathArray;
  24878. this.closeArray = closeArray;
  24879. this.closePath = closePath;
  24880. this.offset = offset;
  24881. this.side = side;
  24882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24883. }
  24884. Ribbon.prototype._regenerateVertexData = function () {
  24885. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24886. };
  24887. Ribbon.prototype.copy = function (id) {
  24888. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24889. };
  24890. return Ribbon;
  24891. })(_Primitive);
  24892. Primitives.Ribbon = Ribbon;
  24893. var Box = (function (_super) {
  24894. __extends(Box, _super);
  24895. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24897. this.size = size;
  24898. this.side = side;
  24899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24900. }
  24901. Box.prototype._regenerateVertexData = function () {
  24902. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24903. };
  24904. Box.prototype.copy = function (id) {
  24905. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24906. };
  24907. return Box;
  24908. })(_Primitive);
  24909. Primitives.Box = Box;
  24910. var Sphere = (function (_super) {
  24911. __extends(Sphere, _super);
  24912. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24914. this.segments = segments;
  24915. this.diameter = diameter;
  24916. this.side = side;
  24917. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24918. }
  24919. Sphere.prototype._regenerateVertexData = function () {
  24920. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24921. };
  24922. Sphere.prototype.copy = function (id) {
  24923. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24924. };
  24925. return Sphere;
  24926. })(_Primitive);
  24927. Primitives.Sphere = Sphere;
  24928. var Cylinder = (function (_super) {
  24929. __extends(Cylinder, _super);
  24930. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24931. if (subdivisions === void 0) { subdivisions = 1; }
  24932. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24933. this.height = height;
  24934. this.diameterTop = diameterTop;
  24935. this.diameterBottom = diameterBottom;
  24936. this.tessellation = tessellation;
  24937. this.subdivisions = subdivisions;
  24938. this.side = side;
  24939. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24940. }
  24941. Cylinder.prototype._regenerateVertexData = function () {
  24942. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24943. };
  24944. Cylinder.prototype.copy = function (id) {
  24945. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24946. };
  24947. return Cylinder;
  24948. })(_Primitive);
  24949. Primitives.Cylinder = Cylinder;
  24950. var Torus = (function (_super) {
  24951. __extends(Torus, _super);
  24952. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24953. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24954. this.diameter = diameter;
  24955. this.thickness = thickness;
  24956. this.tessellation = tessellation;
  24957. this.side = side;
  24958. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24959. }
  24960. Torus.prototype._regenerateVertexData = function () {
  24961. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24962. };
  24963. Torus.prototype.copy = function (id) {
  24964. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24965. };
  24966. return Torus;
  24967. })(_Primitive);
  24968. Primitives.Torus = Torus;
  24969. var Ground = (function (_super) {
  24970. __extends(Ground, _super);
  24971. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24972. this.width = width;
  24973. this.height = height;
  24974. this.subdivisions = subdivisions;
  24975. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24976. }
  24977. Ground.prototype._regenerateVertexData = function () {
  24978. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24979. };
  24980. Ground.prototype.copy = function (id) {
  24981. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24982. };
  24983. return Ground;
  24984. })(_Primitive);
  24985. Primitives.Ground = Ground;
  24986. var TiledGround = (function (_super) {
  24987. __extends(TiledGround, _super);
  24988. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24989. this.xmin = xmin;
  24990. this.zmin = zmin;
  24991. this.xmax = xmax;
  24992. this.zmax = zmax;
  24993. this.subdivisions = subdivisions;
  24994. this.precision = precision;
  24995. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24996. }
  24997. TiledGround.prototype._regenerateVertexData = function () {
  24998. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24999. };
  25000. TiledGround.prototype.copy = function (id) {
  25001. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25002. };
  25003. return TiledGround;
  25004. })(_Primitive);
  25005. Primitives.TiledGround = TiledGround;
  25006. var Plane = (function (_super) {
  25007. __extends(Plane, _super);
  25008. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25009. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25010. this.size = size;
  25011. this.side = side;
  25012. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25013. }
  25014. Plane.prototype._regenerateVertexData = function () {
  25015. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25016. };
  25017. Plane.prototype.copy = function (id) {
  25018. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25019. };
  25020. return Plane;
  25021. })(_Primitive);
  25022. Primitives.Plane = Plane;
  25023. var TorusKnot = (function (_super) {
  25024. __extends(TorusKnot, _super);
  25025. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25026. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25027. this.radius = radius;
  25028. this.tube = tube;
  25029. this.radialSegments = radialSegments;
  25030. this.tubularSegments = tubularSegments;
  25031. this.p = p;
  25032. this.q = q;
  25033. this.side = side;
  25034. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25035. }
  25036. TorusKnot.prototype._regenerateVertexData = function () {
  25037. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25038. };
  25039. TorusKnot.prototype.copy = function (id) {
  25040. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25041. };
  25042. return TorusKnot;
  25043. })(_Primitive);
  25044. Primitives.TorusKnot = TorusKnot;
  25045. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25046. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25047. })(BABYLON || (BABYLON = {}));
  25048. //# sourceMappingURL=babylon.geometry.js.map
  25049. var BABYLON;
  25050. (function (BABYLON) {
  25051. var Gamepads = (function () {
  25052. function Gamepads(ongamedpadconnected) {
  25053. var _this = this;
  25054. this.babylonGamepads = [];
  25055. this.oneGamepadConnected = false;
  25056. this.isMonitoring = false;
  25057. this.gamepadEventSupported = 'GamepadEvent' in window;
  25058. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25059. 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=";
  25060. this._callbackGamepadConnected = ongamedpadconnected;
  25061. if (this.gamepadSupportAvailable) {
  25062. // Checking if the gamepad connected event is supported (like in Firefox)
  25063. if (this.gamepadEventSupported) {
  25064. window.addEventListener('gamepadconnected', function (evt) {
  25065. _this._onGamepadConnected(evt);
  25066. }, false);
  25067. window.addEventListener('gamepaddisconnected', function (evt) {
  25068. _this._onGamepadDisconnected(evt);
  25069. }, false);
  25070. }
  25071. else {
  25072. this._startMonitoringGamepads();
  25073. }
  25074. if (!this.oneGamepadConnected) {
  25075. this._insertGamepadDOMInstructions();
  25076. }
  25077. }
  25078. else {
  25079. this._insertGamepadDOMNotSupported();
  25080. }
  25081. }
  25082. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25083. Gamepads.gamepadDOMInfo = document.createElement("div");
  25084. var buttonAImage = document.createElement("img");
  25085. buttonAImage.src = this.buttonADataURL;
  25086. var spanMessage = document.createElement("span");
  25087. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25088. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25089. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25090. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25091. Gamepads.gamepadDOMInfo.style.width = "100%";
  25092. Gamepads.gamepadDOMInfo.style.height = "48px";
  25093. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25094. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25095. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25096. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25097. buttonAImage.style.position = "relative";
  25098. buttonAImage.style.bottom = "8px";
  25099. spanMessage.style.position = "relative";
  25100. spanMessage.style.fontSize = "32px";
  25101. spanMessage.style.bottom = "32px";
  25102. spanMessage.style.color = "green";
  25103. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25104. };
  25105. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25106. Gamepads.gamepadDOMInfo = document.createElement("div");
  25107. var spanMessage = document.createElement("span");
  25108. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25109. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25110. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25111. Gamepads.gamepadDOMInfo.style.width = "100%";
  25112. Gamepads.gamepadDOMInfo.style.height = "40px";
  25113. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25114. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25115. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25116. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25117. spanMessage.style.position = "relative";
  25118. spanMessage.style.fontSize = "32px";
  25119. spanMessage.style.color = "red";
  25120. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25121. };
  25122. Gamepads.prototype.dispose = function () {
  25123. if (Gamepads.gamepadDOMInfo) {
  25124. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25125. }
  25126. };
  25127. Gamepads.prototype._onGamepadConnected = function (evt) {
  25128. var newGamepad = this._addNewGamepad(evt.gamepad);
  25129. if (this._callbackGamepadConnected)
  25130. this._callbackGamepadConnected(newGamepad);
  25131. this._startMonitoringGamepads();
  25132. };
  25133. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25134. if (!this.oneGamepadConnected) {
  25135. this.oneGamepadConnected = true;
  25136. if (Gamepads.gamepadDOMInfo) {
  25137. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25138. Gamepads.gamepadDOMInfo = null;
  25139. }
  25140. }
  25141. var newGamepad;
  25142. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25143. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25144. }
  25145. else {
  25146. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25147. }
  25148. this.babylonGamepads.push(newGamepad);
  25149. return newGamepad;
  25150. };
  25151. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25152. for (var i in this.babylonGamepads) {
  25153. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25154. this.babylonGamepads.splice(i, 1);
  25155. break;
  25156. }
  25157. }
  25158. // If no gamepads are left, stop the polling loop.
  25159. if (this.babylonGamepads.length == 0) {
  25160. this._stopMonitoringGamepads();
  25161. }
  25162. };
  25163. Gamepads.prototype._startMonitoringGamepads = function () {
  25164. if (!this.isMonitoring) {
  25165. this.isMonitoring = true;
  25166. this._checkGamepadsStatus();
  25167. }
  25168. };
  25169. Gamepads.prototype._stopMonitoringGamepads = function () {
  25170. this.isMonitoring = false;
  25171. };
  25172. Gamepads.prototype._checkGamepadsStatus = function () {
  25173. var _this = this;
  25174. // updating gamepad objects
  25175. this._updateGamepadObjects();
  25176. for (var i in this.babylonGamepads) {
  25177. this.babylonGamepads[i].update();
  25178. }
  25179. if (this.isMonitoring) {
  25180. if (window.requestAnimationFrame) {
  25181. window.requestAnimationFrame(function () {
  25182. _this._checkGamepadsStatus();
  25183. });
  25184. }
  25185. else if (window.mozRequestAnimationFrame) {
  25186. window.mozRequestAnimationFrame(function () {
  25187. _this._checkGamepadsStatus();
  25188. });
  25189. }
  25190. else if (window.webkitRequestAnimationFrame) {
  25191. window.webkitRequestAnimationFrame(function () {
  25192. _this._checkGamepadsStatus();
  25193. });
  25194. }
  25195. }
  25196. };
  25197. // This function is called only on Chrome, which does not yet support
  25198. // connection/disconnection events, but requires you to monitor
  25199. // an array for changes.
  25200. Gamepads.prototype._updateGamepadObjects = function () {
  25201. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25202. for (var i = 0; i < gamepads.length; i++) {
  25203. if (gamepads[i]) {
  25204. if (!(gamepads[i].index in this.babylonGamepads)) {
  25205. var newGamepad = this._addNewGamepad(gamepads[i]);
  25206. if (this._callbackGamepadConnected) {
  25207. this._callbackGamepadConnected(newGamepad);
  25208. }
  25209. }
  25210. else {
  25211. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25212. }
  25213. }
  25214. }
  25215. };
  25216. return Gamepads;
  25217. })();
  25218. BABYLON.Gamepads = Gamepads;
  25219. var StickValues = (function () {
  25220. function StickValues(x, y) {
  25221. this.x = x;
  25222. this.y = y;
  25223. }
  25224. return StickValues;
  25225. })();
  25226. BABYLON.StickValues = StickValues;
  25227. var Gamepad = (function () {
  25228. function Gamepad(id, index, browserGamepad) {
  25229. this.id = id;
  25230. this.index = index;
  25231. this.browserGamepad = browserGamepad;
  25232. if (this.browserGamepad.axes.length >= 2) {
  25233. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25234. }
  25235. if (this.browserGamepad.axes.length >= 4) {
  25236. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25237. }
  25238. }
  25239. Gamepad.prototype.onleftstickchanged = function (callback) {
  25240. this._onleftstickchanged = callback;
  25241. };
  25242. Gamepad.prototype.onrightstickchanged = function (callback) {
  25243. this._onrightstickchanged = callback;
  25244. };
  25245. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25246. get: function () {
  25247. return this._leftStick;
  25248. },
  25249. set: function (newValues) {
  25250. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25251. this._onleftstickchanged(newValues);
  25252. }
  25253. this._leftStick = newValues;
  25254. },
  25255. enumerable: true,
  25256. configurable: true
  25257. });
  25258. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25259. get: function () {
  25260. return this._rightStick;
  25261. },
  25262. set: function (newValues) {
  25263. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25264. this._onrightstickchanged(newValues);
  25265. }
  25266. this._rightStick = newValues;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Gamepad.prototype.update = function () {
  25272. if (this._leftStick) {
  25273. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25274. }
  25275. if (this._rightStick) {
  25276. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25277. }
  25278. };
  25279. return Gamepad;
  25280. })();
  25281. BABYLON.Gamepad = Gamepad;
  25282. var GenericPad = (function (_super) {
  25283. __extends(GenericPad, _super);
  25284. function GenericPad(id, index, gamepad) {
  25285. _super.call(this, id, index, gamepad);
  25286. this.id = id;
  25287. this.index = index;
  25288. this.gamepad = gamepad;
  25289. this._buttons = new Array(gamepad.buttons.length);
  25290. }
  25291. GenericPad.prototype.onbuttondown = function (callback) {
  25292. this._onbuttondown = callback;
  25293. };
  25294. GenericPad.prototype.onbuttonup = function (callback) {
  25295. this._onbuttonup = callback;
  25296. };
  25297. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25298. if (newValue !== currentValue) {
  25299. if (this._onbuttondown && newValue === 1) {
  25300. this._onbuttondown(buttonIndex);
  25301. }
  25302. if (this._onbuttonup && newValue === 0) {
  25303. this._onbuttonup(buttonIndex);
  25304. }
  25305. }
  25306. return newValue;
  25307. };
  25308. GenericPad.prototype.update = function () {
  25309. _super.prototype.update.call(this);
  25310. for (var index = 0; index < this._buttons.length; index++) {
  25311. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25312. }
  25313. };
  25314. return GenericPad;
  25315. })(Gamepad);
  25316. BABYLON.GenericPad = GenericPad;
  25317. (function (Xbox360Button) {
  25318. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25319. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25320. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25321. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25322. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25323. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25324. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25325. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25326. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25327. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25328. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25329. var Xbox360Button = BABYLON.Xbox360Button;
  25330. (function (Xbox360Dpad) {
  25331. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25332. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25333. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25334. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25335. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25336. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25337. var Xbox360Pad = (function (_super) {
  25338. __extends(Xbox360Pad, _super);
  25339. function Xbox360Pad() {
  25340. _super.apply(this, arguments);
  25341. this._leftTrigger = 0;
  25342. this._rightTrigger = 0;
  25343. this._buttonA = 0;
  25344. this._buttonB = 0;
  25345. this._buttonX = 0;
  25346. this._buttonY = 0;
  25347. this._buttonBack = 0;
  25348. this._buttonStart = 0;
  25349. this._buttonLB = 0;
  25350. this._buttonRB = 0;
  25351. this._buttonLeftStick = 0;
  25352. this._buttonRightStick = 0;
  25353. this._dPadUp = 0;
  25354. this._dPadDown = 0;
  25355. this._dPadLeft = 0;
  25356. this._dPadRight = 0;
  25357. }
  25358. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25359. this._onlefttriggerchanged = callback;
  25360. };
  25361. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25362. this._onrighttriggerchanged = callback;
  25363. };
  25364. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25365. get: function () {
  25366. return this._leftTrigger;
  25367. },
  25368. set: function (newValue) {
  25369. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25370. this._onlefttriggerchanged(newValue);
  25371. }
  25372. this._leftTrigger = newValue;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25378. get: function () {
  25379. return this._rightTrigger;
  25380. },
  25381. set: function (newValue) {
  25382. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25383. this._onrighttriggerchanged(newValue);
  25384. }
  25385. this._rightTrigger = newValue;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25391. this._onbuttondown = callback;
  25392. };
  25393. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25394. this._onbuttonup = callback;
  25395. };
  25396. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25397. this._ondpaddown = callback;
  25398. };
  25399. Xbox360Pad.prototype.ondpadup = function (callback) {
  25400. this._ondpadup = callback;
  25401. };
  25402. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25403. if (newValue !== currentValue) {
  25404. if (this._onbuttondown && newValue === 1) {
  25405. this._onbuttondown(buttonType);
  25406. }
  25407. if (this._onbuttonup && newValue === 0) {
  25408. this._onbuttonup(buttonType);
  25409. }
  25410. }
  25411. return newValue;
  25412. };
  25413. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25414. if (newValue !== currentValue) {
  25415. if (this._ondpaddown && newValue === 1) {
  25416. this._ondpaddown(buttonType);
  25417. }
  25418. if (this._ondpadup && newValue === 0) {
  25419. this._ondpadup(buttonType);
  25420. }
  25421. }
  25422. return newValue;
  25423. };
  25424. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25425. get: function () {
  25426. return this._buttonA;
  25427. },
  25428. set: function (value) {
  25429. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25430. },
  25431. enumerable: true,
  25432. configurable: true
  25433. });
  25434. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25435. get: function () {
  25436. return this._buttonB;
  25437. },
  25438. set: function (value) {
  25439. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25440. },
  25441. enumerable: true,
  25442. configurable: true
  25443. });
  25444. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25445. get: function () {
  25446. return this._buttonX;
  25447. },
  25448. set: function (value) {
  25449. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25455. get: function () {
  25456. return this._buttonY;
  25457. },
  25458. set: function (value) {
  25459. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25460. },
  25461. enumerable: true,
  25462. configurable: true
  25463. });
  25464. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25465. get: function () {
  25466. return this._buttonStart;
  25467. },
  25468. set: function (value) {
  25469. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25475. get: function () {
  25476. return this._buttonBack;
  25477. },
  25478. set: function (value) {
  25479. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25480. },
  25481. enumerable: true,
  25482. configurable: true
  25483. });
  25484. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25485. get: function () {
  25486. return this._buttonLB;
  25487. },
  25488. set: function (value) {
  25489. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25490. },
  25491. enumerable: true,
  25492. configurable: true
  25493. });
  25494. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25495. get: function () {
  25496. return this._buttonRB;
  25497. },
  25498. set: function (value) {
  25499. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25500. },
  25501. enumerable: true,
  25502. configurable: true
  25503. });
  25504. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25505. get: function () {
  25506. return this._buttonLeftStick;
  25507. },
  25508. set: function (value) {
  25509. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25510. },
  25511. enumerable: true,
  25512. configurable: true
  25513. });
  25514. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25515. get: function () {
  25516. return this._buttonRightStick;
  25517. },
  25518. set: function (value) {
  25519. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25520. },
  25521. enumerable: true,
  25522. configurable: true
  25523. });
  25524. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25525. get: function () {
  25526. return this._dPadUp;
  25527. },
  25528. set: function (value) {
  25529. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25535. get: function () {
  25536. return this._dPadDown;
  25537. },
  25538. set: function (value) {
  25539. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25540. },
  25541. enumerable: true,
  25542. configurable: true
  25543. });
  25544. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25545. get: function () {
  25546. return this._dPadLeft;
  25547. },
  25548. set: function (value) {
  25549. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25555. get: function () {
  25556. return this._dPadRight;
  25557. },
  25558. set: function (value) {
  25559. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25560. },
  25561. enumerable: true,
  25562. configurable: true
  25563. });
  25564. Xbox360Pad.prototype.update = function () {
  25565. _super.prototype.update.call(this);
  25566. this.buttonA = this.browserGamepad.buttons[0].value;
  25567. this.buttonB = this.browserGamepad.buttons[1].value;
  25568. this.buttonX = this.browserGamepad.buttons[2].value;
  25569. this.buttonY = this.browserGamepad.buttons[3].value;
  25570. this.buttonLB = this.browserGamepad.buttons[4].value;
  25571. this.buttonRB = this.browserGamepad.buttons[5].value;
  25572. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25573. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25574. this.buttonBack = this.browserGamepad.buttons[8].value;
  25575. this.buttonStart = this.browserGamepad.buttons[9].value;
  25576. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25577. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25578. this.dPadUp = this.browserGamepad.buttons[12].value;
  25579. this.dPadDown = this.browserGamepad.buttons[13].value;
  25580. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25581. this.dPadRight = this.browserGamepad.buttons[15].value;
  25582. };
  25583. return Xbox360Pad;
  25584. })(Gamepad);
  25585. BABYLON.Xbox360Pad = Xbox360Pad;
  25586. })(BABYLON || (BABYLON = {}));
  25587. //# sourceMappingURL=babylon.gamepads.js.map
  25588. var BABYLON;
  25589. (function (BABYLON) {
  25590. // We're mainly based on the logic defined into the FreeCamera code
  25591. var GamepadCamera = (function (_super) {
  25592. __extends(GamepadCamera, _super);
  25593. function GamepadCamera(name, position, scene) {
  25594. var _this = this;
  25595. _super.call(this, name, position, scene);
  25596. this.angularSensibility = 200;
  25597. this.moveSensibility = 75;
  25598. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25599. _this._onNewGameConnected(gamepad);
  25600. });
  25601. }
  25602. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25603. // Only the first gamepad can control the camera
  25604. if (gamepad.index === 0) {
  25605. this._gamepad = gamepad;
  25606. }
  25607. };
  25608. GamepadCamera.prototype._checkInputs = function () {
  25609. if (!this._gamepad) {
  25610. return;
  25611. }
  25612. var LSValues = this._gamepad.leftStick;
  25613. var normalizedLX = LSValues.x / this.moveSensibility;
  25614. var normalizedLY = LSValues.y / this.moveSensibility;
  25615. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25616. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25617. var RSValues = this._gamepad.rightStick;
  25618. var normalizedRX = RSValues.x / this.angularSensibility;
  25619. var normalizedRY = RSValues.y / this.angularSensibility;
  25620. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25621. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25622. ;
  25623. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25624. var speed = this._computeLocalCameraSpeed() * 50.0;
  25625. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25626. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25627. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25628. };
  25629. GamepadCamera.prototype.dispose = function () {
  25630. this._gamepads.dispose();
  25631. _super.prototype.dispose.call(this);
  25632. };
  25633. return GamepadCamera;
  25634. })(BABYLON.FreeCamera);
  25635. BABYLON.GamepadCamera = GamepadCamera;
  25636. })(BABYLON || (BABYLON = {}));
  25637. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25638. var BABYLON;
  25639. (function (BABYLON) {
  25640. var LinesMesh = (function (_super) {
  25641. __extends(LinesMesh, _super);
  25642. function LinesMesh(name, scene, updatable) {
  25643. if (updatable === void 0) { updatable = false; }
  25644. _super.call(this, name, scene);
  25645. this.color = new BABYLON.Color3(1, 1, 1);
  25646. this.alpha = 1;
  25647. this._indices = new Array();
  25648. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25649. attributes: ["position"],
  25650. uniforms: ["worldViewProjection", "color"],
  25651. needAlphaBlending: true
  25652. });
  25653. }
  25654. Object.defineProperty(LinesMesh.prototype, "material", {
  25655. get: function () {
  25656. return this._colorShader;
  25657. },
  25658. enumerable: true,
  25659. configurable: true
  25660. });
  25661. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25662. get: function () {
  25663. return false;
  25664. },
  25665. enumerable: true,
  25666. configurable: true
  25667. });
  25668. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25669. get: function () {
  25670. return false;
  25671. },
  25672. enumerable: true,
  25673. configurable: true
  25674. });
  25675. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25676. var engine = this.getScene().getEngine();
  25677. var indexToBind = this._geometry.getIndexBuffer();
  25678. // VBOs
  25679. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25680. // Color
  25681. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25682. };
  25683. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25684. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25685. return;
  25686. }
  25687. var engine = this.getScene().getEngine();
  25688. // Draw order
  25689. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25690. };
  25691. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25692. return null;
  25693. };
  25694. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25695. this._colorShader.dispose();
  25696. _super.prototype.dispose.call(this, doNotRecurse);
  25697. };
  25698. return LinesMesh;
  25699. })(BABYLON.Mesh);
  25700. BABYLON.LinesMesh = LinesMesh;
  25701. })(BABYLON || (BABYLON = {}));
  25702. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25703. (function (BABYLON) {
  25704. var OutlineRenderer = (function () {
  25705. function OutlineRenderer(scene) {
  25706. this._scene = scene;
  25707. }
  25708. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25709. var _this = this;
  25710. if (useOverlay === void 0) { useOverlay = false; }
  25711. var scene = this._scene;
  25712. var engine = this._scene.getEngine();
  25713. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25714. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25715. return;
  25716. }
  25717. var mesh = subMesh.getRenderingMesh();
  25718. var material = subMesh.getMaterial();
  25719. engine.enableEffect(this._effect);
  25720. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25721. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25722. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25723. // Bones
  25724. if (mesh.useBones) {
  25725. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25726. }
  25727. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25728. // Alpha test
  25729. if (material && material.needAlphaTesting()) {
  25730. var alphaTexture = material.getAlphaTestTexture();
  25731. this._effect.setTexture("diffuseSampler", alphaTexture);
  25732. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25733. }
  25734. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25735. _this._effect.setMatrix("world", world);
  25736. });
  25737. };
  25738. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25739. var defines = [];
  25740. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25741. var mesh = subMesh.getMesh();
  25742. var material = subMesh.getMaterial();
  25743. // Alpha test
  25744. if (material && material.needAlphaTesting()) {
  25745. defines.push("#define ALPHATEST");
  25746. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25747. attribs.push(BABYLON.VertexBuffer.UVKind);
  25748. defines.push("#define UV1");
  25749. }
  25750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25751. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25752. defines.push("#define UV2");
  25753. }
  25754. }
  25755. // Bones
  25756. if (mesh.useBones) {
  25757. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25758. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25759. defines.push("#define BONES");
  25760. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25761. }
  25762. // Instances
  25763. if (useInstances) {
  25764. defines.push("#define INSTANCES");
  25765. attribs.push("world0");
  25766. attribs.push("world1");
  25767. attribs.push("world2");
  25768. attribs.push("world3");
  25769. }
  25770. // Get correct effect
  25771. var join = defines.join("\n");
  25772. if (this._cachedDefines !== join) {
  25773. this._cachedDefines = join;
  25774. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25775. }
  25776. return this._effect.isReady();
  25777. };
  25778. return OutlineRenderer;
  25779. })();
  25780. BABYLON.OutlineRenderer = OutlineRenderer;
  25781. })(BABYLON || (BABYLON = {}));
  25782. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25783. (function (BABYLON) {
  25784. var MeshAssetTask = (function () {
  25785. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25786. this.name = name;
  25787. this.meshesNames = meshesNames;
  25788. this.rootUrl = rootUrl;
  25789. this.sceneFilename = sceneFilename;
  25790. this.isCompleted = false;
  25791. }
  25792. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25793. var _this = this;
  25794. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25795. _this.loadedMeshes = meshes;
  25796. _this.loadedParticleSystems = particleSystems;
  25797. _this.loadedSkeletons = skeletons;
  25798. _this.isCompleted = true;
  25799. if (_this.onSuccess) {
  25800. _this.onSuccess(_this);
  25801. }
  25802. onSuccess();
  25803. }, null, function () {
  25804. if (_this.onError) {
  25805. _this.onError(_this);
  25806. }
  25807. onError();
  25808. });
  25809. };
  25810. return MeshAssetTask;
  25811. })();
  25812. BABYLON.MeshAssetTask = MeshAssetTask;
  25813. var TextFileAssetTask = (function () {
  25814. function TextFileAssetTask(name, url) {
  25815. this.name = name;
  25816. this.url = url;
  25817. this.isCompleted = false;
  25818. }
  25819. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25820. var _this = this;
  25821. BABYLON.Tools.LoadFile(this.url, function (data) {
  25822. _this.text = data;
  25823. _this.isCompleted = true;
  25824. if (_this.onSuccess) {
  25825. _this.onSuccess(_this);
  25826. }
  25827. onSuccess();
  25828. }, null, scene.database, false, function () {
  25829. if (_this.onError) {
  25830. _this.onError(_this);
  25831. }
  25832. onError();
  25833. });
  25834. };
  25835. return TextFileAssetTask;
  25836. })();
  25837. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25838. var BinaryFileAssetTask = (function () {
  25839. function BinaryFileAssetTask(name, url) {
  25840. this.name = name;
  25841. this.url = url;
  25842. this.isCompleted = false;
  25843. }
  25844. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25845. var _this = this;
  25846. BABYLON.Tools.LoadFile(this.url, function (data) {
  25847. _this.data = data;
  25848. _this.isCompleted = true;
  25849. if (_this.onSuccess) {
  25850. _this.onSuccess(_this);
  25851. }
  25852. onSuccess();
  25853. }, null, scene.database, true, function () {
  25854. if (_this.onError) {
  25855. _this.onError(_this);
  25856. }
  25857. onError();
  25858. });
  25859. };
  25860. return BinaryFileAssetTask;
  25861. })();
  25862. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25863. var ImageAssetTask = (function () {
  25864. function ImageAssetTask(name, url) {
  25865. this.name = name;
  25866. this.url = url;
  25867. this.isCompleted = false;
  25868. }
  25869. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25870. var _this = this;
  25871. var img = new Image();
  25872. img.onload = function () {
  25873. _this.image = img;
  25874. _this.isCompleted = true;
  25875. if (_this.onSuccess) {
  25876. _this.onSuccess(_this);
  25877. }
  25878. onSuccess();
  25879. };
  25880. img.onerror = function () {
  25881. if (_this.onError) {
  25882. _this.onError(_this);
  25883. }
  25884. onError();
  25885. };
  25886. img.src = this.url;
  25887. };
  25888. return ImageAssetTask;
  25889. })();
  25890. BABYLON.ImageAssetTask = ImageAssetTask;
  25891. var TextureAssetTask = (function () {
  25892. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25894. this.name = name;
  25895. this.url = url;
  25896. this.noMipmap = noMipmap;
  25897. this.invertY = invertY;
  25898. this.samplingMode = samplingMode;
  25899. this.isCompleted = false;
  25900. }
  25901. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25902. var _this = this;
  25903. var onload = function () {
  25904. _this.isCompleted = true;
  25905. if (_this.onSuccess) {
  25906. _this.onSuccess(_this);
  25907. }
  25908. onSuccess();
  25909. };
  25910. var onerror = function () {
  25911. if (_this.onError) {
  25912. _this.onError(_this);
  25913. }
  25914. onError();
  25915. };
  25916. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25917. };
  25918. return TextureAssetTask;
  25919. })();
  25920. BABYLON.TextureAssetTask = TextureAssetTask;
  25921. var AssetsManager = (function () {
  25922. function AssetsManager(scene) {
  25923. this._tasks = new Array();
  25924. this._waitingTasksCount = 0;
  25925. this.useDefaultLoadingScreen = true;
  25926. this._scene = scene;
  25927. }
  25928. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25929. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25930. this._tasks.push(task);
  25931. return task;
  25932. };
  25933. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25934. var task = new TextFileAssetTask(taskName, url);
  25935. this._tasks.push(task);
  25936. return task;
  25937. };
  25938. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25939. var task = new BinaryFileAssetTask(taskName, url);
  25940. this._tasks.push(task);
  25941. return task;
  25942. };
  25943. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25944. var task = new ImageAssetTask(taskName, url);
  25945. this._tasks.push(task);
  25946. return task;
  25947. };
  25948. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25950. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25951. this._tasks.push(task);
  25952. return task;
  25953. };
  25954. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25955. this._waitingTasksCount--;
  25956. if (this._waitingTasksCount === 0) {
  25957. if (this.onFinish) {
  25958. this.onFinish(this._tasks);
  25959. }
  25960. this._scene.getEngine().hideLoadingUI();
  25961. }
  25962. };
  25963. AssetsManager.prototype._runTask = function (task) {
  25964. var _this = this;
  25965. task.run(this._scene, function () {
  25966. if (_this.onTaskSuccess) {
  25967. _this.onTaskSuccess(task);
  25968. }
  25969. _this._decreaseWaitingTasksCount();
  25970. }, function () {
  25971. if (_this.onTaskError) {
  25972. _this.onTaskError(task);
  25973. }
  25974. _this._decreaseWaitingTasksCount();
  25975. });
  25976. };
  25977. AssetsManager.prototype.reset = function () {
  25978. this._tasks = new Array();
  25979. return this;
  25980. };
  25981. AssetsManager.prototype.load = function () {
  25982. this._waitingTasksCount = this._tasks.length;
  25983. if (this._waitingTasksCount === 0) {
  25984. if (this.onFinish) {
  25985. this.onFinish(this._tasks);
  25986. }
  25987. return this;
  25988. }
  25989. if (this.useDefaultLoadingScreen) {
  25990. this._scene.getEngine().displayLoadingUI();
  25991. }
  25992. for (var index = 0; index < this._tasks.length; index++) {
  25993. var task = this._tasks[index];
  25994. this._runTask(task);
  25995. }
  25996. return this;
  25997. };
  25998. return AssetsManager;
  25999. })();
  26000. BABYLON.AssetsManager = AssetsManager;
  26001. })(BABYLON || (BABYLON = {}));
  26002. //# sourceMappingURL=babylon.assetsManager.js.map
  26003. var BABYLON;
  26004. (function (BABYLON) {
  26005. var VRDeviceOrientationCamera = (function (_super) {
  26006. __extends(VRDeviceOrientationCamera, _super);
  26007. function VRDeviceOrientationCamera(name, position, scene) {
  26008. _super.call(this, name, position, scene);
  26009. this._alpha = 0;
  26010. this._beta = 0;
  26011. this._gamma = 0;
  26012. }
  26013. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26014. this._alpha = +evt.alpha | 0;
  26015. this._beta = +evt.beta | 0;
  26016. this._gamma = +evt.gamma | 0;
  26017. if (this._gamma < 0) {
  26018. this._gamma = 90 + this._gamma;
  26019. }
  26020. else {
  26021. // Incline it in the correct angle.
  26022. this._gamma = 270 - this._gamma;
  26023. }
  26024. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26025. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26026. this.rotation.z = this._beta / 180.0 * Math.PI;
  26027. };
  26028. return VRDeviceOrientationCamera;
  26029. })(BABYLON.OculusCamera);
  26030. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26031. })(BABYLON || (BABYLON = {}));
  26032. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26033. var BABYLON;
  26034. (function (BABYLON) {
  26035. var WebVRCamera = (function (_super) {
  26036. __extends(WebVRCamera, _super);
  26037. function WebVRCamera(name, position, scene) {
  26038. _super.call(this, name, position, scene);
  26039. this._hmdDevice = null;
  26040. this._sensorDevice = null;
  26041. this._cacheState = null;
  26042. this._cacheQuaternion = new BABYLON.Quaternion();
  26043. this._cacheRotation = BABYLON.Vector3.Zero();
  26044. this._vrEnabled = false;
  26045. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26046. }
  26047. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26048. var size = devices.length;
  26049. var i = 0;
  26050. // Reset devices.
  26051. this._sensorDevice = null;
  26052. this._hmdDevice = null;
  26053. while (i < size && this._hmdDevice === null) {
  26054. if (devices[i] instanceof HMDVRDevice) {
  26055. this._hmdDevice = devices[i];
  26056. }
  26057. i++;
  26058. }
  26059. i = 0;
  26060. while (i < size && this._sensorDevice === null) {
  26061. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26062. this._sensorDevice = devices[i];
  26063. }
  26064. i++;
  26065. }
  26066. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26067. };
  26068. WebVRCamera.prototype._update = function () {
  26069. if (this._vrEnabled) {
  26070. this._cacheState = this._sensorDevice.getState();
  26071. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26072. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26073. this.rotation.x = -this._cacheRotation.z;
  26074. this.rotation.y = -this._cacheRotation.y;
  26075. this.rotation.z = this._cacheRotation.x;
  26076. }
  26077. _super.prototype._update.call(this);
  26078. };
  26079. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26080. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26081. if (navigator.getVRDevices) {
  26082. navigator.getVRDevices().then(this._getWebVRDevices);
  26083. }
  26084. else if (navigator.mozGetVRDevices) {
  26085. navigator.mozGetVRDevices(this._getWebVRDevices);
  26086. }
  26087. };
  26088. WebVRCamera.prototype.detachControl = function (element) {
  26089. _super.prototype.detachControl.call(this, element);
  26090. this._vrEnabled = false;
  26091. };
  26092. return WebVRCamera;
  26093. })(BABYLON.OculusCamera);
  26094. BABYLON.WebVRCamera = WebVRCamera;
  26095. })(BABYLON || (BABYLON = {}));
  26096. //# sourceMappingURL=babylon.webVRCamera.js.map
  26097. var BABYLON;
  26098. (function (BABYLON) {
  26099. // Standard optimizations
  26100. var SceneOptimization = (function () {
  26101. function SceneOptimization(priority) {
  26102. if (priority === void 0) { priority = 0; }
  26103. this.priority = priority;
  26104. this.apply = function (scene) {
  26105. return true; // Return true if everything that can be done was applied
  26106. };
  26107. }
  26108. return SceneOptimization;
  26109. })();
  26110. BABYLON.SceneOptimization = SceneOptimization;
  26111. var TextureOptimization = (function (_super) {
  26112. __extends(TextureOptimization, _super);
  26113. function TextureOptimization(priority, maximumSize) {
  26114. var _this = this;
  26115. if (priority === void 0) { priority = 0; }
  26116. if (maximumSize === void 0) { maximumSize = 1024; }
  26117. _super.call(this, priority);
  26118. this.priority = priority;
  26119. this.maximumSize = maximumSize;
  26120. this.apply = function (scene) {
  26121. var allDone = true;
  26122. for (var index = 0; index < scene.textures.length; index++) {
  26123. var texture = scene.textures[index];
  26124. if (!texture.canRescale) {
  26125. continue;
  26126. }
  26127. var currentSize = texture.getSize();
  26128. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26129. if (maxDimension > _this.maximumSize) {
  26130. texture.scale(0.5);
  26131. allDone = false;
  26132. }
  26133. }
  26134. return allDone;
  26135. };
  26136. }
  26137. return TextureOptimization;
  26138. })(SceneOptimization);
  26139. BABYLON.TextureOptimization = TextureOptimization;
  26140. var HardwareScalingOptimization = (function (_super) {
  26141. __extends(HardwareScalingOptimization, _super);
  26142. function HardwareScalingOptimization(priority, maximumScale) {
  26143. var _this = this;
  26144. if (priority === void 0) { priority = 0; }
  26145. if (maximumScale === void 0) { maximumScale = 2; }
  26146. _super.call(this, priority);
  26147. this.priority = priority;
  26148. this.maximumScale = maximumScale;
  26149. this._currentScale = 1;
  26150. this.apply = function (scene) {
  26151. _this._currentScale++;
  26152. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26153. return _this._currentScale >= _this.maximumScale;
  26154. };
  26155. }
  26156. return HardwareScalingOptimization;
  26157. })(SceneOptimization);
  26158. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26159. var ShadowsOptimization = (function (_super) {
  26160. __extends(ShadowsOptimization, _super);
  26161. function ShadowsOptimization() {
  26162. _super.apply(this, arguments);
  26163. this.apply = function (scene) {
  26164. scene.shadowsEnabled = false;
  26165. return true;
  26166. };
  26167. }
  26168. return ShadowsOptimization;
  26169. })(SceneOptimization);
  26170. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26171. var PostProcessesOptimization = (function (_super) {
  26172. __extends(PostProcessesOptimization, _super);
  26173. function PostProcessesOptimization() {
  26174. _super.apply(this, arguments);
  26175. this.apply = function (scene) {
  26176. scene.postProcessesEnabled = false;
  26177. return true;
  26178. };
  26179. }
  26180. return PostProcessesOptimization;
  26181. })(SceneOptimization);
  26182. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26183. var LensFlaresOptimization = (function (_super) {
  26184. __extends(LensFlaresOptimization, _super);
  26185. function LensFlaresOptimization() {
  26186. _super.apply(this, arguments);
  26187. this.apply = function (scene) {
  26188. scene.lensFlaresEnabled = false;
  26189. return true;
  26190. };
  26191. }
  26192. return LensFlaresOptimization;
  26193. })(SceneOptimization);
  26194. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26195. var ParticlesOptimization = (function (_super) {
  26196. __extends(ParticlesOptimization, _super);
  26197. function ParticlesOptimization() {
  26198. _super.apply(this, arguments);
  26199. this.apply = function (scene) {
  26200. scene.particlesEnabled = false;
  26201. return true;
  26202. };
  26203. }
  26204. return ParticlesOptimization;
  26205. })(SceneOptimization);
  26206. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26207. var RenderTargetsOptimization = (function (_super) {
  26208. __extends(RenderTargetsOptimization, _super);
  26209. function RenderTargetsOptimization() {
  26210. _super.apply(this, arguments);
  26211. this.apply = function (scene) {
  26212. scene.renderTargetsEnabled = false;
  26213. return true;
  26214. };
  26215. }
  26216. return RenderTargetsOptimization;
  26217. })(SceneOptimization);
  26218. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26219. var MergeMeshesOptimization = (function (_super) {
  26220. __extends(MergeMeshesOptimization, _super);
  26221. function MergeMeshesOptimization() {
  26222. var _this = this;
  26223. _super.apply(this, arguments);
  26224. this._canBeMerged = function (abstractMesh) {
  26225. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26226. return false;
  26227. }
  26228. var mesh = abstractMesh;
  26229. if (!mesh.isVisible || !mesh.isEnabled()) {
  26230. return false;
  26231. }
  26232. if (mesh.instances.length > 0) {
  26233. return false;
  26234. }
  26235. if (mesh.skeleton || mesh.hasLODLevels) {
  26236. return false;
  26237. }
  26238. return true;
  26239. };
  26240. this.apply = function (scene) {
  26241. var globalPool = scene.meshes.slice(0);
  26242. var globalLength = globalPool.length;
  26243. for (var index = 0; index < globalLength; index++) {
  26244. var currentPool = new Array();
  26245. var current = globalPool[index];
  26246. // Checks
  26247. if (!_this._canBeMerged(current)) {
  26248. continue;
  26249. }
  26250. currentPool.push(current);
  26251. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26252. var otherMesh = globalPool[subIndex];
  26253. if (!_this._canBeMerged(otherMesh)) {
  26254. continue;
  26255. }
  26256. if (otherMesh.material !== current.material) {
  26257. continue;
  26258. }
  26259. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26260. continue;
  26261. }
  26262. currentPool.push(otherMesh);
  26263. globalLength--;
  26264. globalPool.splice(subIndex, 1);
  26265. subIndex--;
  26266. }
  26267. if (currentPool.length < 2) {
  26268. continue;
  26269. }
  26270. // Merge meshes
  26271. BABYLON.Mesh.MergeMeshes(currentPool);
  26272. }
  26273. return true;
  26274. };
  26275. }
  26276. return MergeMeshesOptimization;
  26277. })(SceneOptimization);
  26278. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26279. // Options
  26280. var SceneOptimizerOptions = (function () {
  26281. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26282. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26283. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26284. this.targetFrameRate = targetFrameRate;
  26285. this.trackerDuration = trackerDuration;
  26286. this.optimizations = new Array();
  26287. }
  26288. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26289. var result = new SceneOptimizerOptions(targetFrameRate);
  26290. var priority = 0;
  26291. result.optimizations.push(new MergeMeshesOptimization(priority));
  26292. result.optimizations.push(new ShadowsOptimization(priority));
  26293. result.optimizations.push(new LensFlaresOptimization(priority));
  26294. // Next priority
  26295. priority++;
  26296. result.optimizations.push(new PostProcessesOptimization(priority));
  26297. result.optimizations.push(new ParticlesOptimization(priority));
  26298. // Next priority
  26299. priority++;
  26300. result.optimizations.push(new TextureOptimization(priority, 1024));
  26301. return result;
  26302. };
  26303. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26304. var result = new SceneOptimizerOptions(targetFrameRate);
  26305. var priority = 0;
  26306. result.optimizations.push(new MergeMeshesOptimization(priority));
  26307. result.optimizations.push(new ShadowsOptimization(priority));
  26308. result.optimizations.push(new LensFlaresOptimization(priority));
  26309. // Next priority
  26310. priority++;
  26311. result.optimizations.push(new PostProcessesOptimization(priority));
  26312. result.optimizations.push(new ParticlesOptimization(priority));
  26313. // Next priority
  26314. priority++;
  26315. result.optimizations.push(new TextureOptimization(priority, 512));
  26316. // Next priority
  26317. priority++;
  26318. result.optimizations.push(new RenderTargetsOptimization(priority));
  26319. // Next priority
  26320. priority++;
  26321. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26322. return result;
  26323. };
  26324. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26325. var result = new SceneOptimizerOptions(targetFrameRate);
  26326. var priority = 0;
  26327. result.optimizations.push(new MergeMeshesOptimization(priority));
  26328. result.optimizations.push(new ShadowsOptimization(priority));
  26329. result.optimizations.push(new LensFlaresOptimization(priority));
  26330. // Next priority
  26331. priority++;
  26332. result.optimizations.push(new PostProcessesOptimization(priority));
  26333. result.optimizations.push(new ParticlesOptimization(priority));
  26334. // Next priority
  26335. priority++;
  26336. result.optimizations.push(new TextureOptimization(priority, 256));
  26337. // Next priority
  26338. priority++;
  26339. result.optimizations.push(new RenderTargetsOptimization(priority));
  26340. // Next priority
  26341. priority++;
  26342. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26343. return result;
  26344. };
  26345. return SceneOptimizerOptions;
  26346. })();
  26347. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26348. // Scene optimizer tool
  26349. var SceneOptimizer = (function () {
  26350. function SceneOptimizer() {
  26351. }
  26352. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26353. // TODO: add an epsilon
  26354. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26355. if (onSuccess) {
  26356. onSuccess();
  26357. }
  26358. return;
  26359. }
  26360. // Apply current level of optimizations
  26361. var allDone = true;
  26362. var noOptimizationApplied = true;
  26363. for (var index = 0; index < options.optimizations.length; index++) {
  26364. var optimization = options.optimizations[index];
  26365. if (optimization.priority === currentPriorityLevel) {
  26366. noOptimizationApplied = false;
  26367. allDone = allDone && optimization.apply(scene);
  26368. }
  26369. }
  26370. // If no optimization was applied, this is a failure :(
  26371. if (noOptimizationApplied) {
  26372. if (onFailure) {
  26373. onFailure();
  26374. }
  26375. return;
  26376. }
  26377. // If all optimizations were done, move to next level
  26378. if (allDone) {
  26379. currentPriorityLevel++;
  26380. }
  26381. // Let's the system running for a specific amount of time before checking FPS
  26382. scene.executeWhenReady(function () {
  26383. setTimeout(function () {
  26384. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26385. }, options.trackerDuration);
  26386. });
  26387. };
  26388. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26389. if (!options) {
  26390. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26391. }
  26392. // Let's the system running for a specific amount of time before checking FPS
  26393. scene.executeWhenReady(function () {
  26394. setTimeout(function () {
  26395. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26396. }, options.trackerDuration);
  26397. });
  26398. };
  26399. return SceneOptimizer;
  26400. })();
  26401. BABYLON.SceneOptimizer = SceneOptimizer;
  26402. })(BABYLON || (BABYLON = {}));
  26403. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26404. (function (BABYLON) {
  26405. var Internals;
  26406. (function (Internals) {
  26407. var MeshLODLevel = (function () {
  26408. function MeshLODLevel(distance, mesh) {
  26409. this.distance = distance;
  26410. this.mesh = mesh;
  26411. }
  26412. return MeshLODLevel;
  26413. })();
  26414. Internals.MeshLODLevel = MeshLODLevel;
  26415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26416. })(BABYLON || (BABYLON = {}));
  26417. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26418. (function (BABYLON) {
  26419. var AudioEngine = (function () {
  26420. function AudioEngine() {
  26421. this.audioContext = null;
  26422. this.canUseWebAudio = false;
  26423. this.WarnedWebAudioUnsupported = false;
  26424. try {
  26425. if (typeof AudioContext !== 'undefined') {
  26426. this.audioContext = new AudioContext();
  26427. this.canUseWebAudio = true;
  26428. }
  26429. else if (typeof webkitAudioContext !== 'undefined') {
  26430. this.audioContext = new webkitAudioContext();
  26431. this.canUseWebAudio = true;
  26432. }
  26433. }
  26434. catch (e) {
  26435. this.canUseWebAudio = false;
  26436. BABYLON.Tools.Error("Web Audio: " + e.message);
  26437. }
  26438. // create a global volume gain node
  26439. if (this.canUseWebAudio) {
  26440. this.masterGain = this.audioContext.createGain();
  26441. this.masterGain.gain.value = 1;
  26442. this.masterGain.connect(this.audioContext.destination);
  26443. }
  26444. }
  26445. AudioEngine.prototype.dispose = function () {
  26446. if (this.canUseWebAudio) {
  26447. if (this._connectedAnalyser) {
  26448. this._connectedAnalyser.stopDebugCanvas();
  26449. this._connectedAnalyser.dispose();
  26450. this.masterGain.disconnect();
  26451. this.masterGain.connect(this.audioContext.destination);
  26452. this._connectedAnalyser = null;
  26453. }
  26454. this.masterGain.gain.value = 1;
  26455. }
  26456. this.WarnedWebAudioUnsupported = false;
  26457. };
  26458. AudioEngine.prototype.getGlobalVolume = function () {
  26459. if (this.canUseWebAudio) {
  26460. return this.masterGain.gain.value;
  26461. }
  26462. else {
  26463. return -1;
  26464. }
  26465. };
  26466. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26467. if (this.canUseWebAudio) {
  26468. this.masterGain.gain.value = newVolume;
  26469. }
  26470. };
  26471. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26472. if (this._connectedAnalyser) {
  26473. this._connectedAnalyser.stopDebugCanvas();
  26474. }
  26475. this._connectedAnalyser = analyser;
  26476. if (this.canUseWebAudio) {
  26477. this.masterGain.disconnect();
  26478. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26479. }
  26480. };
  26481. return AudioEngine;
  26482. })();
  26483. BABYLON.AudioEngine = AudioEngine;
  26484. })(BABYLON || (BABYLON = {}));
  26485. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26486. (function (BABYLON) {
  26487. var Sound = (function () {
  26488. /**
  26489. * Create a sound and attach it to a scene
  26490. * @param name Name of your sound
  26491. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26492. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26493. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26494. */
  26495. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26496. var _this = this;
  26497. this.autoplay = false;
  26498. this.loop = false;
  26499. this.useCustomAttenuation = false;
  26500. this.spatialSound = false;
  26501. this.refDistance = 1;
  26502. this.rolloffFactor = 1;
  26503. this.maxDistance = 100;
  26504. this.distanceModel = "linear";
  26505. this._panningModel = "equalpower";
  26506. this._playbackRate = 1;
  26507. this._startTime = 0;
  26508. this._startOffset = 0;
  26509. this._position = BABYLON.Vector3.Zero();
  26510. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26511. this._volume = 1;
  26512. this._isLoaded = false;
  26513. this._isReadyToPlay = false;
  26514. this.isPlaying = false;
  26515. this.isPaused = false;
  26516. this._isDirectional = false;
  26517. // Used if you'd like to create a directional sound.
  26518. // If not set, the sound will be omnidirectional
  26519. this._coneInnerAngle = 360;
  26520. this._coneOuterAngle = 360;
  26521. this._coneOuterGain = 0;
  26522. this.name = name;
  26523. this._scene = scene;
  26524. this._readyToPlayCallback = readyToPlayCallback;
  26525. // Default custom attenuation function is a linear attenuation
  26526. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26527. if (currentDistance < maxDistance) {
  26528. return currentVolume * (1 - currentDistance / maxDistance);
  26529. }
  26530. else {
  26531. return 0;
  26532. }
  26533. };
  26534. if (options) {
  26535. this.autoplay = options.autoplay || false;
  26536. this.loop = options.loop || false;
  26537. // if volume === 0, we need another way to check this option
  26538. if (options.volume !== undefined) {
  26539. this._volume = options.volume;
  26540. }
  26541. this.spatialSound = options.spatialSound || false;
  26542. this.maxDistance = options.maxDistance || 100;
  26543. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26544. this.rolloffFactor = options.rolloffFactor || 1;
  26545. this.refDistance = options.refDistance || 1;
  26546. this.distanceModel = options.distanceModel || "linear";
  26547. this._playbackRate = options.playbackRate || 1;
  26548. }
  26549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26550. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26551. this._soundGain.gain.value = this._volume;
  26552. this._inputAudioNode = this._soundGain;
  26553. this._ouputAudioNode = this._soundGain;
  26554. if (this.spatialSound) {
  26555. this._createSpatialParameters();
  26556. }
  26557. this._scene.mainSoundTrack.AddSound(this);
  26558. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26559. if (urlOrArrayBuffer) {
  26560. // If it's an URL
  26561. if (typeof (urlOrArrayBuffer) === "string") {
  26562. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26563. _this._soundLoaded(data);
  26564. }, null, null, true);
  26565. }
  26566. else {
  26567. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26568. this._soundLoaded(urlOrArrayBuffer);
  26569. }
  26570. else {
  26571. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26572. }
  26573. }
  26574. }
  26575. }
  26576. else {
  26577. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26578. this._scene.mainSoundTrack.AddSound(this);
  26579. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26580. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26581. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26582. }
  26583. }
  26584. }
  26585. Sound.prototype.dispose = function () {
  26586. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26587. if (this.isPlaying) {
  26588. this.stop();
  26589. }
  26590. this._isReadyToPlay = false;
  26591. if (this.soundTrackId === -1) {
  26592. this._scene.mainSoundTrack.RemoveSound(this);
  26593. }
  26594. else {
  26595. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26596. }
  26597. if (this._soundGain) {
  26598. this._soundGain.disconnect();
  26599. this._soundGain = null;
  26600. }
  26601. if (this._soundPanner) {
  26602. this._soundPanner.disconnect();
  26603. this._soundPanner = null;
  26604. }
  26605. if (this._soundSource) {
  26606. this._soundSource.disconnect();
  26607. this._soundSource = null;
  26608. }
  26609. this._audioBuffer = null;
  26610. if (this._connectedMesh) {
  26611. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26612. this._connectedMesh = null;
  26613. }
  26614. }
  26615. };
  26616. Sound.prototype._soundLoaded = function (audioData) {
  26617. var _this = this;
  26618. this._isLoaded = true;
  26619. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26620. _this._audioBuffer = buffer;
  26621. _this._isReadyToPlay = true;
  26622. if (_this.autoplay) {
  26623. _this.play();
  26624. }
  26625. if (_this._readyToPlayCallback) {
  26626. _this._readyToPlayCallback();
  26627. }
  26628. }, function (error) {
  26629. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26630. });
  26631. };
  26632. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26634. this._audioBuffer = audioBuffer;
  26635. this._isReadyToPlay = true;
  26636. }
  26637. };
  26638. Sound.prototype.updateOptions = function (options) {
  26639. if (options) {
  26640. this.loop = options.loop || this.loop;
  26641. this.maxDistance = options.maxDistance || this.maxDistance;
  26642. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26643. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26644. this.refDistance = options.refDistance || this.refDistance;
  26645. this.distanceModel = options.distanceModel || this.distanceModel;
  26646. this._playbackRate = options.playbackRate || this._playbackRate;
  26647. }
  26648. };
  26649. Sound.prototype._createSpatialParameters = function () {
  26650. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26651. if (this._scene.headphone) {
  26652. this._panningModel = "HRTF";
  26653. }
  26654. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26655. if (this.useCustomAttenuation) {
  26656. // Tricks to disable in a way embedded Web Audio attenuation
  26657. this._soundPanner.distanceModel = "linear";
  26658. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26659. this._soundPanner.refDistance = 1;
  26660. this._soundPanner.rolloffFactor = 1;
  26661. this._soundPanner.panningModel = this._panningModel;
  26662. }
  26663. else {
  26664. this._soundPanner.distanceModel = this.distanceModel;
  26665. this._soundPanner.maxDistance = this.maxDistance;
  26666. this._soundPanner.refDistance = this.refDistance;
  26667. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26668. this._soundPanner.panningModel = this._panningModel;
  26669. }
  26670. this._soundPanner.connect(this._ouputAudioNode);
  26671. this._inputAudioNode = this._soundPanner;
  26672. }
  26673. };
  26674. Sound.prototype.switchPanningModelToHRTF = function () {
  26675. this._panningModel = "HRTF";
  26676. this._switchPanningModel();
  26677. };
  26678. Sound.prototype.switchPanningModelToEqualPower = function () {
  26679. this._panningModel = "equalpower";
  26680. this._switchPanningModel();
  26681. };
  26682. Sound.prototype._switchPanningModel = function () {
  26683. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26684. this._soundPanner.panningModel = this._panningModel;
  26685. }
  26686. };
  26687. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26689. this._ouputAudioNode.disconnect();
  26690. this._ouputAudioNode.connect(soundTrackAudioNode);
  26691. }
  26692. };
  26693. /**
  26694. * Transform this sound into a directional source
  26695. * @param coneInnerAngle Size of the inner cone in degree
  26696. * @param coneOuterAngle Size of the outer cone in degree
  26697. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26698. */
  26699. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26700. if (coneOuterAngle < coneInnerAngle) {
  26701. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26702. return;
  26703. }
  26704. this._coneInnerAngle = coneInnerAngle;
  26705. this._coneOuterAngle = coneOuterAngle;
  26706. this._coneOuterGain = coneOuterGain;
  26707. this._isDirectional = true;
  26708. if (this.isPlaying && this.loop) {
  26709. this.stop();
  26710. this.play();
  26711. }
  26712. };
  26713. Sound.prototype.setPosition = function (newPosition) {
  26714. this._position = newPosition;
  26715. if (this.isPlaying && this.spatialSound) {
  26716. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26717. }
  26718. };
  26719. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26720. this._localDirection = newLocalDirection;
  26721. if (this._connectedMesh && this.isPlaying) {
  26722. this._updateDirection();
  26723. }
  26724. };
  26725. Sound.prototype._updateDirection = function () {
  26726. var mat = this._connectedMesh.getWorldMatrix();
  26727. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26728. direction.normalize();
  26729. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26730. };
  26731. Sound.prototype.updateDistanceFromListener = function () {
  26732. if (this._connectedMesh && this.useCustomAttenuation) {
  26733. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26734. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26735. }
  26736. };
  26737. Sound.prototype.setAttenuationFunction = function (callback) {
  26738. this._customAttenuationFunction = callback;
  26739. };
  26740. /**
  26741. * Play the sound
  26742. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26743. */
  26744. Sound.prototype.play = function (time) {
  26745. var _this = this;
  26746. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26747. try {
  26748. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26749. if (!this._soundSource) {
  26750. if (this.spatialSound) {
  26751. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26752. if (this._isDirectional) {
  26753. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26754. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26755. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26756. if (this._connectedMesh) {
  26757. this._updateDirection();
  26758. }
  26759. else {
  26760. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26761. }
  26762. }
  26763. }
  26764. }
  26765. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26766. this._soundSource.buffer = this._audioBuffer;
  26767. this._soundSource.connect(this._inputAudioNode);
  26768. this._soundSource.loop = this.loop;
  26769. this._soundSource.playbackRate.value = this._playbackRate;
  26770. this._startTime = startTime;
  26771. this._soundSource.onended = function () {
  26772. _this._onended();
  26773. };
  26774. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26775. this.isPlaying = true;
  26776. this.isPaused = false;
  26777. }
  26778. catch (ex) {
  26779. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26780. }
  26781. }
  26782. };
  26783. Sound.prototype._onended = function () {
  26784. this.isPlaying = false;
  26785. if (this.onended) {
  26786. this.onended();
  26787. }
  26788. };
  26789. /**
  26790. * Stop the sound
  26791. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26792. */
  26793. Sound.prototype.stop = function (time) {
  26794. if (this.isPlaying) {
  26795. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26796. this._soundSource.stop(stopTime);
  26797. this.isPlaying = false;
  26798. }
  26799. };
  26800. Sound.prototype.pause = function () {
  26801. if (this.isPlaying) {
  26802. this.stop(0);
  26803. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26804. this.isPaused = true;
  26805. }
  26806. };
  26807. Sound.prototype.setVolume = function (newVolume, time) {
  26808. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26809. if (time) {
  26810. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26811. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26812. }
  26813. else {
  26814. this._soundGain.gain.value = newVolume;
  26815. }
  26816. }
  26817. this._volume = newVolume;
  26818. };
  26819. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26820. this._playbackRate = newPlaybackRate;
  26821. if (this.isPlaying) {
  26822. this._soundSource.playbackRate.value = this._playbackRate;
  26823. }
  26824. };
  26825. Sound.prototype.getVolume = function () {
  26826. return this._volume;
  26827. };
  26828. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26829. var _this = this;
  26830. this._connectedMesh = meshToConnectTo;
  26831. if (!this.spatialSound) {
  26832. this._createSpatialParameters();
  26833. this.spatialSound = true;
  26834. if (this.isPlaying && this.loop) {
  26835. this.stop();
  26836. this.play();
  26837. }
  26838. }
  26839. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26840. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26841. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26842. };
  26843. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26844. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26845. if (this._isDirectional && this.isPlaying) {
  26846. this._updateDirection();
  26847. }
  26848. };
  26849. return Sound;
  26850. })();
  26851. BABYLON.Sound = Sound;
  26852. })(BABYLON || (BABYLON = {}));
  26853. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26854. (function (BABYLON) {
  26855. var SoundTrack = (function () {
  26856. function SoundTrack(scene, options) {
  26857. this.id = -1;
  26858. this._isMainTrack = false;
  26859. this._scene = scene;
  26860. this._audioEngine = BABYLON.Engine.audioEngine;
  26861. this.soundCollection = new Array();
  26862. if (this._audioEngine.canUseWebAudio) {
  26863. this._trackGain = this._audioEngine.audioContext.createGain();
  26864. this._trackGain.connect(this._audioEngine.masterGain);
  26865. if (options) {
  26866. if (options.volume) {
  26867. this._trackGain.gain.value = options.volume;
  26868. }
  26869. if (options.mainTrack) {
  26870. this._isMainTrack = options.mainTrack;
  26871. }
  26872. }
  26873. }
  26874. if (!this._isMainTrack) {
  26875. this._scene.soundTracks.push(this);
  26876. this.id = this._scene.soundTracks.length - 1;
  26877. }
  26878. }
  26879. SoundTrack.prototype.dispose = function () {
  26880. if (this._audioEngine.canUseWebAudio) {
  26881. if (this._connectedAnalyser) {
  26882. this._connectedAnalyser.stopDebugCanvas();
  26883. }
  26884. while (this.soundCollection.length) {
  26885. this.soundCollection[0].dispose();
  26886. }
  26887. this._trackGain.disconnect();
  26888. this._trackGain = null;
  26889. }
  26890. };
  26891. SoundTrack.prototype.AddSound = function (sound) {
  26892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26893. sound.connectToSoundTrackAudioNode(this._trackGain);
  26894. }
  26895. if (sound.soundTrackId) {
  26896. if (sound.soundTrackId === -1) {
  26897. this._scene.mainSoundTrack.RemoveSound(sound);
  26898. }
  26899. else {
  26900. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26901. }
  26902. }
  26903. this.soundCollection.push(sound);
  26904. sound.soundTrackId = this.id;
  26905. };
  26906. SoundTrack.prototype.RemoveSound = function (sound) {
  26907. var index = this.soundCollection.indexOf(sound);
  26908. if (index !== -1) {
  26909. this.soundCollection.splice(index, 1);
  26910. }
  26911. };
  26912. SoundTrack.prototype.setVolume = function (newVolume) {
  26913. if (this._audioEngine.canUseWebAudio) {
  26914. this._trackGain.gain.value = newVolume;
  26915. }
  26916. };
  26917. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26919. for (var i = 0; i < this.soundCollection.length; i++) {
  26920. this.soundCollection[i].switchPanningModelToHRTF();
  26921. }
  26922. }
  26923. };
  26924. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26925. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26926. for (var i = 0; i < this.soundCollection.length; i++) {
  26927. this.soundCollection[i].switchPanningModelToEqualPower();
  26928. }
  26929. }
  26930. };
  26931. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26932. if (this._connectedAnalyser) {
  26933. this._connectedAnalyser.stopDebugCanvas();
  26934. }
  26935. this._connectedAnalyser = analyser;
  26936. if (this._audioEngine.canUseWebAudio) {
  26937. this._trackGain.disconnect();
  26938. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26939. }
  26940. };
  26941. return SoundTrack;
  26942. })();
  26943. BABYLON.SoundTrack = SoundTrack;
  26944. })(BABYLON || (BABYLON = {}));
  26945. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26946. (function (BABYLON) {
  26947. var DebugLayer = (function () {
  26948. function DebugLayer(scene) {
  26949. var _this = this;
  26950. this._transformationMatrix = BABYLON.Matrix.Identity();
  26951. this._enabled = false;
  26952. this._labelsEnabled = false;
  26953. this._displayStatistics = true;
  26954. this._displayTree = false;
  26955. this._displayLogs = false;
  26956. this._identityMatrix = BABYLON.Matrix.Identity();
  26957. this.axisRatio = 0.02;
  26958. this.accentColor = "orange";
  26959. this._scene = scene;
  26960. this._syncPositions = function () {
  26961. var engine = _this._scene.getEngine();
  26962. var canvasRect = engine.getRenderingCanvasClientRect();
  26963. if (_this._showUI) {
  26964. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26965. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26966. _this._statsDiv.style.width = "400px";
  26967. _this._statsDiv.style.height = "auto";
  26968. _this._statsSubsetDiv.style.maxHeight = "240px";
  26969. _this._optionsDiv.style.left = "0px";
  26970. _this._optionsDiv.style.top = "10px";
  26971. _this._optionsDiv.style.width = "200px";
  26972. _this._optionsDiv.style.height = "auto";
  26973. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26974. _this._logDiv.style.left = "0px";
  26975. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26976. _this._logDiv.style.width = "600px";
  26977. _this._logDiv.style.height = "160px";
  26978. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26979. _this._treeDiv.style.top = "10px";
  26980. _this._treeDiv.style.width = "300px";
  26981. _this._treeDiv.style.height = "auto";
  26982. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26983. }
  26984. _this._globalDiv.style.left = canvasRect.left + "px";
  26985. _this._globalDiv.style.top = canvasRect.top + "px";
  26986. _this._drawingCanvas.style.left = "0px";
  26987. _this._drawingCanvas.style.top = "0px";
  26988. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26989. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26990. var devicePixelRatio = window.devicePixelRatio || 1;
  26991. var context = _this._drawingContext;
  26992. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26993. _this._ratio = devicePixelRatio / backingStoreRatio;
  26994. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26995. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26996. };
  26997. this._onCanvasClick = function (evt) {
  26998. _this._clickPosition = {
  26999. x: evt.clientX * _this._ratio,
  27000. y: evt.clientY * _this._ratio
  27001. };
  27002. };
  27003. this._syncUI = function () {
  27004. if (_this._showUI) {
  27005. if (_this._displayStatistics) {
  27006. _this._displayStats();
  27007. _this._statsDiv.style.display = "";
  27008. }
  27009. else {
  27010. _this._statsDiv.style.display = "none";
  27011. }
  27012. if (_this._displayLogs) {
  27013. _this._logDiv.style.display = "";
  27014. }
  27015. else {
  27016. _this._logDiv.style.display = "none";
  27017. }
  27018. if (_this._displayTree) {
  27019. _this._treeDiv.style.display = "";
  27020. if (_this._needToRefreshMeshesTree) {
  27021. _this._needToRefreshMeshesTree = false;
  27022. _this._refreshMeshesTreeContent();
  27023. }
  27024. }
  27025. else {
  27026. _this._treeDiv.style.display = "none";
  27027. }
  27028. }
  27029. };
  27030. this._syncData = function () {
  27031. if (_this._labelsEnabled || !_this._showUI) {
  27032. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27033. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27034. var engine = _this._scene.getEngine();
  27035. var viewport = _this._camera.viewport;
  27036. var globalViewport = viewport.toGlobal(engine);
  27037. // Meshes
  27038. var meshes = _this._camera.getActiveMeshes();
  27039. for (var index = 0; index < meshes.length; index++) {
  27040. var mesh = meshes.data[index];
  27041. var position = mesh.getBoundingInfo().boundingSphere.center;
  27042. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27043. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27044. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27045. }
  27046. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27047. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27048. mesh.renderOverlay = !mesh.renderOverlay;
  27049. }, function () {
  27050. return mesh.renderOverlay ? 'red' : 'black';
  27051. });
  27052. }
  27053. }
  27054. // Cameras
  27055. var cameras = _this._scene.cameras;
  27056. for (index = 0; index < cameras.length; index++) {
  27057. var camera = cameras[index];
  27058. if (camera === _this._camera) {
  27059. continue;
  27060. }
  27061. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27062. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27063. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27064. _this._camera.detachControl(engine.getRenderingCanvas());
  27065. _this._camera = camera;
  27066. _this._camera.attachControl(engine.getRenderingCanvas());
  27067. }, function () {
  27068. return "purple";
  27069. });
  27070. }
  27071. }
  27072. // Lights
  27073. var lights = _this._scene.lights;
  27074. for (index = 0; index < lights.length; index++) {
  27075. var light = lights[index];
  27076. if (light.position) {
  27077. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27078. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27079. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27080. light.setEnabled(!light.isEnabled());
  27081. }, function () {
  27082. return light.isEnabled() ? "orange" : "gray";
  27083. });
  27084. }
  27085. }
  27086. }
  27087. }
  27088. _this._clickPosition = undefined;
  27089. };
  27090. }
  27091. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27092. while (this._treeSubsetDiv.hasChildNodes()) {
  27093. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27094. }
  27095. // Add meshes
  27096. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27097. sortedArray.sort(function (a, b) {
  27098. if (a.name === b.name) {
  27099. return 0;
  27100. }
  27101. return (a.name > b.name) ? 1 : -1;
  27102. });
  27103. for (var index = 0; index < sortedArray.length; index++) {
  27104. var mesh = sortedArray[index];
  27105. if (!mesh.isEnabled()) {
  27106. continue;
  27107. }
  27108. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27109. m.isVisible = element.checked;
  27110. }, mesh);
  27111. }
  27112. };
  27113. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27114. this._drawingContext.beginPath();
  27115. this._drawingContext.moveTo(zero.x, zero.y);
  27116. this._drawingContext.lineTo(unit.x, unit.y);
  27117. this._drawingContext.strokeStyle = color;
  27118. this._drawingContext.lineWidth = 4;
  27119. this._drawingContext.stroke();
  27120. this._drawingContext.font = "normal 14px Segoe UI";
  27121. this._drawingContext.fillStyle = color;
  27122. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27123. };
  27124. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27125. var position = mesh.getBoundingInfo().boundingSphere.center;
  27126. var worldMatrix = mesh.getWorldMatrix();
  27127. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27128. var unit = (unprojectedVector.subtract(position)).length();
  27129. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27130. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27131. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27132. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27133. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27134. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27135. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27136. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27137. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27138. };
  27139. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27140. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27141. this._drawingContext.font = "normal 12px Segoe UI";
  27142. var textMetrics = this._drawingContext.measureText(text);
  27143. var centerX = projectedPosition.x - textMetrics.width / 2;
  27144. var centerY = projectedPosition.y;
  27145. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27146. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27147. onClick();
  27148. }
  27149. this._drawingContext.beginPath();
  27150. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27151. this._drawingContext.fillStyle = getFillStyle();
  27152. this._drawingContext.globalAlpha = 0.5;
  27153. this._drawingContext.fill();
  27154. this._drawingContext.globalAlpha = 1.0;
  27155. this._drawingContext.strokeStyle = '#FFFFFF';
  27156. this._drawingContext.lineWidth = 1;
  27157. this._drawingContext.stroke();
  27158. this._drawingContext.fillStyle = "#FFFFFF";
  27159. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27160. this._drawingContext.beginPath();
  27161. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27162. this._drawingContext.fill();
  27163. }
  27164. };
  27165. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27166. if (!this._clickPosition) {
  27167. return false;
  27168. }
  27169. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27170. return false;
  27171. }
  27172. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27173. return false;
  27174. }
  27175. return true;
  27176. };
  27177. DebugLayer.prototype.isVisible = function () {
  27178. return this._enabled;
  27179. };
  27180. DebugLayer.prototype.hide = function () {
  27181. if (!this._enabled) {
  27182. return;
  27183. }
  27184. this._enabled = false;
  27185. var engine = this._scene.getEngine();
  27186. this._scene.unregisterBeforeRender(this._syncData);
  27187. this._scene.unregisterAfterRender(this._syncUI);
  27188. document.body.removeChild(this._globalDiv);
  27189. window.removeEventListener("resize", this._syncPositions);
  27190. this._scene.forceShowBoundingBoxes = false;
  27191. this._scene.forceWireframe = false;
  27192. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27193. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27194. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27195. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27196. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27197. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27198. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27199. this._scene.shadowsEnabled = true;
  27200. this._scene.particlesEnabled = true;
  27201. this._scene.postProcessesEnabled = true;
  27202. this._scene.collisionsEnabled = true;
  27203. this._scene.lightsEnabled = true;
  27204. this._scene.texturesEnabled = true;
  27205. this._scene.lensFlaresEnabled = true;
  27206. this._scene.proceduralTexturesEnabled = true;
  27207. this._scene.renderTargetsEnabled = true;
  27208. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27209. };
  27210. DebugLayer.prototype.show = function (showUI, camera) {
  27211. if (showUI === void 0) { showUI = true; }
  27212. if (camera === void 0) { camera = null; }
  27213. if (this._enabled) {
  27214. return;
  27215. }
  27216. if (camera) {
  27217. this._camera = camera;
  27218. }
  27219. else {
  27220. this._camera = this._scene.activeCamera;
  27221. }
  27222. this._enabled = true;
  27223. this._showUI = showUI;
  27224. var engine = this._scene.getEngine();
  27225. this._globalDiv = document.createElement("div");
  27226. document.body.appendChild(this._globalDiv);
  27227. this._generateDOMelements();
  27228. window.addEventListener("resize", this._syncPositions);
  27229. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27230. this._syncPositions();
  27231. this._scene.registerBeforeRender(this._syncData);
  27232. this._scene.registerAfterRender(this._syncUI);
  27233. };
  27234. DebugLayer.prototype._clearLabels = function () {
  27235. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27236. for (var index = 0; index < this._scene.meshes.length; index++) {
  27237. var mesh = this._scene.meshes[index];
  27238. mesh.renderOverlay = false;
  27239. }
  27240. };
  27241. DebugLayer.prototype._generateheader = function (root, text) {
  27242. var header = document.createElement("div");
  27243. header.innerHTML = text + "&nbsp;";
  27244. header.style.textAlign = "right";
  27245. header.style.width = "100%";
  27246. header.style.color = "white";
  27247. header.style.backgroundColor = "Black";
  27248. header.style.padding = "5px 5px 4px 0px";
  27249. header.style.marginLeft = "-5px";
  27250. header.style.fontWeight = "bold";
  27251. root.appendChild(header);
  27252. };
  27253. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27254. var label = document.createElement("label");
  27255. label.innerHTML = title;
  27256. label.style.color = color;
  27257. root.appendChild(label);
  27258. root.appendChild(document.createElement("br"));
  27259. };
  27260. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27261. if (tag === void 0) { tag = null; }
  27262. var label = document.createElement("label");
  27263. var boundingBoxesCheckbox = document.createElement("input");
  27264. boundingBoxesCheckbox.type = "checkbox";
  27265. boundingBoxesCheckbox.checked = initialState;
  27266. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27267. task(evt.target, tag);
  27268. });
  27269. label.appendChild(boundingBoxesCheckbox);
  27270. var container = document.createElement("span");
  27271. var leftPart = document.createElement("span");
  27272. var rightPart = document.createElement("span");
  27273. rightPart.style.cssFloat = "right";
  27274. leftPart.innerHTML = leftTitle;
  27275. rightPart.innerHTML = rightTitle;
  27276. rightPart.style.fontSize = "12px";
  27277. rightPart.style.maxWidth = "200px";
  27278. container.appendChild(leftPart);
  27279. container.appendChild(rightPart);
  27280. label.appendChild(container);
  27281. root.appendChild(label);
  27282. root.appendChild(document.createElement("br"));
  27283. };
  27284. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27285. if (tag === void 0) { tag = null; }
  27286. var label = document.createElement("label");
  27287. var checkBox = document.createElement("input");
  27288. checkBox.type = "checkbox";
  27289. checkBox.checked = initialState;
  27290. checkBox.addEventListener("change", function (evt) {
  27291. task(evt.target, tag);
  27292. });
  27293. label.appendChild(checkBox);
  27294. label.appendChild(document.createTextNode(title));
  27295. root.appendChild(label);
  27296. root.appendChild(document.createElement("br"));
  27297. };
  27298. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27299. if (tag === void 0) { tag = null; }
  27300. var button = document.createElement("button");
  27301. button.innerHTML = title;
  27302. button.style.height = "24px";
  27303. button.style.color = "#444444";
  27304. button.style.border = "1px solid white";
  27305. button.className = "debugLayerButton";
  27306. button.addEventListener("click", function (evt) {
  27307. task(evt.target, tag);
  27308. });
  27309. root.appendChild(button);
  27310. root.appendChild(document.createElement("br"));
  27311. };
  27312. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27313. if (tag === void 0) { tag = null; }
  27314. var label = document.createElement("label");
  27315. var boundingBoxesRadio = document.createElement("input");
  27316. boundingBoxesRadio.type = "radio";
  27317. boundingBoxesRadio.name = name;
  27318. boundingBoxesRadio.checked = initialState;
  27319. boundingBoxesRadio.addEventListener("change", function (evt) {
  27320. task(evt.target, tag);
  27321. });
  27322. label.appendChild(boundingBoxesRadio);
  27323. label.appendChild(document.createTextNode(title));
  27324. root.appendChild(label);
  27325. root.appendChild(document.createElement("br"));
  27326. };
  27327. DebugLayer.prototype._generateDOMelements = function () {
  27328. var _this = this;
  27329. this._globalDiv.id = "DebugLayer";
  27330. this._globalDiv.style.position = "absolute";
  27331. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27332. this._globalDiv.style.fontSize = "14px";
  27333. this._globalDiv.style.color = "white";
  27334. // Drawing canvas
  27335. this._drawingCanvas = document.createElement("canvas");
  27336. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27337. this._drawingCanvas.style.position = "absolute";
  27338. this._drawingCanvas.style.pointerEvents = "none";
  27339. this._drawingContext = this._drawingCanvas.getContext("2d");
  27340. this._globalDiv.appendChild(this._drawingCanvas);
  27341. if (this._showUI) {
  27342. var background = "rgba(128, 128, 128, 0.4)";
  27343. var border = "rgb(180, 180, 180) solid 1px";
  27344. // Stats
  27345. this._statsDiv = document.createElement("div");
  27346. this._statsDiv.id = "DebugLayerStats";
  27347. this._statsDiv.style.border = border;
  27348. this._statsDiv.style.position = "absolute";
  27349. this._statsDiv.style.background = background;
  27350. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27351. this._generateheader(this._statsDiv, "STATISTICS");
  27352. this._statsSubsetDiv = document.createElement("div");
  27353. this._statsSubsetDiv.style.paddingTop = "5px";
  27354. this._statsSubsetDiv.style.paddingBottom = "5px";
  27355. this._statsSubsetDiv.style.overflowY = "auto";
  27356. this._statsDiv.appendChild(this._statsSubsetDiv);
  27357. // Tree
  27358. this._treeDiv = document.createElement("div");
  27359. this._treeDiv.id = "DebugLayerTree";
  27360. this._treeDiv.style.border = border;
  27361. this._treeDiv.style.position = "absolute";
  27362. this._treeDiv.style.background = background;
  27363. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27364. this._treeDiv.style.display = "none";
  27365. this._generateheader(this._treeDiv, "MESHES TREE");
  27366. this._treeSubsetDiv = document.createElement("div");
  27367. this._treeSubsetDiv.style.paddingTop = "5px";
  27368. this._treeSubsetDiv.style.paddingRight = "5px";
  27369. this._treeSubsetDiv.style.overflowY = "auto";
  27370. this._treeSubsetDiv.style.maxHeight = "300px";
  27371. this._treeDiv.appendChild(this._treeSubsetDiv);
  27372. this._needToRefreshMeshesTree = true;
  27373. // Logs
  27374. this._logDiv = document.createElement("div");
  27375. this._logDiv.style.border = border;
  27376. this._logDiv.id = "DebugLayerLogs";
  27377. this._logDiv.style.position = "absolute";
  27378. this._logDiv.style.background = background;
  27379. this._logDiv.style.padding = "0px 0px 0px 5px";
  27380. this._logDiv.style.display = "none";
  27381. this._generateheader(this._logDiv, "LOGS");
  27382. this._logSubsetDiv = document.createElement("div");
  27383. this._logSubsetDiv.style.height = "127px";
  27384. this._logSubsetDiv.style.paddingTop = "5px";
  27385. this._logSubsetDiv.style.overflowY = "auto";
  27386. this._logSubsetDiv.style.fontSize = "12px";
  27387. this._logSubsetDiv.style.fontFamily = "consolas";
  27388. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27389. this._logDiv.appendChild(this._logSubsetDiv);
  27390. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27391. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27392. };
  27393. // Options
  27394. this._optionsDiv = document.createElement("div");
  27395. this._optionsDiv.id = "DebugLayerOptions";
  27396. this._optionsDiv.style.border = border;
  27397. this._optionsDiv.style.position = "absolute";
  27398. this._optionsDiv.style.background = background;
  27399. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27400. this._optionsDiv.style.overflowY = "auto";
  27401. this._generateheader(this._optionsDiv, "OPTIONS");
  27402. this._optionsSubsetDiv = document.createElement("div");
  27403. this._optionsSubsetDiv.style.paddingTop = "5px";
  27404. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27405. this._optionsSubsetDiv.style.overflowY = "auto";
  27406. this._optionsSubsetDiv.style.maxHeight = "200px";
  27407. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27408. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27409. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27410. _this._displayStatistics = element.checked;
  27411. });
  27412. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27413. _this._displayLogs = element.checked;
  27414. });
  27415. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27416. _this._displayTree = element.checked;
  27417. _this._needToRefreshMeshesTree = true;
  27418. });
  27419. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27420. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27421. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27422. _this._scene.forceShowBoundingBoxes = element.checked;
  27423. });
  27424. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27425. _this._labelsEnabled = element.checked;
  27426. if (!_this._labelsEnabled) {
  27427. _this._clearLabels();
  27428. }
  27429. });
  27430. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27431. if (element.checked) {
  27432. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27433. }
  27434. else {
  27435. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27436. }
  27437. });
  27438. ;
  27439. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27440. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27441. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27442. if (element.checked) {
  27443. _this._scene.forceWireframe = false;
  27444. _this._scene.forcePointsCloud = false;
  27445. }
  27446. });
  27447. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27448. if (element.checked) {
  27449. _this._scene.forceWireframe = true;
  27450. _this._scene.forcePointsCloud = false;
  27451. }
  27452. });
  27453. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27454. if (element.checked) {
  27455. _this._scene.forceWireframe = false;
  27456. _this._scene.forcePointsCloud = true;
  27457. }
  27458. });
  27459. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27460. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27461. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27462. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27463. });
  27464. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27465. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27466. });
  27467. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27468. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27469. });
  27470. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27471. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27472. });
  27473. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27474. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27475. });
  27476. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27477. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27478. });
  27479. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27480. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27481. });
  27482. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27483. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27484. });
  27485. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27486. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27487. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27488. _this._scene.animationsEnabled = element.checked;
  27489. });
  27490. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27491. _this._scene.collisionsEnabled = element.checked;
  27492. });
  27493. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27494. _this._scene.fogEnabled = element.checked;
  27495. });
  27496. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27497. _this._scene.lensFlaresEnabled = element.checked;
  27498. });
  27499. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27500. _this._scene.lightsEnabled = element.checked;
  27501. });
  27502. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27503. _this._scene.particlesEnabled = element.checked;
  27504. });
  27505. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27506. _this._scene.postProcessesEnabled = element.checked;
  27507. });
  27508. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27509. _this._scene.proceduralTexturesEnabled = element.checked;
  27510. });
  27511. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27512. _this._scene.renderTargetsEnabled = element.checked;
  27513. });
  27514. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27515. _this._scene.shadowsEnabled = element.checked;
  27516. });
  27517. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27518. _this._scene.skeletonsEnabled = element.checked;
  27519. });
  27520. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27521. _this._scene.spritesEnabled = element.checked;
  27522. });
  27523. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27524. _this._scene.texturesEnabled = element.checked;
  27525. });
  27526. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27527. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27528. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27529. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27530. if (element.checked) {
  27531. _this._scene.headphone = true;
  27532. }
  27533. });
  27534. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27535. if (element.checked) {
  27536. _this._scene.headphone = false;
  27537. }
  27538. });
  27539. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27540. _this._scene.audioEnabled = !element.checked;
  27541. });
  27542. }
  27543. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27544. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27545. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27546. _this._scene.dumpNextRenderTargets = true;
  27547. });
  27548. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27549. this._globalDiv.appendChild(this._statsDiv);
  27550. this._globalDiv.appendChild(this._logDiv);
  27551. this._globalDiv.appendChild(this._optionsDiv);
  27552. this._globalDiv.appendChild(this._treeDiv);
  27553. }
  27554. };
  27555. DebugLayer.prototype._displayStats = function () {
  27556. var scene = this._scene;
  27557. var engine = scene.getEngine();
  27558. var glInfo = engine.getGlInfo();
  27559. 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>";
  27560. if (this.customStatsFunction) {
  27561. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27562. }
  27563. };
  27564. return DebugLayer;
  27565. })();
  27566. BABYLON.DebugLayer = DebugLayer;
  27567. })(BABYLON || (BABYLON = {}));
  27568. //# sourceMappingURL=babylon.debugLayer.js.map
  27569. var BABYLON;
  27570. (function (BABYLON) {
  27571. var RawTexture = (function (_super) {
  27572. __extends(RawTexture, _super);
  27573. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27575. if (invertY === void 0) { invertY = false; }
  27576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27577. _super.call(this, null, scene, !generateMipMaps, invertY);
  27578. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27579. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27580. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27581. }
  27582. // Statics
  27583. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27585. if (invertY === void 0) { invertY = false; }
  27586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27588. };
  27589. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27591. if (invertY === void 0) { invertY = false; }
  27592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27594. };
  27595. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27597. if (invertY === void 0) { invertY = false; }
  27598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27600. };
  27601. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27603. if (invertY === void 0) { invertY = false; }
  27604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27605. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27606. };
  27607. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27608. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27609. if (invertY === void 0) { invertY = false; }
  27610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27611. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27612. };
  27613. return RawTexture;
  27614. })(BABYLON.Texture);
  27615. BABYLON.RawTexture = RawTexture;
  27616. })(BABYLON || (BABYLON = {}));
  27617. //# sourceMappingURL=babylon.rawTexture.js.map
  27618. var BABYLON;
  27619. (function (BABYLON) {
  27620. var IndexedVector2 = (function (_super) {
  27621. __extends(IndexedVector2, _super);
  27622. function IndexedVector2(original, index) {
  27623. _super.call(this, original.x, original.y);
  27624. this.index = index;
  27625. }
  27626. return IndexedVector2;
  27627. })(BABYLON.Vector2);
  27628. var PolygonPoints = (function () {
  27629. function PolygonPoints() {
  27630. this.elements = new Array();
  27631. }
  27632. PolygonPoints.prototype.add = function (originalPoints) {
  27633. var _this = this;
  27634. var result = new Array();
  27635. originalPoints.forEach(function (point) {
  27636. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27637. var newPoint = new IndexedVector2(point, _this.elements.length);
  27638. result.push(newPoint);
  27639. _this.elements.push(newPoint);
  27640. }
  27641. });
  27642. return result;
  27643. };
  27644. PolygonPoints.prototype.computeBounds = function () {
  27645. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27646. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27647. this.elements.forEach(function (point) {
  27648. // x
  27649. if (point.x < lmin.x) {
  27650. lmin.x = point.x;
  27651. }
  27652. else if (point.x > lmax.x) {
  27653. lmax.x = point.x;
  27654. }
  27655. // y
  27656. if (point.y < lmin.y) {
  27657. lmin.y = point.y;
  27658. }
  27659. else if (point.y > lmax.y) {
  27660. lmax.y = point.y;
  27661. }
  27662. });
  27663. return {
  27664. min: lmin,
  27665. max: lmax,
  27666. width: lmax.x - lmin.x,
  27667. height: lmax.y - lmin.y
  27668. };
  27669. };
  27670. return PolygonPoints;
  27671. })();
  27672. var Polygon = (function () {
  27673. function Polygon() {
  27674. }
  27675. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27676. return [
  27677. new BABYLON.Vector2(xmin, ymin),
  27678. new BABYLON.Vector2(xmax, ymin),
  27679. new BABYLON.Vector2(xmax, ymax),
  27680. new BABYLON.Vector2(xmin, ymax)
  27681. ];
  27682. };
  27683. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27684. if (cx === void 0) { cx = 0; }
  27685. if (cy === void 0) { cy = 0; }
  27686. if (numberOfSides === void 0) { numberOfSides = 32; }
  27687. var result = new Array();
  27688. var angle = 0;
  27689. var increment = (Math.PI * 2) / numberOfSides;
  27690. for (var i = 0; i < numberOfSides; i++) {
  27691. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27692. angle -= increment;
  27693. }
  27694. return result;
  27695. };
  27696. Polygon.Parse = function (input) {
  27697. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27698. var i, result = [];
  27699. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27700. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27701. }
  27702. return result;
  27703. };
  27704. Polygon.StartingAt = function (x, y) {
  27705. return BABYLON.Path2.StartingAt(x, y);
  27706. };
  27707. return Polygon;
  27708. })();
  27709. BABYLON.Polygon = Polygon;
  27710. var PolygonMeshBuilder = (function () {
  27711. function PolygonMeshBuilder(name, contours, scene) {
  27712. this._points = new PolygonPoints();
  27713. if (!("poly2tri" in window)) {
  27714. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27715. }
  27716. this._name = name;
  27717. this._scene = scene;
  27718. var points;
  27719. if (contours instanceof BABYLON.Path2) {
  27720. points = contours.getPoints();
  27721. }
  27722. else {
  27723. points = contours;
  27724. }
  27725. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27726. }
  27727. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27728. this._swctx.addHole(this._points.add(hole));
  27729. return this;
  27730. };
  27731. PolygonMeshBuilder.prototype.build = function (updatable) {
  27732. if (updatable === void 0) { updatable = false; }
  27733. var result = new BABYLON.Mesh(this._name, this._scene);
  27734. var normals = [];
  27735. var positions = [];
  27736. var uvs = [];
  27737. var bounds = this._points.computeBounds();
  27738. this._points.elements.forEach(function (p) {
  27739. normals.push(0, 1.0, 0);
  27740. positions.push(p.x, 0, p.y);
  27741. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27742. });
  27743. var indices = [];
  27744. this._swctx.triangulate();
  27745. this._swctx.getTriangles().forEach(function (triangle) {
  27746. triangle.getPoints().forEach(function (point) {
  27747. indices.push(point.index);
  27748. });
  27749. });
  27750. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27751. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27752. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27753. result.setIndices(indices);
  27754. return result;
  27755. };
  27756. return PolygonMeshBuilder;
  27757. })();
  27758. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27759. })(BABYLON || (BABYLON = {}));
  27760. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27761. (function (BABYLON) {
  27762. var SimplificationSettings = (function () {
  27763. function SimplificationSettings(quality, distance) {
  27764. this.quality = quality;
  27765. this.distance = distance;
  27766. }
  27767. return SimplificationSettings;
  27768. })();
  27769. BABYLON.SimplificationSettings = SimplificationSettings;
  27770. var SimplificationQueue = (function () {
  27771. function SimplificationQueue() {
  27772. this.running = false;
  27773. this._simplificationArray = [];
  27774. }
  27775. SimplificationQueue.prototype.addTask = function (task) {
  27776. this._simplificationArray.push(task);
  27777. };
  27778. SimplificationQueue.prototype.executeNext = function () {
  27779. var task = this._simplificationArray.pop();
  27780. if (task) {
  27781. this.running = true;
  27782. this.runSimplification(task);
  27783. }
  27784. else {
  27785. this.running = false;
  27786. }
  27787. };
  27788. SimplificationQueue.prototype.runSimplification = function (task) {
  27789. var _this = this;
  27790. function setLODLevel(distance, mesh) {
  27791. }
  27792. if (task.parallelProcessing) {
  27793. //parallel simplifier
  27794. task.settings.forEach(function (setting) {
  27795. var simplifier = _this.getSimplifier(task);
  27796. simplifier.simplify(setting, function (newMesh) {
  27797. task.mesh.addLODLevel(setting.distance, newMesh);
  27798. //check if it is the last
  27799. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27800. //all done, run the success callback.
  27801. task.successCallback();
  27802. }
  27803. _this.executeNext();
  27804. });
  27805. });
  27806. }
  27807. else {
  27808. //single simplifier.
  27809. var simplifier = this.getSimplifier(task);
  27810. var runDecimation = function (setting, callback) {
  27811. simplifier.simplify(setting, function (newMesh) {
  27812. task.mesh.addLODLevel(setting.distance, newMesh);
  27813. //run the next quality level
  27814. callback();
  27815. });
  27816. };
  27817. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27818. runDecimation(task.settings[loop.index], function () {
  27819. loop.executeNext();
  27820. });
  27821. }, function () {
  27822. //execution ended, run the success callback.
  27823. if (task.successCallback) {
  27824. task.successCallback();
  27825. }
  27826. _this.executeNext();
  27827. });
  27828. }
  27829. };
  27830. SimplificationQueue.prototype.getSimplifier = function (task) {
  27831. switch (task.simplificationType) {
  27832. case 0 /* QUADRATIC */:
  27833. default:
  27834. return new QuadraticErrorSimplification(task.mesh);
  27835. }
  27836. };
  27837. return SimplificationQueue;
  27838. })();
  27839. BABYLON.SimplificationQueue = SimplificationQueue;
  27840. /**
  27841. * The implemented types of simplification.
  27842. * At the moment only Quadratic Error Decimation is implemented.
  27843. */
  27844. (function (SimplificationType) {
  27845. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27846. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27847. var SimplificationType = BABYLON.SimplificationType;
  27848. var DecimationTriangle = (function () {
  27849. function DecimationTriangle(vertices) {
  27850. this.vertices = vertices;
  27851. this.error = new Array(4);
  27852. this.deleted = false;
  27853. this.isDirty = false;
  27854. this.borderFactor = 0;
  27855. }
  27856. return DecimationTriangle;
  27857. })();
  27858. BABYLON.DecimationTriangle = DecimationTriangle;
  27859. var DecimationVertex = (function () {
  27860. function DecimationVertex(position, normal, uv, id) {
  27861. this.position = position;
  27862. this.normal = normal;
  27863. this.uv = uv;
  27864. this.id = id;
  27865. this.isBorder = true;
  27866. this.q = new QuadraticMatrix();
  27867. this.triangleCount = 0;
  27868. this.triangleStart = 0;
  27869. }
  27870. return DecimationVertex;
  27871. })();
  27872. BABYLON.DecimationVertex = DecimationVertex;
  27873. var QuadraticMatrix = (function () {
  27874. function QuadraticMatrix(data) {
  27875. this.data = new Array(10);
  27876. for (var i = 0; i < 10; ++i) {
  27877. if (data && data[i]) {
  27878. this.data[i] = data[i];
  27879. }
  27880. else {
  27881. this.data[i] = 0;
  27882. }
  27883. }
  27884. }
  27885. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27886. 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];
  27887. return det;
  27888. };
  27889. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27890. for (var i = 0; i < 10; ++i) {
  27891. this.data[i] += matrix.data[i];
  27892. }
  27893. };
  27894. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27895. for (var i = 0; i < 10; ++i) {
  27896. this.data[i] += data[i];
  27897. }
  27898. };
  27899. QuadraticMatrix.prototype.add = function (matrix) {
  27900. var m = new QuadraticMatrix();
  27901. for (var i = 0; i < 10; ++i) {
  27902. m.data[i] = this.data[i] + matrix.data[i];
  27903. }
  27904. return m;
  27905. };
  27906. QuadraticMatrix.FromData = function (a, b, c, d) {
  27907. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27908. };
  27909. //returning an array to avoid garbage collection
  27910. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27911. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27912. };
  27913. return QuadraticMatrix;
  27914. })();
  27915. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27916. var Reference = (function () {
  27917. function Reference(vertexId, triangleId) {
  27918. this.vertexId = vertexId;
  27919. this.triangleId = triangleId;
  27920. }
  27921. return Reference;
  27922. })();
  27923. BABYLON.Reference = Reference;
  27924. /**
  27925. * An implementation of the Quadratic Error simplification algorithm.
  27926. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27927. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27928. * @author RaananW
  27929. */
  27930. var QuadraticErrorSimplification = (function () {
  27931. function QuadraticErrorSimplification(_mesh) {
  27932. this._mesh = _mesh;
  27933. this.initialised = false;
  27934. this.syncIterations = 5000;
  27935. this.aggressiveness = 7;
  27936. this.decimationIterations = 100;
  27937. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  27938. }
  27939. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27940. var _this = this;
  27941. this.initDecimatedMesh();
  27942. //iterating through the submeshes array, one after the other.
  27943. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  27944. _this.initWithMesh(_this._mesh, loop.index, function () {
  27945. _this.runDecimation(settings, loop.index, function () {
  27946. loop.executeNext();
  27947. });
  27948. });
  27949. }, function () {
  27950. setTimeout(function () {
  27951. _this._reconstructedMesh.isVisible = true;
  27952. successCallback(_this._reconstructedMesh);
  27953. }, 0);
  27954. });
  27955. };
  27956. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  27957. var _this = this;
  27958. var gCount = 0;
  27959. triangle.vertices.forEach(function (vId) {
  27960. var count = 0;
  27961. var vPos = _this.vertices[vId].position;
  27962. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  27963. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  27964. ++count;
  27965. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  27966. ++count;
  27967. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  27968. ++count;
  27969. if (count > 1) {
  27970. ++gCount;
  27971. }
  27972. ;
  27973. });
  27974. if (gCount > 1) {
  27975. console.log(triangle, gCount);
  27976. }
  27977. return gCount > 1;
  27978. };
  27979. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  27980. var _this = this;
  27981. var targetCount = ~~(this.triangles.length * settings.quality);
  27982. var deletedTriangles = 0;
  27983. var triangleCount = this.triangles.length;
  27984. var iterationFunction = function (iteration, callback) {
  27985. setTimeout(function () {
  27986. if (iteration % 5 === 0) {
  27987. _this.updateMesh(iteration === 0);
  27988. }
  27989. for (var i = 0; i < _this.triangles.length; ++i) {
  27990. _this.triangles[i].isDirty = false;
  27991. }
  27992. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27993. var trianglesIterator = function (i) {
  27994. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27995. var t = _this.triangles[tIdx];
  27996. if (!t)
  27997. return;
  27998. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27999. return;
  28000. }
  28001. for (var j = 0; j < 3; ++j) {
  28002. if (t.error[j] < threshold) {
  28003. var deleted0 = [];
  28004. var deleted1 = [];
  28005. var i0 = t.vertices[j];
  28006. var i1 = t.vertices[(j + 1) % 3];
  28007. var v0 = _this.vertices[i0];
  28008. var v1 = _this.vertices[i1];
  28009. if (v0.isBorder !== v1.isBorder)
  28010. continue;
  28011. var p = BABYLON.Vector3.Zero();
  28012. var n = BABYLON.Vector3.Zero();
  28013. var uv = BABYLON.Vector2.Zero();
  28014. var color = new BABYLON.Color4(0, 0, 0, 1);
  28015. _this.calculateError(v0, v1, p, n, uv, color);
  28016. var delTr = [];
  28017. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28018. continue;
  28019. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28020. continue;
  28021. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  28022. continue;
  28023. }
  28024. v0.normal = n;
  28025. if (v0.uv)
  28026. v0.uv = uv;
  28027. else if (v0.color)
  28028. v0.color = color;
  28029. v0.q = v1.q.add(v0.q);
  28030. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28031. continue;
  28032. if (p.equals(v0.position))
  28033. continue;
  28034. v0.position = p;
  28035. var tStart = _this.references.length;
  28036. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28037. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28038. var tCount = _this.references.length - tStart;
  28039. if (tCount <= v0.triangleCount) {
  28040. if (tCount) {
  28041. for (var c = 0; c < tCount; c++) {
  28042. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28043. }
  28044. }
  28045. }
  28046. else {
  28047. v0.triangleStart = tStart;
  28048. }
  28049. v0.triangleCount = tCount;
  28050. break;
  28051. }
  28052. }
  28053. };
  28054. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28055. return (triangleCount - deletedTriangles <= targetCount);
  28056. });
  28057. }, 0);
  28058. };
  28059. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28060. if (triangleCount - deletedTriangles <= targetCount)
  28061. loop.breakLoop();
  28062. else {
  28063. iterationFunction(loop.index, function () {
  28064. loop.executeNext();
  28065. });
  28066. }
  28067. }, function () {
  28068. setTimeout(function () {
  28069. //reconstruct this part of the mesh
  28070. _this.reconstructMesh(submeshIndex);
  28071. successCallback();
  28072. }, 0);
  28073. });
  28074. };
  28075. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28076. var _this = this;
  28077. if (!mesh)
  28078. return;
  28079. this.vertices = [];
  28080. this.triangles = [];
  28081. this._mesh = mesh;
  28082. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28083. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28084. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28085. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28086. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28087. var indices = mesh.getIndices();
  28088. var submesh = mesh.subMeshes[submeshIndex];
  28089. var vertexInit = function (i) {
  28090. var offset = i + submesh.verticesStart;
  28091. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28092. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28093. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28094. }
  28095. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28096. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28097. }
  28098. _this.vertices.push(vertex);
  28099. };
  28100. //var totalVertices = mesh.getTotalVertices();
  28101. var totalVertices = submesh.verticesCount;
  28102. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28103. var indicesInit = function (i) {
  28104. var offset = (submesh.indexStart / 3) + i;
  28105. var pos = (offset * 3);
  28106. var i0 = indices[pos + 0] - submesh.verticesStart;
  28107. var i1 = indices[pos + 1] - submesh.verticesStart;
  28108. var i2 = indices[pos + 2] - submesh.verticesStart;
  28109. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28110. _this.triangles.push(triangle);
  28111. };
  28112. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28113. _this.init(callback);
  28114. });
  28115. });
  28116. };
  28117. QuadraticErrorSimplification.prototype.init = function (callback) {
  28118. var _this = this;
  28119. var triangleInit1 = function (i) {
  28120. var t = _this.triangles[i];
  28121. 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();
  28122. for (var j = 0; j < 3; j++) {
  28123. _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))));
  28124. }
  28125. };
  28126. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28127. var triangleInit2 = function (i) {
  28128. var t = _this.triangles[i];
  28129. for (var j = 0; j < 3; ++j) {
  28130. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28131. }
  28132. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28133. };
  28134. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28135. _this.initialised = true;
  28136. callback();
  28137. });
  28138. });
  28139. };
  28140. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28141. var newTriangles = [];
  28142. var i;
  28143. for (i = 0; i < this.vertices.length; ++i) {
  28144. this.vertices[i].triangleCount = 0;
  28145. }
  28146. var t;
  28147. var j;
  28148. for (i = 0; i < this.triangles.length; ++i) {
  28149. if (!this.triangles[i].deleted) {
  28150. t = this.triangles[i];
  28151. for (j = 0; j < 3; ++j) {
  28152. this.vertices[t.vertices[j]].triangleCount = 1;
  28153. }
  28154. newTriangles.push(t);
  28155. }
  28156. }
  28157. var newVerticesOrder = [];
  28158. //compact vertices, get the IDs of the vertices used.
  28159. var dst = 0;
  28160. for (i = 0; i < this.vertices.length; ++i) {
  28161. if (this.vertices[i].triangleCount) {
  28162. this.vertices[i].triangleStart = dst;
  28163. this.vertices[dst].position = this.vertices[i].position;
  28164. this.vertices[dst].normal = this.vertices[i].normal;
  28165. this.vertices[dst].uv = this.vertices[i].uv;
  28166. this.vertices[dst].color = this.vertices[i].color;
  28167. newVerticesOrder.push(i);
  28168. dst++;
  28169. }
  28170. }
  28171. for (i = 0; i < newTriangles.length; ++i) {
  28172. t = newTriangles[i];
  28173. for (j = 0; j < 3; ++j) {
  28174. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28175. }
  28176. }
  28177. this.vertices = this.vertices.slice(0, dst);
  28178. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28179. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28180. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28181. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28182. for (i = 0; i < newVerticesOrder.length; ++i) {
  28183. newPositionData.push(this.vertices[i].position.x);
  28184. newPositionData.push(this.vertices[i].position.y);
  28185. newPositionData.push(this.vertices[i].position.z);
  28186. newNormalData.push(this.vertices[i].normal.x);
  28187. newNormalData.push(this.vertices[i].normal.y);
  28188. newNormalData.push(this.vertices[i].normal.z);
  28189. if (this.vertices[i].uv) {
  28190. newUVsData.push(this.vertices[i].uv.x);
  28191. newUVsData.push(this.vertices[i].uv.y);
  28192. }
  28193. else if (this.vertices[i].color) {
  28194. newColorsData.push(this.vertices[i].color.r);
  28195. newColorsData.push(this.vertices[i].color.g);
  28196. newColorsData.push(this.vertices[i].color.b);
  28197. newColorsData.push(this.vertices[i].color.a);
  28198. }
  28199. }
  28200. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28201. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28202. var submeshesArray = this._reconstructedMesh.subMeshes;
  28203. this._reconstructedMesh.subMeshes = [];
  28204. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28205. for (i = 0; i < newTriangles.length; ++i) {
  28206. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28207. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28208. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28209. }
  28210. //overwriting the old vertex buffers and indices.
  28211. this._reconstructedMesh.setIndices(newIndicesArray);
  28212. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28213. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28214. if (newUVsData.length > 0)
  28215. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28216. if (newColorsData.length > 0)
  28217. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28218. //create submesh
  28219. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28220. if (submeshIndex > 0) {
  28221. this._reconstructedMesh.subMeshes = [];
  28222. submeshesArray.forEach(function (submesh) {
  28223. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28224. });
  28225. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28226. }
  28227. };
  28228. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28229. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28230. this._reconstructedMesh.material = this._mesh.material;
  28231. this._reconstructedMesh.parent = this._mesh.parent;
  28232. this._reconstructedMesh.isVisible = false;
  28233. };
  28234. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28235. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28236. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28237. if (t.deleted)
  28238. continue;
  28239. var s = this.references[vertex1.triangleStart + i].vertexId;
  28240. var id1 = t.vertices[(s + 1) % 3];
  28241. var id2 = t.vertices[(s + 2) % 3];
  28242. if ((id1 === index2 || id2 === index2)) {
  28243. deletedArray[i] = true;
  28244. delTr.push(t);
  28245. continue;
  28246. }
  28247. var d1 = this.vertices[id1].position.subtract(point);
  28248. d1 = d1.normalize();
  28249. var d2 = this.vertices[id2].position.subtract(point);
  28250. d2 = d2.normalize();
  28251. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28252. return true;
  28253. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28254. deletedArray[i] = false;
  28255. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28256. return true;
  28257. }
  28258. return false;
  28259. };
  28260. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28261. var newDeleted = deletedTriangles;
  28262. for (var i = 0; i < vertex.triangleCount; ++i) {
  28263. var ref = this.references[vertex.triangleStart + i];
  28264. var t = this.triangles[ref.triangleId];
  28265. if (t.deleted)
  28266. continue;
  28267. if (deletedArray[i]) {
  28268. t.deleted = true;
  28269. newDeleted++;
  28270. continue;
  28271. }
  28272. t.vertices[ref.vertexId] = vertexId;
  28273. t.isDirty = true;
  28274. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28275. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28276. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28277. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28278. this.references.push(ref);
  28279. }
  28280. return newDeleted;
  28281. };
  28282. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28283. for (var i = 0; i < this.vertices.length; ++i) {
  28284. var vCount = [];
  28285. var vId = [];
  28286. var v = this.vertices[i];
  28287. var j;
  28288. for (j = 0; j < v.triangleCount; ++j) {
  28289. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28290. for (var ii = 0; ii < 3; ii++) {
  28291. var ofs = 0;
  28292. var id = triangle.vertices[ii];
  28293. while (ofs < vCount.length) {
  28294. if (vId[ofs] === id)
  28295. break;
  28296. ++ofs;
  28297. }
  28298. if (ofs === vCount.length) {
  28299. vCount.push(1);
  28300. vId.push(id);
  28301. }
  28302. else {
  28303. vCount[ofs]++;
  28304. }
  28305. }
  28306. }
  28307. for (j = 0; j < vCount.length; ++j) {
  28308. if (vCount[j] === 1) {
  28309. this.vertices[vId[j]].isBorder = true;
  28310. }
  28311. else {
  28312. this.vertices[vId[j]].isBorder = false;
  28313. }
  28314. }
  28315. }
  28316. };
  28317. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28318. if (identifyBorders === void 0) { identifyBorders = false; }
  28319. var i;
  28320. if (!identifyBorders) {
  28321. var newTrianglesVector = [];
  28322. for (i = 0; i < this.triangles.length; ++i) {
  28323. if (!this.triangles[i].deleted) {
  28324. newTrianglesVector.push(this.triangles[i]);
  28325. }
  28326. }
  28327. this.triangles = newTrianglesVector;
  28328. }
  28329. for (i = 0; i < this.vertices.length; ++i) {
  28330. this.vertices[i].triangleCount = 0;
  28331. this.vertices[i].triangleStart = 0;
  28332. }
  28333. var t;
  28334. var j;
  28335. var v;
  28336. for (i = 0; i < this.triangles.length; ++i) {
  28337. t = this.triangles[i];
  28338. for (j = 0; j < 3; ++j) {
  28339. v = this.vertices[t.vertices[j]];
  28340. v.triangleCount++;
  28341. }
  28342. }
  28343. var tStart = 0;
  28344. for (i = 0; i < this.vertices.length; ++i) {
  28345. this.vertices[i].triangleStart = tStart;
  28346. tStart += this.vertices[i].triangleCount;
  28347. this.vertices[i].triangleCount = 0;
  28348. }
  28349. var newReferences = new Array(this.triangles.length * 3);
  28350. for (i = 0; i < this.triangles.length; ++i) {
  28351. t = this.triangles[i];
  28352. for (j = 0; j < 3; ++j) {
  28353. v = this.vertices[t.vertices[j]];
  28354. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28355. v.triangleCount++;
  28356. }
  28357. }
  28358. this.references = newReferences;
  28359. if (identifyBorders) {
  28360. this.identifyBorder();
  28361. }
  28362. };
  28363. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28364. var x = point.x;
  28365. var y = point.y;
  28366. var z = point.z;
  28367. 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];
  28368. };
  28369. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28370. var q = vertex1.q.add(vertex2.q);
  28371. var border = vertex1.isBorder && vertex2.isBorder;
  28372. var error = 0;
  28373. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28374. if (qDet !== 0 && !border) {
  28375. if (!pointResult) {
  28376. pointResult = BABYLON.Vector3.Zero();
  28377. }
  28378. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28379. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28380. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28381. error = this.vertexError(q, pointResult);
  28382. //TODO this should be correctly calculated
  28383. if (normalResult) {
  28384. normalResult.copyFrom(vertex1.normal);
  28385. if (vertex1.uv)
  28386. uvResult.copyFrom(vertex1.uv);
  28387. else if (vertex1.color)
  28388. colorResult.copyFrom(vertex1.color);
  28389. }
  28390. }
  28391. else {
  28392. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28393. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28394. var error1 = this.vertexError(q, vertex1.position);
  28395. var error2 = this.vertexError(q, vertex2.position);
  28396. var error3 = this.vertexError(q, p3);
  28397. error = Math.min(error1, error2, error3);
  28398. if (error === error1) {
  28399. if (pointResult) {
  28400. pointResult.copyFrom(vertex1.position);
  28401. normalResult.copyFrom(vertex1.normal);
  28402. if (vertex1.uv)
  28403. uvResult.copyFrom(vertex1.uv);
  28404. else if (vertex1.color)
  28405. colorResult.copyFrom(vertex1.color);
  28406. }
  28407. }
  28408. else if (error === error2) {
  28409. if (pointResult) {
  28410. pointResult.copyFrom(vertex2.position);
  28411. normalResult.copyFrom(vertex2.normal);
  28412. if (vertex2.uv)
  28413. uvResult.copyFrom(vertex2.uv);
  28414. else if (vertex2.color)
  28415. colorResult.copyFrom(vertex2.color);
  28416. }
  28417. }
  28418. else {
  28419. if (pointResult) {
  28420. pointResult.copyFrom(p3);
  28421. normalResult.copyFrom(vertex1.normal);
  28422. if (vertex1.uv)
  28423. uvResult.copyFrom(vertex1.uv);
  28424. else if (vertex1.color)
  28425. colorResult.copyFrom(vertex1.color);
  28426. }
  28427. }
  28428. }
  28429. return error;
  28430. };
  28431. return QuadraticErrorSimplification;
  28432. })();
  28433. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28434. })(BABYLON || (BABYLON = {}));
  28435. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28436. (function (BABYLON) {
  28437. var Analyser = (function () {
  28438. function Analyser(scene) {
  28439. this.SMOOTHING = 0.75;
  28440. this.FFT_SIZE = 512;
  28441. this.BARGRAPHAMPLITUDE = 256;
  28442. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28443. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28444. this._scene = scene;
  28445. this._audioEngine = BABYLON.Engine.audioEngine;
  28446. if (this._audioEngine.canUseWebAudio) {
  28447. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28448. this._webAudioAnalyser.minDecibels = -140;
  28449. this._webAudioAnalyser.maxDecibels = 0;
  28450. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28451. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28452. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28453. }
  28454. }
  28455. Analyser.prototype.getFrequencyBinCount = function () {
  28456. if (this._audioEngine.canUseWebAudio) {
  28457. return this._webAudioAnalyser.frequencyBinCount;
  28458. }
  28459. else {
  28460. return 0;
  28461. }
  28462. };
  28463. Analyser.prototype.getByteFrequencyData = function () {
  28464. if (this._audioEngine.canUseWebAudio) {
  28465. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28466. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28467. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28468. }
  28469. return this._byteFreqs;
  28470. };
  28471. Analyser.prototype.getByteTimeDomainData = function () {
  28472. if (this._audioEngine.canUseWebAudio) {
  28473. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28474. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28475. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28476. }
  28477. return this._byteTime;
  28478. };
  28479. Analyser.prototype.getFloatFrequencyData = function () {
  28480. if (this._audioEngine.canUseWebAudio) {
  28481. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28482. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28483. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28484. }
  28485. return this._floatFreqs;
  28486. };
  28487. Analyser.prototype.drawDebugCanvas = function () {
  28488. var _this = this;
  28489. if (this._audioEngine.canUseWebAudio) {
  28490. if (!this._debugCanvas) {
  28491. this._debugCanvas = document.createElement("canvas");
  28492. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28493. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28494. this._debugCanvas.style.position = "absolute";
  28495. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28496. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28497. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28498. document.body.appendChild(this._debugCanvas);
  28499. this._registerFunc = function () {
  28500. _this.drawDebugCanvas();
  28501. };
  28502. this._scene.registerBeforeRender(this._registerFunc);
  28503. }
  28504. if (this._registerFunc) {
  28505. var workingArray = this.getByteFrequencyData();
  28506. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28507. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28508. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28509. var value = workingArray[i];
  28510. var percent = value / this.BARGRAPHAMPLITUDE;
  28511. var height = this.DEBUGCANVASSIZE.height * percent;
  28512. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28513. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28514. var hue = i / this.getFrequencyBinCount() * 360;
  28515. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28516. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28517. }
  28518. }
  28519. }
  28520. };
  28521. Analyser.prototype.stopDebugCanvas = function () {
  28522. if (this._debugCanvas) {
  28523. this._scene.unregisterBeforeRender(this._registerFunc);
  28524. this._registerFunc = null;
  28525. document.body.removeChild(this._debugCanvas);
  28526. this._debugCanvas = null;
  28527. this._debugCanvasContext = null;
  28528. }
  28529. };
  28530. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28531. if (this._audioEngine.canUseWebAudio) {
  28532. inputAudioNode.connect(this._webAudioAnalyser);
  28533. this._webAudioAnalyser.connect(outputAudioNode);
  28534. }
  28535. };
  28536. Analyser.prototype.dispose = function () {
  28537. if (this._audioEngine.canUseWebAudio) {
  28538. this._webAudioAnalyser.disconnect();
  28539. }
  28540. };
  28541. return Analyser;
  28542. })();
  28543. BABYLON.Analyser = Analyser;
  28544. })(BABYLON || (BABYLON = {}));
  28545. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28546. (function (BABYLON) {
  28547. var DepthRenderer = (function () {
  28548. function DepthRenderer(scene, type) {
  28549. var _this = this;
  28550. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28551. this._viewMatrix = BABYLON.Matrix.Zero();
  28552. this._projectionMatrix = BABYLON.Matrix.Zero();
  28553. this._transformMatrix = BABYLON.Matrix.Zero();
  28554. this._worldViewProjection = BABYLON.Matrix.Zero();
  28555. this._scene = scene;
  28556. var engine = scene.getEngine();
  28557. // Render target
  28558. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28559. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28560. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28561. this._depthMap.refreshRate = 1;
  28562. this._depthMap.renderParticles = false;
  28563. this._depthMap.renderList = null;
  28564. // Custom render function
  28565. var renderSubMesh = function (subMesh) {
  28566. var mesh = subMesh.getRenderingMesh();
  28567. var scene = _this._scene;
  28568. var engine = scene.getEngine();
  28569. // Culling
  28570. engine.setState(subMesh.getMaterial().backFaceCulling);
  28571. // Managing instances
  28572. var batch = mesh._getInstancesRenderList(subMesh._id);
  28573. if (batch.mustReturn) {
  28574. return;
  28575. }
  28576. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28577. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28578. engine.enableEffect(_this._effect);
  28579. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28580. var material = subMesh.getMaterial();
  28581. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28582. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28583. // Alpha test
  28584. if (material && material.needAlphaTesting()) {
  28585. var alphaTexture = material.getAlphaTestTexture();
  28586. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28587. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28588. }
  28589. // Bones
  28590. if (mesh.useBones) {
  28591. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28592. }
  28593. // Draw
  28594. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28595. }
  28596. };
  28597. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28598. var index;
  28599. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28600. renderSubMesh(opaqueSubMeshes.data[index]);
  28601. }
  28602. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28603. renderSubMesh(alphaTestSubMeshes.data[index]);
  28604. }
  28605. };
  28606. }
  28607. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28608. var defines = [];
  28609. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28610. var mesh = subMesh.getMesh();
  28611. var scene = mesh.getScene();
  28612. var material = subMesh.getMaterial();
  28613. // Alpha test
  28614. if (material && material.needAlphaTesting()) {
  28615. defines.push("#define ALPHATEST");
  28616. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28617. attribs.push(BABYLON.VertexBuffer.UVKind);
  28618. defines.push("#define UV1");
  28619. }
  28620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28622. defines.push("#define UV2");
  28623. }
  28624. }
  28625. // Bones
  28626. if (mesh.useBones) {
  28627. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28628. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28629. defines.push("#define BONES");
  28630. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28631. }
  28632. // Instances
  28633. if (useInstances) {
  28634. defines.push("#define INSTANCES");
  28635. attribs.push("world0");
  28636. attribs.push("world1");
  28637. attribs.push("world2");
  28638. attribs.push("world3");
  28639. }
  28640. // Get correct effect
  28641. var join = defines.join("\n");
  28642. if (this._cachedDefines !== join) {
  28643. this._cachedDefines = join;
  28644. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28645. }
  28646. return this._effect.isReady();
  28647. };
  28648. DepthRenderer.prototype.getDepthMap = function () {
  28649. return this._depthMap;
  28650. };
  28651. // Methods
  28652. DepthRenderer.prototype.dispose = function () {
  28653. this._depthMap.dispose();
  28654. };
  28655. return DepthRenderer;
  28656. })();
  28657. BABYLON.DepthRenderer = DepthRenderer;
  28658. })(BABYLON || (BABYLON = {}));
  28659. //# sourceMappingURL=babylon.depthRenderer.js.map
  28660. var BABYLON;
  28661. (function (BABYLON) {
  28662. var SSAORenderingPipeline = (function (_super) {
  28663. __extends(SSAORenderingPipeline, _super);
  28664. /**
  28665. * @constructor
  28666. * @param {string} name - The rendering pipeline name
  28667. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28668. * @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)
  28669. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28670. */
  28671. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28672. var _this = this;
  28673. _super.call(this, scene.getEngine(), name);
  28674. // Members
  28675. /**
  28676. * The PassPostProcess id in the pipeline that contains the original scene color
  28677. * @type {string}
  28678. */
  28679. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28680. /**
  28681. * The SSAO PostProcess id in the pipeline
  28682. * @type {string}
  28683. */
  28684. this.SSAORenderEffect = "SSAORenderEffect";
  28685. /**
  28686. * The horizontal blur PostProcess id in the pipeline
  28687. * @type {string}
  28688. */
  28689. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28690. /**
  28691. * The vertical blur PostProcess id in the pipeline
  28692. * @type {string}
  28693. */
  28694. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28695. /**
  28696. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28697. * @type {string}
  28698. */
  28699. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28700. this._firstUpdate = true;
  28701. this._scene = scene;
  28702. // Set up assets
  28703. this._createRandomTexture();
  28704. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28705. var ssaoRatio = ratio.ssaoRatio || ratio;
  28706. var combineRatio = ratio.combineRatio || ratio;
  28707. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28708. this._createSSAOPostProcess(ssaoRatio);
  28709. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28710. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28711. this._createSSAOCombinePostProcess(combineRatio);
  28712. // Set up pipeline
  28713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28714. return _this._originalColorPostProcess;
  28715. }, true));
  28716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28717. return _this._ssaoPostProcess;
  28718. }, true));
  28719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28720. return _this._blurHPostProcess;
  28721. }, true));
  28722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28723. return _this._blurVPostProcess;
  28724. }, true));
  28725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28726. return _this._ssaoCombinePostProcess;
  28727. }, true));
  28728. // Finish
  28729. scene.postProcessRenderPipelineManager.addPipeline(this);
  28730. if (cameras)
  28731. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28732. }
  28733. // Public Methods
  28734. /**
  28735. * Returns the horizontal blur PostProcess
  28736. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28737. */
  28738. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28739. return this._blurHPostProcess;
  28740. };
  28741. /**
  28742. * Returns the vertical blur PostProcess
  28743. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28744. */
  28745. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28746. return this._blurVPostProcess;
  28747. };
  28748. /**
  28749. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28750. */
  28751. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28752. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28753. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28754. this._originalColorPostProcess = undefined;
  28755. this._ssaoPostProcess = undefined;
  28756. this._blurHPostProcess = undefined;
  28757. this._blurVPostProcess = undefined;
  28758. this._ssaoCombinePostProcess = undefined;
  28759. this._randomTexture.dispose();
  28760. if (disableDepthRender)
  28761. this._scene.disableDepthRenderer();
  28762. };
  28763. // Private Methods
  28764. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28765. var _this = this;
  28766. var sampleSphere = [
  28767. 0.5381,
  28768. 0.1856,
  28769. -0.4319,
  28770. 0.1379,
  28771. 0.2486,
  28772. 0.4430,
  28773. 0.3371,
  28774. 0.5679,
  28775. -0.0057,
  28776. -0.6999,
  28777. -0.0451,
  28778. -0.0019,
  28779. 0.0689,
  28780. -0.1598,
  28781. -0.8547,
  28782. 0.0560,
  28783. 0.0069,
  28784. -0.1843,
  28785. -0.0146,
  28786. 0.1402,
  28787. 0.0762,
  28788. 0.0100,
  28789. -0.1924,
  28790. -0.0344,
  28791. -0.3577,
  28792. -0.5301,
  28793. -0.4358,
  28794. -0.3169,
  28795. 0.1063,
  28796. 0.0158,
  28797. 0.0103,
  28798. -0.5869,
  28799. 0.0046,
  28800. -0.0897,
  28801. -0.4940,
  28802. 0.3287,
  28803. 0.7119,
  28804. -0.0154,
  28805. -0.0918,
  28806. -0.0533,
  28807. 0.0596,
  28808. -0.5411,
  28809. 0.0352,
  28810. -0.0631,
  28811. 0.5460,
  28812. -0.4776,
  28813. 0.2847,
  28814. -0.0271
  28815. ];
  28816. var samplesFactor = 1.0 / 16.0;
  28817. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28818. this._ssaoPostProcess.onApply = function (effect) {
  28819. if (_this._firstUpdate) {
  28820. effect.setArray3("sampleSphere", sampleSphere);
  28821. effect.setFloat("samplesFactor", samplesFactor);
  28822. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28823. _this._firstUpdate = false;
  28824. }
  28825. effect.setTexture("textureSampler", _this._depthTexture);
  28826. effect.setTexture("randomSampler", _this._randomTexture);
  28827. };
  28828. };
  28829. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28830. var _this = this;
  28831. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28832. this._ssaoCombinePostProcess.onApply = function (effect) {
  28833. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28834. };
  28835. };
  28836. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28837. var size = 512;
  28838. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28839. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28840. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28841. var context = this._randomTexture.getContext();
  28842. var rand = function (min, max) {
  28843. return Math.random() * (max - min) + min;
  28844. };
  28845. for (var x = 0; x < size; x++) {
  28846. for (var y = 0; y < size; y++) {
  28847. var randVector = BABYLON.Vector3.Zero();
  28848. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28849. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28850. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28851. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28852. context.fillRect(x, y, 1, 1);
  28853. }
  28854. }
  28855. this._randomTexture.update(false);
  28856. };
  28857. return SSAORenderingPipeline;
  28858. })(BABYLON.PostProcessRenderPipeline);
  28859. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28860. })(BABYLON || (BABYLON = {}));
  28861. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28862. var BABYLON;
  28863. (function (BABYLON) {
  28864. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28865. var VolumetricLightScatteringPostProcess = (function (_super) {
  28866. __extends(VolumetricLightScatteringPostProcess, _super);
  28867. /**
  28868. * @constructor
  28869. * @param {string} name - The post-process name
  28870. * @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)
  28871. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28872. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28873. * @param {number} samples - The post-process quality, default 100
  28874. * @param {number} samplingMode - The post-process filtering mode
  28875. * @param {BABYLON.Engine} engine - The babylon engine
  28876. * @param {boolean} reusable - If the post-process is reusable
  28877. */
  28878. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28879. var _this = this;
  28880. if (samples === void 0) { samples = 100; }
  28881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28882. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28883. this._screenCoordinates = BABYLON.Vector2.Zero();
  28884. /**
  28885. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28886. * @type {boolean}
  28887. */
  28888. this.useCustomMeshPosition = false;
  28889. /**
  28890. * If the post-process should inverse the light scattering direction
  28891. * @type {boolean}
  28892. */
  28893. this.invert = true;
  28894. /**
  28895. * Array containing the excluded meshes not rendered in the internal pass
  28896. */
  28897. this.excludedMeshes = new Array();
  28898. this.exposure = 0.3;
  28899. this.decay = 0.96815;
  28900. this.weight = 0.58767;
  28901. this.density = 0.926;
  28902. var scene = camera.getScene();
  28903. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28904. // Configure mesh
  28905. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28906. // Configure
  28907. this._createPass(scene, ratio.passRatio || ratio);
  28908. this.onApply = function (effect) {
  28909. _this._updateMeshScreenCoordinates(scene);
  28910. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28911. effect.setFloat("exposure", _this.exposure);
  28912. effect.setFloat("decay", _this.decay);
  28913. effect.setFloat("weight", _this.weight);
  28914. effect.setFloat("density", _this.density);
  28915. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28916. };
  28917. }
  28918. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28919. var mesh = subMesh.getMesh();
  28920. var defines = [];
  28921. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28922. var material = subMesh.getMaterial();
  28923. // Render this.mesh as default
  28924. if (mesh === this.mesh) {
  28925. defines.push("#define BASIC_RENDER");
  28926. }
  28927. // Alpha test
  28928. if (material) {
  28929. if (material.needAlphaTesting() || mesh === this.mesh)
  28930. defines.push("#define ALPHATEST");
  28931. if (material.opacityTexture !== undefined && mesh === this.mesh)
  28932. defines.push("#define OPACITY");
  28933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28934. attribs.push(BABYLON.VertexBuffer.UVKind);
  28935. defines.push("#define UV1");
  28936. }
  28937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28938. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28939. defines.push("#define UV2");
  28940. }
  28941. }
  28942. // Bones
  28943. if (mesh.useBones) {
  28944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28946. defines.push("#define BONES");
  28947. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28948. }
  28949. // Instances
  28950. if (useInstances) {
  28951. defines.push("#define INSTANCES");
  28952. attribs.push("world0");
  28953. attribs.push("world1");
  28954. attribs.push("world2");
  28955. attribs.push("world3");
  28956. }
  28957. // Get correct effect
  28958. var join = defines.join("\n");
  28959. if (this._cachedDefines !== join) {
  28960. this._cachedDefines = join;
  28961. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler", "opacitySampler"], join);
  28962. }
  28963. return this._volumetricLightScatteringPass.isReady();
  28964. };
  28965. /**
  28966. * Sets the new light position for light scattering effect
  28967. * @param {BABYLON.Vector3} The new custom light position
  28968. */
  28969. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28970. this._customMeshPosition = position;
  28971. };
  28972. /**
  28973. * Returns the light position for light scattering effect
  28974. * @return {BABYLON.Vector3} The custom light position
  28975. */
  28976. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28977. return this._customMeshPosition;
  28978. };
  28979. /**
  28980. * Disposes the internal assets and detaches the post-process from the camera
  28981. */
  28982. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28983. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28984. if (rttIndex !== -1) {
  28985. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28986. }
  28987. this._volumetricLightScatteringRTT.dispose();
  28988. _super.prototype.dispose.call(this, camera);
  28989. };
  28990. /**
  28991. * Returns the render target texture used by the post-process
  28992. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28993. */
  28994. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28995. return this._volumetricLightScatteringRTT;
  28996. };
  28997. // Private methods
  28998. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28999. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29000. return true;
  29001. }
  29002. return false;
  29003. };
  29004. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29005. var _this = this;
  29006. var engine = scene.getEngine();
  29007. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29008. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29009. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29010. this._volumetricLightScatteringRTT.renderList = null;
  29011. this._volumetricLightScatteringRTT.renderParticles = false;
  29012. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29013. // Custom render function for submeshes
  29014. var renderSubMesh = function (subMesh) {
  29015. var mesh = subMesh.getRenderingMesh();
  29016. if (_this._meshExcluded(mesh)) {
  29017. return;
  29018. }
  29019. var scene = mesh.getScene();
  29020. var engine = scene.getEngine();
  29021. // Culling
  29022. engine.setState(subMesh.getMaterial().backFaceCulling);
  29023. // Managing instances
  29024. var batch = mesh._getInstancesRenderList(subMesh._id);
  29025. if (batch.mustReturn) {
  29026. return;
  29027. }
  29028. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29029. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29030. engine.enableEffect(_this._volumetricLightScatteringPass);
  29031. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29032. var material = subMesh.getMaterial();
  29033. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29034. // Alpha test
  29035. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29036. var alphaTexture = material.getAlphaTestTexture();
  29037. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29038. if (alphaTexture) {
  29039. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29040. }
  29041. if (material.opacityTexture !== undefined)
  29042. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29043. }
  29044. // Bones
  29045. if (mesh.useBones) {
  29046. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29047. }
  29048. // Draw
  29049. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29050. }
  29051. };
  29052. // Render target texture callbacks
  29053. var savedSceneClearColor;
  29054. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29055. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29056. savedSceneClearColor = scene.clearColor;
  29057. scene.clearColor = sceneClearColor;
  29058. };
  29059. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29060. scene.clearColor = savedSceneClearColor;
  29061. };
  29062. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29063. var index;
  29064. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29065. renderSubMesh(opaqueSubMeshes.data[index]);
  29066. }
  29067. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29068. renderSubMesh(alphaTestSubMeshes.data[index]);
  29069. }
  29070. for (index = 0; index < transparentSubMeshes.length; index++) {
  29071. renderSubMesh(transparentSubMeshes.data[index]);
  29072. }
  29073. };
  29074. };
  29075. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29076. var transform = scene.getTransformMatrix();
  29077. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29078. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29079. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29080. if (this.invert)
  29081. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29082. };
  29083. // Static methods
  29084. /**
  29085. * Creates a default mesh for the Volumeric Light Scattering post-process
  29086. * @param {string} The mesh name
  29087. * @param {BABYLON.Scene} The scene where to create the mesh
  29088. * @return {BABYLON.Mesh} the default mesh
  29089. */
  29090. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29091. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29092. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29093. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29094. return mesh;
  29095. };
  29096. return VolumetricLightScatteringPostProcess;
  29097. })(BABYLON.PostProcess);
  29098. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29099. })(BABYLON || (BABYLON = {}));
  29100. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29101. var BABYLON;
  29102. (function (BABYLON) {
  29103. var LensRenderingPipeline = (function (_super) {
  29104. __extends(LensRenderingPipeline, _super);
  29105. /**
  29106. * @constructor
  29107. * @param {string} name - The rendering pipeline name
  29108. * @param {object} parameters - An object containing all parameters (see below)
  29109. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29110. * @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)
  29111. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29112. Effect parameters are as follow:
  29113. {
  29114. chromatic_aberration: number; // from 0 to x (1 for realism)
  29115. edge_blur: number; // from 0 to x (1 for realism)
  29116. distortion: number; // from 0 to x (1 for realism)
  29117. grain_amount: number; // from 0 to 1
  29118. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29119. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29120. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29121. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29122. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29123. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29124. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29125. }
  29126. Note: if an effect parameter is unset, effect is disabled
  29127. */
  29128. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29129. var _this = this;
  29130. if (ratio === void 0) { ratio = 1.0; }
  29131. _super.call(this, scene.getEngine(), name);
  29132. // Lens effects can be of the following:
  29133. // - chromatic aberration (slight shift of RGB colors)
  29134. // - blur on the edge of the lens
  29135. // - lens distortion
  29136. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29137. // - grain/dust-on-lens effect
  29138. // Two additional texture samplers are needed:
  29139. // - depth map (for depth-of-field)
  29140. // - grain texture
  29141. /**
  29142. * The chromatic aberration PostProcess id in the pipeline
  29143. * @type {string}
  29144. */
  29145. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29146. /**
  29147. * The depth-of-field PostProcess id in the pipeline
  29148. * @type {string}
  29149. */
  29150. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29151. this._scene = scene;
  29152. // Fetch texture samplers
  29153. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29154. if (parameters.grain_texture) {
  29155. this._grainTexture = parameters.grain_texture;
  29156. }
  29157. else {
  29158. this._createGrainTexture();
  29159. }
  29160. // save parameters
  29161. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29162. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29163. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29164. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29165. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29166. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29167. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29168. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29169. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29170. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29171. // Create effects
  29172. this._createChromaticAberrationPostProcess(ratio);
  29173. this._createDepthOfFieldPostProcess(ratio);
  29174. // Set up pipeline
  29175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29176. return _this._chromaticAberrationPostProcess;
  29177. }, true));
  29178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29179. return _this._depthOfFieldPostProcess;
  29180. }, true));
  29181. // Finish
  29182. scene.postProcessRenderPipelineManager.addPipeline(this);
  29183. if (cameras) {
  29184. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29185. }
  29186. }
  29187. // public methods
  29188. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29189. this._edgeBlur = amount;
  29190. };
  29191. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29192. this._edgeBlur = 0;
  29193. };
  29194. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29195. this._grainAmount = amount;
  29196. };
  29197. LensRenderingPipeline.prototype.disableGrain = function () {
  29198. this._grainAmount = 0;
  29199. };
  29200. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29201. this._chromaticAberration = amount;
  29202. };
  29203. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29204. this._chromaticAberration = 0;
  29205. };
  29206. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29207. this._distortion = amount;
  29208. };
  29209. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29210. this._distortion = 0;
  29211. };
  29212. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29213. this._highlightsGain = amount;
  29214. };
  29215. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29216. this._highlightsThreshold = amount;
  29217. };
  29218. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29219. this._dofDepth = amount;
  29220. };
  29221. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29222. this._dofDepth = -1;
  29223. };
  29224. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29225. this._dofAperture = amount;
  29226. };
  29227. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29228. this._dofPentagon = true;
  29229. };
  29230. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29231. this._dofPentagon = false;
  29232. };
  29233. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29234. this._blurNoise = true;
  29235. };
  29236. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29237. this._blurNoise = false;
  29238. };
  29239. /**
  29240. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29241. */
  29242. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29243. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29244. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29245. this._chromaticAberrationPostProcess = undefined;
  29246. this._depthOfFieldPostProcess = undefined;
  29247. this._grainTexture.dispose();
  29248. if (disableDepthRender)
  29249. this._scene.disableDepthRenderer();
  29250. };
  29251. // colors shifting and distortion
  29252. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29253. var _this = this;
  29254. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29255. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29256. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29257. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29258. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29259. };
  29260. };
  29261. // colors shifting and distortion
  29262. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29263. var _this = this;
  29264. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29265. "gain",
  29266. "threshold",
  29267. "focus_depth",
  29268. "aperture",
  29269. "pentagon",
  29270. "maxZ",
  29271. "edge_blur",
  29272. "chromatic_aberration",
  29273. "distortion",
  29274. "blur_noise",
  29275. "grain_amount",
  29276. "screen_width",
  29277. "screen_height"
  29278. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29279. this._depthOfFieldPostProcess.onApply = function (effect) {
  29280. effect.setBool('pentagon', _this._dofPentagon);
  29281. effect.setBool('blur_noise', _this._blurNoise);
  29282. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29283. effect.setFloat('grain_amount', _this._grainAmount);
  29284. effect.setTexture("depthSampler", _this._depthTexture);
  29285. effect.setTexture("grainSampler", _this._grainTexture);
  29286. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29287. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29288. effect.setFloat('distortion', _this._distortion);
  29289. effect.setFloat('focus_depth', _this._dofDepth);
  29290. effect.setFloat('aperture', _this._dofAperture);
  29291. effect.setFloat('gain', _this._highlightsGain);
  29292. effect.setFloat('threshold', _this._highlightsThreshold);
  29293. effect.setFloat('edge_blur', _this._edgeBlur);
  29294. };
  29295. };
  29296. // creates a black and white random noise texture, 512x512
  29297. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29298. var size = 512;
  29299. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29300. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29301. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29302. var context = this._grainTexture.getContext();
  29303. var rand = function (min, max) {
  29304. return Math.random() * (max - min) + min;
  29305. };
  29306. var value;
  29307. for (var x = 0; x < size; x++) {
  29308. for (var y = 0; y < size; y++) {
  29309. value = Math.floor(rand(0.42, 0.58) * 255);
  29310. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29311. context.fillRect(x, y, 1, 1);
  29312. }
  29313. }
  29314. this._grainTexture.update(false);
  29315. };
  29316. return LensRenderingPipeline;
  29317. })(BABYLON.PostProcessRenderPipeline);
  29318. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29319. })(BABYLON || (BABYLON = {}));
  29320. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29321. // This post-process allows the modification of rendered colors by using
  29322. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29323. //
  29324. // The object needs to be provided an url to a texture containing the color
  29325. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29326. // Use an image editing software to tweak the LUT to match your needs.
  29327. //
  29328. // For an example of a color LUT, see here:
  29329. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29330. // For explanations on color grading, see here:
  29331. // http://udn.epicgames.com/Three/ColorGrading.html
  29332. //
  29333. var BABYLON;
  29334. (function (BABYLON) {
  29335. var ColorCorrectionPostProcess = (function (_super) {
  29336. __extends(ColorCorrectionPostProcess, _super);
  29337. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29338. var _this = this;
  29339. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29340. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29341. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29342. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29343. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29344. this.onApply = function (effect) {
  29345. effect.setTexture("colorTable", _this._colorTableTexture);
  29346. };
  29347. }
  29348. return ColorCorrectionPostProcess;
  29349. })(BABYLON.PostProcess);
  29350. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29351. })(BABYLON || (BABYLON = {}));
  29352. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map